text:
'use strict';var lang_1 = require('angular2/src/facade/lang');
exports.DOM;
function setRootDomAdapter(adapter) {
    if (lang_1.isBlank(exports.DOM)) {
        exports.DOM = adapter;
    }
}
exports.setRootDomAdapter = setRootDomAdapter;
function _abstract() {
    return new lang_1.BaseException('This method is abstract');
}
/* tslint:disable:requireParameterType */
/**
 * Provides DOM operations in an environment-agnostic way.
 */
var DomAdapter = (function () {
    function DomAdapter() {
    }
    DomAdapter.prototype.hasProperty = function (element, name) { throw _abstract(); };
    DomAdapter.prototype.setProperty = function (el, name, value) { throw _abstract(); };
    DomAdapter.prototype.getProperty = function (el, name) { throw _abstract(); };
    DomAdapter.prototype.invoke = function (el, methodName, args) { throw _abstract(); };
    DomAdapter.prototype.logError = function (error) { throw _abstract(); };
    DomAdapter.prototype.log = function (error) { throw _abstract(); };
    DomAdapter.prototype.logGroup = function (error) { throw _abstract(); };
    DomAdapter.prototype.logGroupEnd = function () { throw _abstract(); };
    Object.defineProperty(DomAdapter.prototype, "attrToPropMap", {
        /**
         * Maps attribute names to their corresponding property names for cases
         * where attribute name doesn't match property name.
         */
        get: function () { throw _abstract(); },
        enumerable: true,
        configurable: true
    });
    DomAdapter.prototype.parse = function (templateHtml) { throw _abstract(); };
    DomAdapter.prototype.query = function (selector) { throw _abstract(); };
    DomAdapter.prototype.querySelector = function (el, selector) { throw _abstract(); };
    DomAdapter.prototype.querySelectorAll = function (el, selector) { throw _abstract(); };
    DomAdapter.prototype.on = function (el, evt, listener) { throw _abstract(); };
    DomAdapter.prototype.onAndCancel = function (el, evt, listener) { throw _abstract(); };
    DomAdapter.prototype.dispatchEvent = function (el, evt) { throw _abstract(); };
    DomAdapter.prototype.createMouseEvent = function (eventType) { throw _abstract(); };
    DomAdapter.prototype.createEvent = function (eventType) { throw _abstract(); };
    DomAdapter.prototype.preventDefault = function (evt) { throw _abstract(); };
    DomAdapter.prototype.getInnerHTML = function (el) { throw _abstract(); };
    DomAdapter.prototype.getOuterHTML = function (el) { throw _abstract(); };
    DomAdapter.prototype.nodeName = function (node) { throw _abstract(); };
    DomAdapter.prototype.nodeValue = function (node) { throw _abstract(); };
    DomAdapter.prototype.type = function (node) { throw _abstract(); };
    DomAdapter.prototype.content = function (node) { throw _abstract(); };
    DomAdapter.prototype.firstChild = function (el) { throw _abstract(); };
    DomAdapter.prototype.nextSibling = function (el) { throw _abstract(); };
    DomAdapter.prototype.parentElement = function (el) { throw _abstract(); };
    DomAdapter.prototype.childNodes = function (el) { throw _abstract(); };
    DomAdapter.prototype.childNodesAsList = function (el) { throw _abstract(); };
    DomAdapter.prototype.clearNodes = function (el) { throw _abstract(); };
    DomAdapter.prototype.appendChild = function (el, node) { throw _abstract(); };
    DomAdapter.prototype.removeChild = function (el, node) { throw _abstract(); };
    DomAdapter.prototype.replaceChild = function (el, newNode, oldNode) { throw _abstract(); };
    DomAdapter.prototype.remove = function (el) { throw _abstract(); };
    DomAdapter.prototype.insertBefore = function (el, node) { throw _abstract(); };
    DomAdapter.prototype.insertAllBefore = function (el, nodes) { throw _abstract(); };
    DomAdapter.prototype.insertAfter = function (el, node) { throw _abstract(); };
    DomAdapter.prototype.setInnerHTML = function (el, value) { throw _abstract(); };
    DomAdapter.prototype.getText = function (el) { throw _abstract(); };
    DomAdapter.prototype.setText = function (el, value) { throw _abstract(); };
    DomAdapter.prototype.getValue = function (el) { throw _abstract(); };
    DomAdapter.prototype.setValue = function (el, value) { throw _abstract(); };
    DomAdapter.prototype.getChecked = function (el) { throw _abstract(); };
    DomAdapter.prototype.setChecked = function (el, value) { throw _abstract(); };
    DomAdapter.prototype.createTemplate = function (html) { throw _abstract(); };
    DomAdapter.prototype.createElement = function (tagName, doc) {
        if (doc === void 0) { doc = null; }
        throw _abstract();
    };
    DomAdapter.prototype.createTextNode = function (text, doc) {
        if (doc === void 0) { doc = null; }
        throw _abstract();
    };
    DomAdapter.prototype.createScriptTag = function (attrName, attrValue, doc) {
        if (doc === void 0) { doc = null; }
        throw _abstract();
    };
    DomAdapter.prototype.createStyleElement = function (css, doc) {
        if (doc === void 0) { doc = null; }
        throw _abstract();
    };
    DomAdapter.prototype.createShadowRoot = function (el) { throw _abstract(); };
    DomAdapter.prototype.getShadowRoot = function (el) { throw _abstract(); };
    DomAdapter.prototype.getHost = function (el) { throw _abstract(); };
    DomAdapter.prototype.getDistributedNodes = function (el) { throw _abstract(); };
    DomAdapter.prototype.clone /*<T extends Node>*/ = function (node /*T*/) { throw _abstract(); };
    DomAdapter.prototype.getElementsByClassName = function (element, name) { throw _abstract(); };
    DomAdapter.prototype.getElementsByTagName = function (element, name) { throw _abstract(); };
    DomAdapter.prototype.classList = function (element) { throw _abstract(); };
    DomAdapter.prototype.addClass = function (element, classname) { throw _abstract(); };
    DomAdapter.prototype.removeClass = function (element, classname) { throw _abstract(); };
    DomAdapter.prototype.hasClass = function (element, classname) { throw _abstract(); };
    DomAdapter.prototype.setStyle = function (element, stylename, stylevalue) { throw _abstract(); };
    DomAdapter.prototype.removeStyle = function (element, stylename) { throw _abstract(); };
    DomAdapter.prototype.getStyle = function (element, stylename) { throw _abstract(); };
    DomAdapter.prototype.tagName = function (element) { throw _abstract(); };
    DomAdapter.prototype.attributeMap = function (element) { throw _abstract(); };
    DomAdapter.prototype.hasAttribute = function (element, attribute) { throw _abstract(); };
    DomAdapter.prototype.getAttribute = function (element, attribute) { throw _abstract(); };
    DomAdapter.prototype.setAttribute = function (element, name, value) { throw _abstract(); };
    DomAdapter.prototype.removeAttribute = function (element, attribute) { throw _abstract(); };
    DomAdapter.prototype.templateAwareRoot = function (el) { throw _abstract(); };
    DomAdapter.prototype.createHtmlDocument = function () { throw _abstract(); };
    DomAdapter.prototype.defaultDoc = function () { throw _abstract(); };
    DomAdapter.prototype.getBoundingClientRect = function (el) { throw _abstract(); };
    DomAdapter.prototype.getTitle = function () { throw _abstract(); };
    DomAdapter.prototype.setTitle = function (newTitle) { throw _abstract(); };
    DomAdapter.prototype.elementMatches = function (n, selector) { throw _abstract(); };
    DomAdapter.prototype.isTemplateElement = function (el) { throw _abstract(); };
    DomAdapter.prototype.isTextNode = function (node) { throw _abstract(); };
    DomAdapter.prototype.isCommentNode = function (node) { throw _abstract(); };
    DomAdapter.prototype.isElementNode = function (node) { throw _abstract(); };
    DomAdapter.prototype.hasShadowRoot = function (node) { throw _abstract(); };
    DomAdapter.prototype.isShadowRoot = function (node) { throw _abstract(); };
    DomAdapter.prototype.importIntoDoc /*<T extends Node>*/ = function (node /*T*/) { throw _abstract(); };
    DomAdapter.prototype.isPageRule = function (rule) { throw _abstract(); };
    DomAdapter.prototype.isStyleRule = function (rule) { throw _abstract(); };
    DomAdapter.prototype.isMediaRule = function (rule) { throw _abstract(); };
    DomAdapter.prototype.isKeyframesRule = function (rule) { throw _abstract(); };
    DomAdapter.prototype.getHref = function (element) { throw _abstract(); };
    DomAdapter.prototype.getEventKey = function (event) { throw _abstract(); };
    DomAdapter.prototype.resolveAndSetHref = function (element, baseUrl, href) { throw _abstract(); };
    DomAdapter.prototype.cssToRules = function (css) { throw _abstract(); };
    DomAdapter.prototype.supportsDOMEvents = function () { throw _abstract(); };
    DomAdapter.prototype.supportsNativeShadowDOM = function () { throw _abstract(); };
    DomAdapter.prototype.getGlobalEventTarget = function (target) { throw _abstract(); };
    DomAdapter.prototype.getHistory = function () { throw _abstract(); };
    DomAdapter.prototype.getLocation = function () { throw _abstract(); };
    DomAdapter.prototype.getBaseHref = function () { throw _abstract(); };
    DomAdapter.prototype.getUserAgent = function () { throw _abstract(); };
    DomAdapter.prototype.setData = function (element, name, value) { throw _abstract(); };
    DomAdapter.prototype.getData = function (element, name) { throw _abstract(); };
    DomAdapter.prototype.setGlobalVar = function (name, value) { throw _abstract(); };
    return DomAdapter;
})();
exports.DomAdapter = DomAdapter;
//# sourceMappingURL=dom_adapter.js.map


text:
package com.amazonaws.services.iotanalytics.model.transform;

import java.math.*;
import java.nio.ByteBuffer;
import javax.annotation.Generated;

import com.amazonaws.services.iotanalytics.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * RunPipelineActivityResult JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class RunPipelineActivityResultJsonUnmarshaller implements Unmarshaller<RunPipelineActivityResult, JsonUnmarshallerContext> {

    public RunPipelineActivityResult unmarshall(JsonUnmarshallerContext context) throws Exception {
        RunPipelineActivityResult runPipelineActivityResult = new RunPipelineActivityResult();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return runPipelineActivityResult;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("payloads", targetDepth)) {
                    context.nextToken();
                    runPipelineActivityResult.setPayloads(new ListUnmarshaller<java.nio.ByteBuffer>(context.getUnmarshaller(java.nio.ByteBuffer.class))

                    .unmarshall(context));
                }
                if (context.testExpression("logResult", targetDepth)) {
                    context.nextToken();
                    runPipelineActivityResult.setLogResult(context.getUnmarshaller(String.class).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return runPipelineActivityResult;
    }

    private static RunPipelineActivityResultJsonUnmarshaller instance;

    public static RunPipelineActivityResultJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new RunPipelineActivityResultJsonUnmarshaller();
        return instance;
    }
}

redpajama_set_name: RedPajamaGithub


text:
/*
Unique Paths
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

How many possible unique paths are there?

Above is a 3 x 7 grid. How many possible unique paths are there?

Note: m and n will be at most 100.

Hide Tags Array Dynamic Programming
Hide Similar Problems (M) Unique Paths II (M) Minimum Path Sum (H) Dungeon Game
*/
public class Solution {
    public int uniquePaths(int m, int n) {
        if(m<0 || n<0)return 0;
        int[][] dp = new int[m][n];
        dp[0][0]=1;
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                if(!(i==0 && j==0)){
                    if(i-1>=0 && i-1<=n)dp[j][i]+=dp[j][i-1];
                    if(j-1>=0 && j-1<=m)dp[j][i]+=dp[j-1][i];
                }
            }
        }
        return dp[m-1][n-1];
    }
}


text:
FROM golang:1.9

RUN curl -LO https://storage.googleapis.com/kubernetes-release/release/v1.8.2/bin/linux/amd64/kubectl \
    && chmod +x ./kubectl \
    && mv ./kubectl /usr/local/bin/kubectl

ADD ./ /go/src/github.com/coreos/vault-operator

WORKDIR /go/src/github.com/coreos/vault-operator

RUN rm -rf _output _test .git .gitignore


text:
import * as gulp from 'gulp';
import * as gulpLoadPlugins from 'gulp-load-plugins';
import * as merge from 'merge-stream';
import * as autoprefixer from 'autoprefixer';
import * as cssnano from 'cssnano';
import {join} from 'path';
import * as buildConfig from '../../config';
const plugins = <any>gulpLoadPlugins();

const processors = [
  autoprefixer({
    browsers: buildConfig.BROWSER_LIST
  })
];

const isProd = buildConfig.ENV === 'prod';

if (isProd) {
  processors.push(
    cssnano({
      discardComments: {removeAll: true}
    })
  );
}

function prepareTemplates() {
  return gulp.src(join(buildConfig.APP_SRC, '**', '*.html'))
    .pipe(gulp.dest(buildConfig.TMP_DIR));
}

function processComponentCss() {
  return gulp.src([
      join(buildConfig.APP_SRC, '**', '*.css'),
      '!' + join(buildConfig.APP_SRC, 'assets', '**', '*.css')
    ])
    .pipe(isProd ? plugins.cached('process-component-css') : plugins.util.noop())
    .pipe(plugins.postcss(processors))
    .pipe(gulp.dest(isProd ? buildConfig.TMP_DIR: buildConfig.APP_DEST));
}

function processExternalCss() {
  return gulp.src(getExternalCss().map(r => r.src))
    .pipe(isProd ? plugins.cached('process-external-css') : plugins.util.noop())
    .pipe(plugins.postcss(processors))
    .pipe(isProd ? plugins.concat(buildConfig.CSS_PROD_BUNDLE) : plugins.util.noop())
    .pipe(gulp.dest(buildConfig.CSS_DEST));
}

function getExternalCss() {
  return buildConfig.DEPENDENCIES.filter(d => /\.css$/.test(d.src));
}

export = () => merge(processComponentCss(), prepareTemplates(), processExternalCss());


text:
package org.araymond.joal.core.bandwith.weight;

import org.araymond.joal.core.bandwith.Peers;

public class PeersAwareWeightCalculator {
    public double calculate(final Peers peers) {
        final double leechersRatio = peers.getLeechersRatio();
        return (peers.getSeeders() == 0 || leechersRatio == 0)
                ? 0.0
                : leechersRatio * 100 * leechersRatio * peers.getLeechers();
    }
}


text:
package ai.verta.swagger._public.modeldb.metadata.model

import scala.util.Try

import net.liftweb.json._

import ai.verta.swagger._public.modeldb.metadata.model.IDTypeEnumIDType._
import ai.verta.swagger._public.modeldb.metadata.model.OperatorEnumOperator._
import ai.verta.swagger.client.objects._

case class MetadataAddKeyValuePropertiesRequest (
  id: Option[MetadataIdentificationType] = None,
  key_value_property: Option[List[MetadataKeyValueStringProperty]] = None,
  property_name: Option[String] = None
) extends BaseSwagger {
  def toJson(): JValue = MetadataAddKeyValuePropertiesRequest.toJson(this)
}

object MetadataAddKeyValuePropertiesRequest {
  def toJson(obj: MetadataAddKeyValuePropertiesRequest): JObject = {
    new JObject(
      List[Option[JField]](
        obj.id.map(x => JField("id", ((x: MetadataIdentificationType) => MetadataIdentificationType.toJson(x))(x))),
        obj.key_value_property.map(x => JField("key_value_property", ((x: List[MetadataKeyValueStringProperty]) => JArray(x.map(((x: MetadataKeyValueStringProperty) => MetadataKeyValueStringProperty.toJson(x)))))(x))),
        obj.property_name.map(x => JField("property_name", JString(x)))
      ).flatMap(x => x match {
        case Some(y) => List(y)
        case None => Nil
      })
    )
  }

  def fromJson(value: JValue): MetadataAddKeyValuePropertiesRequest =
    value match {
      case JObject(fields) => {
        val fieldsMap = fields.map(f => (f.name, f.value)).toMap
        MetadataAddKeyValuePropertiesRequest(
          // TODO: handle required
          id = fieldsMap.get("id").map(MetadataIdentificationType.fromJson),
          key_value_property = fieldsMap.get("key_value_property").map((x: JValue) => x match {case JArray(elements) => elements.map(MetadataKeyValueStringProperty.fromJson); case _ => throw new IllegalArgumentException(s"unknown type ${x.getClass.toString}")}),
          property_name = fieldsMap.get("property_name").map(JsonConverter.fromJsonString)
        )
      }
      case _ => throw new IllegalArgumentException(s"unknown type ${value.getClass.toString}")
    }
}


text:
<?php

App::uses('AfigestionAppController', 'Afigestion.Controller');

/**
 * Base Application Controller
 *
 * @package  Croogo
 * @link     http://www.croogo.org
 */
class AppController extends AfigestionAppController {

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Tokens version="1.0">
	<File path="Classes/CCActionEaseIn.html">

		<Token>
			<TokenIdentifier>//apple_ref/occ/cl/CCActionEaseIn</TokenIdentifier>
			<Abstract type="html">CCEaseIn action with a rate</Abstract>
			<DeclaredIn>CCActionEase.h</DeclaredIn>

			<NodeRef refid="24"/>
		</Token>

	</File>
</Tokens>


text:
package com.opengamma.integration.tool.portfolio;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opengamma.component.tool.AbstractTool;
import com.opengamma.financial.tool.ToolContext;
import com.opengamma.scripts.Scriptable;

/**
 * Tool to delete positions that are not currently in a portfolio.
 */
@Scriptable
public class OrphanedPositionDeleteTool extends AbstractTool<ToolContext> {

  /** Logger */
  private static final Logger LOGGER = LoggerFactory.getLogger(OrphanedPositionDeleteTool.class);

  // -------------------------------------------------------------------------
  /**
   * Main method to run the tool.
   *
   * @param args
   *          the standard tool arguments, not null
   */
  public static void main(final String[] args) { // CSIGNORE
    new OrphanedPositionDeleteTool().invokeAndTerminate(args);
  }

  // -------------------------------------------------------------------------
  @Override
  protected void doRun() throws Exception {
    final ToolContext toolContext = getToolContext();
    final OrphanedPositionRemover orphanedPositionRemover = new OrphanedPositionRemover(toolContext.getPortfolioMaster(), toolContext.getPositionMaster());
    LOGGER.info("running orphanedPositionRemover");
    orphanedPositionRemover.run();
    toolContext.close();
  }

}


text:
package org.rioproject.servicebean;

/**
 * The ServiceBeanState provides information on the lifecycle of a ServiceBean
 *
 * @author Dennis Reedy
 */
public class ServiceBeanState {
    /**
     * ServiceBean is inactive
     */
    public static final int INACTIVE = 0;
    /**
     * ServiceBean is starting
     */
    public static final int STARTING = 1;
    /**
     * ServiceBean has been initialized
     */
    public static final int INITIALIZED = 2;
    /**
     * ServiceBean has been stopped
     */
    public static final int STOPPED = 3;
    /**
     * ServiceBean has been started
     */
    public static final int STARTED = 4;
    /**
     * ServiceBean has been unadvertised
     */
    public static final int UNADVERTISED = 5;
    /**
     * ServiceBean has been advertised
     */
    public static final int ADVERTISED = 6;
    /**
     * ServiceBean has been advertised
     */
    public static final int ABORTED = 7;
    /**
     * The current state
     */
    private int state;

    /**
     * Create a ServiceBeanState object
     */
    public ServiceBeanState() {
        state = INACTIVE;
    }

    /**
     * Get the current state of the ServiceBean
     *
     * @return The state of the ServiceBean
     */
    public int getState() {
        int theState;
        synchronized(this) {
            theState = state;
        }
        return (theState);
    }

    /**
     * Set the state of the ServiceBean
     *
     * @param newState The new state
     *
     * @throws IllegalStateException if the newState is not a valid
     * state
     */
    public void setState(int newState) {
        if(newState == getState())
            return;
        if(newState < 0 || newState > ABORTED)
            throw new IllegalStateException("newState out of bounds ["
                                            + newState
                                            + "]");
        synchronized(this) {
            verifyTransition(newState);
            state = newState;
        }
    }

    /**
     * Verify the state transition, checking if the proposed new state is
     * allowed from the current state. If the proposed state is not allowed an
     * IllegalStateException will be thrown
     *
     * @param newState The new state to check
     * @throws IllegalStateException If the proposed newState is not allowed
     */
    public void verifyTransition(int newState) {
        boolean validTransition = false;
        if(isAborted() && getState()!=ABORTED)
            throw new IllegalStateException("Current state is ABORTED, "
                                            + "transition not allowed from "+
                                            getStateDesc(getState()));
        switch (newState) {
            case STARTING :
                if(getState() < STARTING)
                    validTransition = true;
                break;
            case INITIALIZED :
                if(getState() < INITIALIZED)
                    validTransition = true;
                break;
            case STARTED :
                if(getState() < STARTED)
                    validTransition = true;
                break;
            case STOPPED :
                if(getState() == STARTING ||
                   getState() == STARTED || getState() == UNADVERTISED)
                    validTransition = true;
                break;
            case UNADVERTISED :
                if(getState() == ADVERTISED || getState() == STOPPED)
                    validTransition = true;
                break;
            case ADVERTISED :
                if(getState() == STARTED || getState() == UNADVERTISED)
                    validTransition = true;
                break;
            case INACTIVE :
                if(getState() == STOPPED)
                    validTransition = true;
                break;
            case ABORTED:
                validTransition = true;
                break;
        }
        if(!validTransition)
            throw new IllegalStateException("New state ["
                                            +getStateDesc(newState)
                                            + "] not allowed "
                                            + "from ["
                                            +getStateDesc(getState())
                                            + "]");
    }

    /**
     * Check if we're aborted
     *
     * @return If the state is ABORTED, return true
     */
    public boolean isAborted() {
        boolean aborted = false;
        synchronized(this) {
            if(getState() == ABORTED)
                aborted = true;
        }
        return (aborted);
    }

    private String getStateDesc(int state) {
        String desc = null;
        switch(state) {
            case STARTING :
                desc = "STARTING";
                break;
            case INITIALIZED :
                desc = "INITIALIZED";
                break;
            case STARTED :
                desc = "STARTED";
                break;
            case STOPPED :
                desc = "STOPPED";
                break;
            case UNADVERTISED :
                desc = "UNADVERTISED";
                break;
            case ADVERTISED :
                desc = "ADVERTISED";
                break;
            case INACTIVE :
                desc = "INACTIVE";
                break;
            case ABORTED :
                desc = "ABORTED";
                break;
        }
        return(desc);
    }
}


text:
using System.Collections;

/// <exclude/>
public class ObjectList
{
	class Link {
		internal object it;
		internal Link next;
		internal Link(object o, Link x) { it=o;next=x; }
	}
	void Add0(Link a) {
		if (head==null)
			head = last = a;
		else
			last = last.next = a;
	}
	object Get0(Link a,int x) {
		if (a==null || x<0)  // safety
			return null;
		if (x==0)
			return a.it;
		return Get0(a.next,x-1);
	}
	private Link head = null, last=null;
	private int count = 0;
    /// <exclude/>
	public ObjectList() {}
    /// <exclude/>
	public void Add(object o) { Add0(new Link(o,null)); count++; }
    /// <exclude/>
	public void Push(object o) { head = new Link(o,head); count++; }
    /// <exclude/>
	public object Pop() { object r=head.it; head=head.next; count--; return r; }
    /// <exclude/>
    public object Top { get { return head.it; }}
    /// <exclude/>
	public int Count { get { return count; }}
    /// <exclude/>
	public object this[int ix] { get { return Get0(head,ix); } }
    /// <exclude/>
	public class OListEnumerator : IEnumerator
	{
		ObjectList list;
		Link cur = null;
        /// <exclude/>
		public object Current { get { return cur.it; }}
        /// <exclude/>
		public OListEnumerator(ObjectList o)
		{
			list = o;
		}
        /// <exclude/>
		public bool MoveNext()
		{
			if (cur==null)
				cur = list.head;
			else
				cur = cur.next;
			return cur!=null;
		}
        /// <exclude/>
		public void Reset()
		{
			cur = null;
		}
	}
    /// <exclude/>
	public IEnumerator GetEnumerator()
	{
		return new OListEnumerator(this);
	}
}


text:
package org.caleydo.vis.lineup.model;

import org.caleydo.core.util.color.Color;
import org.caleydo.core.view.opengl.layout.Column.VAlign;
import org.caleydo.core.view.opengl.layout2.GLElement;
import org.caleydo.core.view.opengl.layout2.GLGraphics;
import org.caleydo.core.view.opengl.layout2.renderer.GLRenderers;
import org.caleydo.core.view.opengl.layout2.renderer.IGLRenderer;
import org.caleydo.vis.lineup.model.mixin.ICollapseableColumnMixin;
import org.caleydo.vis.lineup.model.mixin.IHideableColumnMixin;
import org.caleydo.vis.lineup.ui.detail.ColoredValueElement;
import org.caleydo.vis.lineup.ui.detail.ValueElement;
/**
 * @author Samuel Gratzl
 *
 */
public final class RankRankColumnModel extends ARankColumnModel implements IGLRenderer, ICollapseableColumnMixin,
		IHideableColumnMixin, Cloneable {
	public static final String PROP_SHOW_RANK_DELTA = "showRankDelta";

	private boolean showRankDelta = false;

	public RankRankColumnModel() {
		super(Color.GRAY, new Color(0.95f, .95f, .95f));
		setHeaderRenderer(GLRenderers.drawText("Rank", VAlign.CENTER));
		setWidth(45);
	}

	public RankRankColumnModel(RankRankColumnModel copy) {
		super(copy);
		setHeaderRenderer(getHeaderRenderer());
	}

	@Override
	public RankRankColumnModel clone() {
		return new RankRankColumnModel(this);
	}

	@Override
	public GLElement createSummary(boolean interactive) {
		return new GLElement(); // dummy
	}

	@Override
	public ValueElement createValue() {
		return (ValueElement) (new ColoredValueElement().setRenderer(this));
	}

	/**
	 * @param showRankDelta
	 *            setter, see {@link showRankDelta}
	 */
	public void setShowRankDelta(boolean showRankDelta) {
		this.showRankDelta = showRankDelta;
	}

	/**
	 * @return the showRankDelta, see {@link #showRankDelta}
	 */
	public boolean isShowRankDelta() {
		return showRankDelta;
	}

	/**
	 *
	 */
	public void createDeltaColumn() {
		final RankTableModel table = getTable();

		RankDeltaRankColumnModel d = new RankDeltaRankColumnModel();
		table.add(table.indexOf(this) + 1, d);
		ColumnRanker b_r = getMyRanker();
		ColumnRanker a_r = table.getPreviousRanker(b_r);

		d.add((ARankColumnModel) a_r.getOrderBy().clone());
		d.add((ARankColumnModel) b_r.getOrderBy().clone());
	}

	@Override
	public String getValue(IRow row) {
		ColumnRanker ranker = getMyRanker();
		if (!ranker.hasDefinedRank())
			return "";
		int rank = ranker.getVisualRank(row);
		if (showRankDelta) {
			ColumnRanker previous = getTable().getPreviousRanker(ranker);
			if (previous != null) {
				int prank = previous.getVisualRank(row);
				int delta = prank - rank; // upwards = positive
				if (prank >= 0 && delta != 0) {
					return String.format("(%+d) %2d.", delta, rank);
				}
			}
		}
		return String.format("%2d.", rank);
	}

	@Override
	public void render(GLGraphics g, float w, float h, GLElement parent) {
		if (h < 5 || w < 15)
			return;
		float hi = Math.min(h, 12);
		String value = getValue(parent.getLayoutDataAs(IRow.class, null));
		if (value.length() == 0)
			return;
		g.drawText(value, 1, (h - hi) * 0.5f, w - 10, hi, VAlign.RIGHT);
	}
}


text:
package org.apache.hadoop.yarn.server.resourcemanager.placement;

import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacitySchedulerConfiguration.DOT;

public class QueuePath {

  private String parentQueue;
  private String leafQueue;
  private String fullPath;

  public QueuePath(final String leafQueue) {
    //if the queue does not have a parent, the full path == leaf queue name
    this.leafQueue = leafQueue;
    this.fullPath  = leafQueue;
  }

  public QueuePath(final String parentQueue, final String leafQueue) {
    this.parentQueue = parentQueue;
    this.leafQueue = leafQueue;
    this.fullPath = parentQueue + DOT + leafQueue;
  }

  public String getParentQueue() {
    return parentQueue;
  }

  public String getLeafQueue() {
    return leafQueue;
  }

  public boolean hasParentQueue() {
    return parentQueue != null;
  }

  public String getFullPath() {
    return fullPath;
  }

  @Override
  public String toString() {
    return fullPath;
  }
}


text:
@interface NewsContentEntity : NSManagedObject

@property (nonatomic, retain) NSString * content;

@end


text:
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.content.browser;

import android.view.View;
import android.view.ViewTreeObserver;

import java.util.ArrayList;

/**
 * Used to register listeners that can be notified of changes to the position of a view.
 */
public class ViewPositionObserver implements PositionObserver {
    private View mView;
    // Absolute position of the container view relative to its parent window.
    private final int[] mPosition = new int[2];

    private final ArrayList<Listener> mListeners;
    private ViewTreeObserver.OnPreDrawListener mPreDrawListener;

    /**
     * @param view The view to observe.
     */
    public ViewPositionObserver(View view) {
        mView = view;
        mListeners = new ArrayList<Listener>();
        updatePosition();
        mPreDrawListener = new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                updatePosition();
                return true;
            }
        };
    }

    /**
     * @return The current x position of the observed view.
     */
    @Override
    public int getPositionX() {
        // The stored position may be out-of-date. Get the real current position.
        updatePosition();
        return mPosition[0];
    }

    /**
     * @return The current y position of the observed view.
     */
    @Override
    public int getPositionY() {
        // The stored position may be out-of-date. Get the real current position.
        updatePosition();
        return mPosition[1];
    }

    /**
     * Register a listener to be called when the position of the underlying view changes.
     */
    @Override
    public void addListener(Listener listener) {
        if (mListeners.contains(listener)) return;

        if (mListeners.isEmpty()) {
            mView.getViewTreeObserver().addOnPreDrawListener(mPreDrawListener);
            updatePosition();
        }

        mListeners.add(listener);
    }

    /**
     * Remove a previously installed listener.
     */
    @Override
    public void removeListener(Listener listener) {
        if (!mListeners.contains(listener)) return;

        mListeners.remove(listener);

        if (mListeners.isEmpty()) {
            mView.getViewTreeObserver().removeOnPreDrawListener(mPreDrawListener);
        }
    }

    private void notifyListeners() {
        for (int i = 0; i < mListeners.size(); i++) {
            mListeners.get(i).onPositionChanged(mPosition[0], mPosition[1]);
        }
    }

    private void updatePosition() {
        int previousPositionX = mPosition[0];
        int previousPositionY = mPosition[1];
        mView.getLocationInWindow(mPosition);
        if (mPosition[0] != previousPositionX || mPosition[1] != previousPositionY) {
            notifyListeners();
        }
    }

    /**
     * Clears installed listener(s).
     */
    @Override
    public void clearListener() {
        mListeners.clear();
    }
}


text:
@interface DataModelTests : XCTestCase

@end

@implementation DataModelTests

- (void)testSerialize {
    TestDataModel *_test = [[TestDataModel alloc] init];

    NSDictionary *_d = [_test A_Serialize];
    TestDataModel *_result = (TestDataModel*)[TestDataModel A_Deserialize:_d];

    XCTAssertNotNil(_result);
}

- (void)testConvertJSON {
    TestDataModel *_test = [[TestDataModel alloc] init];
    _test.Name = @"Test2";
    _test.CreateDate = [NSDate date];
    _test.Index = 100;
    _test.ID = [NSNumber numberWithInt:123];

    NSString *_d = [_test A_ConvertToJSON];
    TestDataModel *_result = (TestDataModel*)[TestDataModel A_ConvertFromJSON:_d];

    XCTAssertNotNil(_result);
}

@end


text:
package com.google.cloud.dataplex.v1.samples;

// [START dataplex_v1_generated_DataplexService_CreateEnvironment_sync]
import com.google.cloud.dataplex.v1.CreateEnvironmentRequest;
import com.google.cloud.dataplex.v1.DataplexServiceClient;
import com.google.cloud.dataplex.v1.Environment;
import com.google.cloud.dataplex.v1.LakeName;

public class SyncCreateEnvironment {

  public static void main(String[] args) throws Exception {
    syncCreateEnvironment();
  }

  public static void syncCreateEnvironment() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (DataplexServiceClient dataplexServiceClient = DataplexServiceClient.create()) {
      CreateEnvironmentRequest request =
          CreateEnvironmentRequest.newBuilder()
              .setParent(LakeName.of("[PROJECT]", "[LOCATION]", "[LAKE]").toString())
              .setEnvironmentId("environmentId-950205810")
              .setEnvironment(Environment.newBuilder().build())
              .setValidateOnly(true)
              .build();
      Environment response = dataplexServiceClient.createEnvironmentAsync(request).get();
    }
  }
}
// [END dataplex_v1_generated_DataplexService_CreateEnvironment_sync]


text:
	text-align:center;
	width: 500px;
	height: 100px;
	margin-left: auto;
	margin-right: auto;
	display: inline-block;
}

#cardiacRythmAtStart, #testRuffier, #afterTest {
	display: none;
}


text:
var isMobile;

// Identify if visitor on mobile with lame sniffing to remove parallaxing title
if( navigator.userAgent.match(/Android/i) ||
    navigator.userAgent.match(/webOS/i) ||
    navigator.userAgent.match(/iPhone/i) ||
    navigator.userAgent.match(/iPod/i) ||
    navigator.userAgent.match(/iPad/i) ||
    navigator.userAgent.match(/BlackBerry/)
){
  isMobile = true;
}


text:
package com.example.asktheuniverse;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

import com.appspot.asktheuniverseaquestion.questionService.QuestionService;
import com.appspot.asktheuniverseaquestion.questionService.model.AskTheUniverseAQuestionQuestion;
import com.appspot.asktheuniverseaquestion.questionService.model.AskTheUniverseAQuestionQuestionCollection;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import android.accounts.Account;
import android.accounts.AccountManager;

public class ListQuestionsActivity extends Activity {
	private QuestionsDataAdapter mListAdapter;
	ListView listView = null;
	private Application app = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list_questions);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

		app = (Application) this.getApplicationContext();

		listView = (ListView) findViewById(R.id.questions_list_view);
		mListAdapter = new QuestionsDataAdapter(app);
		listView.setAdapter(mListAdapter);
	}

	@Override
	protected void onStart(){
		super.onStart();

		Log.d("DEBUG", "onstart of ListQuestionActivity called");
		final AsyncTask<Integer, Void, AskTheUniverseAQuestionQuestionCollection> getAndDisplayQuestions =
	            new AsyncTask<Integer, Void, AskTheUniverseAQuestionQuestionCollection> () {
	                @Override
	                protected AskTheUniverseAQuestionQuestionCollection doInBackground(Integer... integers) {
	                    // Retrieve service handle.
	                    QuestionService apiServiceHandle = AppConstants.getApiServiceHandle(app.credential);

	                    try {
	                    	Log.d("DEBUG", "run async api call");
	                    	QuestionService.QuestionServiceOperations getQuestionsCommand = apiServiceHandle.questionService();
	                    	AskTheUniverseAQuestionQuestionCollection questions = getQuestionsCommand.getAllQuestions().execute();
	                        return questions;
	                    } catch (IOException e) {
	                    	e.printStackTrace();
	                    }

	                    Log.d("DEBUG", "async returning null");
	                    return null;
	                }

	                @Override
	                protected void onPostExecute(AskTheUniverseAQuestionQuestionCollection questions) {
	                	displayQuestions(questions);
	                }
	            };

		listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
			public void onItemClick(AdapterView parent, View v, int position, long id){
				AskTheUniverseAQuestionQuestion question = mListAdapter.getItem(position);
				Bundle bundle = new Bundle();

				Log.d("DEBUG", "questionId from listview callback is: " + question.getId());
				bundle.putLong("questionId", question.getId());
				bundle.putString("questionText", question.getQuestion());

				Intent i = new Intent(ListQuestionsActivity.this, com.example.asktheuniverse.AnswerQuestionActivity.class);
				i.putExtras(bundle);

				startActivity(i);
			}
		});

		getAndDisplayQuestions.execute();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	static class QuestionsDataAdapter extends ArrayAdapter<AskTheUniverseAQuestionQuestion> {
        QuestionsDataAdapter(Application application) {
            super(application.getApplicationContext(), R.layout.list_view_items,
                    application.questions);
        }

        void replaceData(AskTheUniverseAQuestionQuestionCollection questions) {
            clear();
            List<AskTheUniverseAQuestionQuestion> list = questions.getItems();

            if (list == null || list.isEmpty()){
            	Toast t = Toast.makeText(this.getContext(), "No questions left, universe is answered.", Toast.LENGTH_LONG);
        		t.show();
            }
            else{
            	for (AskTheUniverseAQuestionQuestion question : list) {
            		//Log.d("DEBUG", question.toString());
            		add(question);
            	}
            }
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            AskTheUniverseAQuestionQuestion question = (AskTheUniverseAQuestionQuestion)this.getItem(position);

            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_view_items, null);

            }

            TextView questionText = (TextView) convertView.findViewById(R.id.question_item);
            questionText.setText(question.getQuestion());

            return convertView;
        }
    }

	private void displayQuestions(AskTheUniverseAQuestionQuestionCollection questions) {
		Log.d("DEBUG","displayQuestions called");
		if (questions == null){
			Toast t = Toast.makeText(this, "Failed to fetch questions, please try again.", Toast.LENGTH_LONG);
    		t.show();
    		this.finish();
		}
		else{
			mListAdapter.replaceData(questions);
		}
	}
}


text:
#ifndef LIBMDB_MDB_TREE_H
#define LIBMDB_MDB_TREE_H

#include <errors/errno.h>
#include <barrelfish/types.h>
#include <mdb/types.h>

struct capability;
struct cte;

enum {
    // All checked invariants hold
    MDB_INVARIANT_OK = 0,
    // A node with level > 0 must have both children
    MDB_INVARIANT_BOTHCHILDREN,
    // The level of a node's left child must be lt the node's level
    MDB_INVARIANT_LEFT_LEVEL_LESS,
    // The level of a node's right child must be leq the node's level
    MDB_INVARIANT_RIGHT_LEVEL_LEQ,
    // The level of a node's right grandchildren must bt lt the node's level
    MDB_INVARIANT_RIGHTRIGHT_LEVEL_LESS,
    MDB_INVARIANT_RIGHTLEFT_LEVEL_LESS,
    // The node's "end" value must be the maximum of the subtree's ends
    MDB_INVARIANT_END_IS_MAX,
    // The left child of a node must be earlier in the ordering
    MDB_INVARIANT_LEFT_SMALLER,
    // The right child of a node must be later in the ordering
    MDB_INVARIANT_RIGHT_GREATER,
};

enum {
    // No cap was found covering the specified region
    MDB_RANGE_NOT_FOUND = 0,
    // A cap was found covering at least the entire specified region
    MDB_RANGE_FOUND_SURROUNDING = 1,
    // A cap was found that is inside the specified region
    MDB_RANGE_FOUND_INNER = 2,
    // A cap was found that overlaps with one of the specified region's ends
    MDB_RANGE_FOUND_PARTIAL = 3,
};

// Print the specified subtree
void mdb_dump(struct cte *cte, int indent);
// Print the complete tree
void mdb_dump_all_the_things(void);
// Check that the invariants hold. The return value indicates the first issue
// that was encountered.
int mdb_check_invariants(void);

// Insert a cap into the tree. An error (MDB_DUPLICATE_ENTRY) is returned iff
// the cap is already present in the tree.
errval_t mdb_insert(struct cte *new_node);
// Remove a cap from the tree. An error (MDB_ENTRY_NOTFOUND) is returned iff
// the cap is not present in the tree.
errval_t mdb_remove(struct cte *node);

struct cte *mdb_predecessor(struct cte *current);
struct cte *mdb_successor(struct cte *current);

// Find a cap in the tree that compares equal to the given cap. Returns NULL if
// no such cap is found.
struct cte *mdb_find_equal(struct capability *cap);
// Find the greatest cap in the tree that is earlier in the ordering. Returns
// NULL if no matching cap is found.
// @param equal_ok If true, will return a copy of the passed cap if it is
//        present.
struct cte *mdb_find_less(struct capability *cap, bool equal_ok);
// Find the smallest cap in the tree that is later in the ordering. Returns
// NULL if no matching cap is found.
// @param equal_ok If true, will return a copy of the passed cap if it is
//        present.
struct cte *mdb_find_greater(struct capability *cap, bool equal_ok);

// Find a cap in the given range.
// @param root indicates which type tree root to search through (usually
//        `get_type_root(ObjType_PhysAddr)`).
// @param max_result Indicates the maximum outcome (not found, surrounding...)
//        for which a cap should be returned. If an result is found that is
//        greater than max_result, this function returns immediately with the
//        given result and NULL cte. The semantics/uses for individual
//        max_result values are thus:
//        - MDB_RANGE_NOT_FOUND: A simple test whether the given region is
//          covered by a cap.
//        - MDB_RANGE_FOUND_SURROUNDING: Can be used to check if a region can
//          be retyped.
//        - MDB_RANGE_FOUND_INNER: Useful for iterating through *immediate*
//          descendants.
errval_t mdb_find_range(mdb_root_t root, genpaddr_t address, gensize_t size,
                        int max_result, struct cte **ret_node, int *result);

errval_t mdb_find_cap_for_address(genpaddr_t address, struct cte **ret_node);

#endif // LIBMDB_MDB_TREE_H


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

namespace Waterboost
{

    public interface IDailyWaterConsumption : IList
    {
        List<IWaterAmountEntry> getWaterAmountEntries();
        bool removeEntry(IWaterAmountEntry e);
        bool addEntry(IWaterAmountEntry e);
        void syncWith(IDailyWaterConsumption waterConsumption);
        int getTotalAmount();
        int getMaximumAllowedAmount();
        // getUserData()
        // will be good to keep UserData such as weight, height, etc. every day. It might change over time :)
    }
}


text:
<?php
$this->load->view('template/head');
?>

<?php
$this->load->view('template/topbar_no_collapse');
$this->load->view('template/sidebar');
?>

Data Dokumen Mobil

						<button class="btn btn-success" onclick="tambah_mobil()"> Tambah Dokumen</button>
						<button class="btn btn-default" onclick="reload_table()"> Reload</button>

								No
								Id
								Jenis Dokumen
								Id Mobil
								File
								Keterangan
								Action

					<?php echo site_url('')?>

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Tambah Dokumen

                <form method="POST" enctype="multipart/form-data" id="form" action="<?php echo site_url('Dokumen/Dokumen/tambah')?>" class="form-horizontal">

                            ID Mobil

                                <select name="id_mobil" class="form-control">
									<?php
									foreach($Id_Mobil as $row)
									{
									?>
                                    <option value="<?php echo $row->Id_Mobil ?>"><?php echo $row->Id_Mobil ?> - <?php echo $row->Nama_Mobil ?></option>
									<?php
									}
									?>
                                </select>

                            Jenis Dokumen

                                <select name="jenis_dokumen" class="form-control">
                                    <option value="BPKB">BPKB</option>
                                    <option value="STNK">STNK</option>
                                    <option value="Lainnya">Lainnya</option>
                                </select>

                            Keterangan

                                <input name="keterangan" placeholder="Keterangan" class="form-control" type="text">

                            File

                                <input type="file" name="file" class="form-control">

                <button type="submit" class="btn btn-primary">Save</button>
                <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>

			</form>

<?php
$this->load->view('template/js');
?>

<?php
$this->load->view('template/foot');
?>


text:
package ben.kn.toolbox.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Overlord {

	private boolean running;
	private ExecutorService eService;

	public Overlord() {
		eService = Executors.newFixedThreadPool(5);
	}

	public void run() {
		running = true;

		String formattedName = "Thread-";
		int maxThreads = 10;

		System.out.println("Starting");

		for ( int i = 0; i < maxThreads; i++ ) {
			MyRunnable runnable = new MyRunnable();
			runnable.initialize(formattedName+i, 50000);
			eService.submit(runnable);
		}

		System.out.println("Ending");

		running = false;
	}

	public synchronized boolean isRunning() {
		return running;
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:orientation="horizontal"
              android:layout_width="match_parent"
              android:layout_height="wrap_content">
    <ImageView
        android:id="@+id/list_item_activity_icon"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="8dp"
        />
    <TextView
        android:id="@+id/list_item_activity_name"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="16dp"
        android:gravity="center_vertical"
        tools:text="App title"/>
</LinearLayout>


text:
var cookieName;
var ajaxurl = "apitalk/endpoint.php";

/// #1 ///
//javascript to grab the login cookie
function otbot_attempt_login(ot_username, ot_password){

  $.post(

    // see tip #1 for how we declare global javascript variables

    ajaxurl,
    {// here we declare the parameters to send along with the request

    action : 'otbot_attempt_login',
    // other parameters can be added along with "action"
    //requests only come from pages which originate with our server

    //username and password for ot
    otbot_username: ot_username,
    otbot_password: ot_password
    },

      function( response ) {
        $('#wait').hide();
      if(response =="ERROR!!!"){
        alert("Password or Username is incorrect, please try again.");
        $('#credentials').show();
      }else{
        cookieName = response;
        $('#status').append('1. ' + ot_username );
        $('#status').attr('otusername',('1. ' + ot_username) );
        otbot_query_projects();
        $('#wait').show();

      }
    });//end ajax post

}//end otbot_attempt_login

/// End #1 ///

/// #2///
//javascript to grab the login cookie
function otbot_query_projects(){

  $.post(

    // see tip #1 for how we declare global javascript variables

    ajaxurl,
    {// here we declare the parameters to send along with the request

    action : 'otbot_query_projects',
    // other parameters can be added along with "action"

    otbot_cookieName: cookieName
    },

      function( response ) {
        $('#wait').hide();
        if(response == 'ERROR!!!'){
          alert("Error retrieving Project List");
        }else{
          $('#projects').show();
          $('#projects').append( response);

        }

    });//end ajax post

}//end otbot_query projects

/// End #2 ///

/// #3///
//returns all of the issue types for a given project
function otbot_issue_types(key){

  $.post(

    // see tip #1 for how we declare global javascript variables

    ajaxurl,
    {// here we declare the parameters to send along with the request

    action : 'otbot_issue_types',
    // other parameters can be added along with "action"

    otbot_project_key: key,
    otbot_cookieName: cookieName
    },

      function( response ) {
          $('#wait').hide();
        if(response == 'ERROR!!!'){
          alert("Error retrieving Issue Types");
        }else{
          $('#issues').show();
          $('#issues').append( response);

        }

    });//end ajax post

}//end otbot_issue types

/// End #3 ///

/// #5///
//sends all data to create an issue with assignee, then displays a successful operation.
function otbot_create_issue(key,issue,summary,description){

  $.post(

    // see tip #1 for how we declare global javascript variables

    ajaxurl,
    {// here we declare the parameters to send along with the request

    action : 'otbot_create_issue',
    // other parameters can be added along with "action"

    otbot_project_key: key,
    otbot_issueType: issue,
    otbot_summary: summary,
    otbot_description: description,
    otbot_cookieName: cookieName

    },

      function( response ) {
          if(response == 'ERROR!!!'){
          alert("Error creating Issue");
        }else{
      $('#wait').hide();
      $('#creates').hide();
      $('#ot_issue_link').attr('href','http://ot.syr.edu/browse/' +response);
      $('#ot_issue_link').text('Issue created at http://ot.syr.edu/browse/' + response);
      $('#ot_issue_link').show();
      }//end if no error
    });//end ajax post

}//end otbot_create_issue

/// End #5 ///


text:
A flexible header is a container view whose height and vertical offset react to
UIScrollViewDelegate events.

## Related components

* [AppBar](../../AppBar)

- - -

## Overview

A flexible header is a simple container view designed to live at the top of a view controller and
react to scroll view events. Flexible headers are intended to be created and owned by each view
controller that requires one. This is an intentional deviation from the one-UINavigationBar design
of UINavigationController, and we discuss the merits and drawbacks of this approach below.

The heart of flexible header is MDCFlexibleHeaderView. MDCFlexibleHeaderView is a container view,
meaning you are expected to register your own subviews to it. MDCFlexibleHeaderView simply manages
its "frame", you are responsible for everything within the bounds.

MDCFlexibleHeaderViewController is the ideal way to create and manage the lifetime of a
MDCFlexibleHeaderView instance. Adding this view controller as a child of your view controller
ensures that the flexible header is able to react to device orientation and view appearance events.
This document generally assumes that you are familiar with
[UIViewController containment](https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/ImplementingaContainerViewController.html).

### Considerations

Requiring each view controller to own a flexible header instance has several technical advantages:

- Transitions between two view controllers can include the header in their motion considerations.
- Flexible header customizations are scoped to the owner view controller.

It also has some technical disadvantages:

- There is a cost to registering and owning a flexible header instance when compared to
  UINavigationController and the free availability of UINavigationBar. Improvements to this
  are being discussed on [issue #268](https://github.com/material-components/material-components-ios/issues/268).

## Installation

- [Typical installation](../../../docs/component-installation.md)

## Usage

- [Typical use: Add the flexible header to a view controller](typical-use.md)
- [Typical use: Tracking a scroll view](typical-use-tracking-a-scroll-view.md)
- [Typical use: Enabling observation of the tracking scroll view](typical-use-scroll-view-observation.md)
- [Shifting a flexible header off-screen](shift-behavior.md)
- [Reacting to frame changes](reacting-to-frame-changes.md)
- [Subclassing considerations](subclassing-considerations.md)
- [Interacting with UINavigationController](interacting-with-uinavigationcontroller.md)
- [Enabling Swipe to Dismiss](enabling-swipe-to-dismiss.md)
- [Status bar style](status-bar-style.md)
- [Background images](background-images.md)
- [Touch forwarding](touch-forwarding.md)
- [Tracking a parent view](tracking-a-parent-view.md)
- [WKWebView considerations](wkwebview-considerations.md)

## Behavioral flags

A behavioral flag is a temporary API that is introduced to allow client teams to migrate from an old
behavior to a new one in a graceful fashion. Behavioral flags all go through the following life
cycle:

1. The flag is introduced. The default is chosen such that clients must opt in to the new behavior.
2. After some time, the default changes to the new behavior and the flag is marked as deprecated.
3. After some time, the flag is removed.

- [Recommended behavioral flags](recommended-behavioral-flags.md)
- [Removing safe area insets from the min/max heights](behavior-minmax-safearea.md)
- [Enabling top layout guide adjustment](behavior-top-layout-adjustment.md)
- [Enabling inferred top safe area insets](behavior-inferred-top-safe-area-inset.md)

## Extensions

- [Color Theming](color-theming.md)

## Migration guides

- [Migration guide: minMaxHeightIncludesSafeArea](migration-guide-minMaxHeightIncludesSafeArea.md)


text:
#ifndef SVGElementRareData_h
#define SVGElementRareData_h

#include "CSSParserMode.h"
#include "StyleResolver.h"
#include <wtf/HashSet.h>
#include <wtf/Noncopyable.h>
#include <wtf/StdLibExtras.h>

namespace WebCore {

class CSSCursorImageValue;
class SVGCursorElement;
class SVGElement;
class SVGElementInstance;

class SVGElementRareData {
    WTF_MAKE_NONCOPYABLE(SVGElementRareData); WTF_MAKE_FAST_ALLOCATED;
public:
    SVGElementRareData()
        : m_cursorElement(0)
        , m_cursorImageValue(0)
        , m_correspondingElement(0)
        , m_instancesUpdatesBlocked(false)
        , m_hasPendingResources(false)
        , m_useOverrideComputedStyle(false)
        , m_needsOverrideComputedStyleUpdate(false)
    {
    }

    typedef HashMap<const SVGElement*, SVGElementRareData*> SVGElementRareDataMap;

    static SVGElementRareDataMap& rareDataMap()
    {
        DEFINE_STATIC_LOCAL(SVGElementRareDataMap, rareDataMap, ());
        return rareDataMap;
    }

    static SVGElementRareData* rareDataFromMap(const SVGElement* element)
    {
        return rareDataMap().get(element);
    }

    HashSet<SVGElementInstance*>& elementInstances() { return m_elementInstances; }
    const HashSet<SVGElementInstance*>& elementInstances() const { return m_elementInstances; }

    bool instanceUpdatesBlocked() const { return m_instancesUpdatesBlocked; }
    void setInstanceUpdatesBlocked(bool value) { m_instancesUpdatesBlocked = value; }

    bool hasPendingResources() const { return m_hasPendingResources; }
    void setHasPendingResources(bool value) { m_hasPendingResources = value; }

    SVGCursorElement* cursorElement() const { return m_cursorElement; }
    void setCursorElement(SVGCursorElement* cursorElement) { m_cursorElement = cursorElement; }

    SVGElement* correspondingElement() { return m_correspondingElement; }
    void setCorrespondingElement(SVGElement* correspondingElement) { m_correspondingElement = correspondingElement; }

    CSSCursorImageValue* cursorImageValue() const { return m_cursorImageValue; }
    void setCursorImageValue(CSSCursorImageValue* cursorImageValue) { m_cursorImageValue = cursorImageValue; }

    StylePropertySet* animatedSMILStyleProperties() const { return m_animatedSMILStyleProperties.get(); }
    StylePropertySet* ensureAnimatedSMILStyleProperties()
    {
        if (!m_animatedSMILStyleProperties)
            m_animatedSMILStyleProperties = StylePropertySet::create(SVGAttributeMode);
        return m_animatedSMILStyleProperties.get();
    }

    void destroyAnimatedSMILStyleProperties()
    {
        m_animatedSMILStyleProperties.clear();
    }

    RenderStyle* overrideComputedStyle(Element* element, RenderStyle* parentStyle)
    {
        ASSERT(element);
        if (!element->document() || !m_useOverrideComputedStyle)
            return 0;
        if (!m_overrideComputedStyle || m_needsOverrideComputedStyleUpdate) {
            // The style computed here contains no CSS Animations/Transitions or SMIL induced rules - this is needed to compute the "base value" for the SMIL animation sandwhich model.
            m_overrideComputedStyle = element->document()->styleResolver()->styleForElement(element, parentStyle, DisallowStyleSharing, MatchAllRulesExcludingSMIL);
            m_needsOverrideComputedStyleUpdate = false;
        }
        ASSERT(m_overrideComputedStyle);
        return m_overrideComputedStyle.get();
    }

    bool useOverrideComputedStyle() const { return m_useOverrideComputedStyle; }
    void setUseOverrideComputedStyle(bool value) { m_useOverrideComputedStyle = value; }
    void setNeedsOverrideComputedStyleUpdate() { m_needsOverrideComputedStyleUpdate = true; }

private:
    HashSet<SVGElementInstance*> m_elementInstances;
    SVGCursorElement* m_cursorElement;
    CSSCursorImageValue* m_cursorImageValue;
    SVGElement* m_correspondingElement;
    bool m_instancesUpdatesBlocked : 1;
    bool m_hasPendingResources : 1;
    bool m_useOverrideComputedStyle : 1;
    bool m_needsOverrideComputedStyleUpdate : 1;
    RefPtr<StylePropertySet> m_animatedSMILStyleProperties;
    RefPtr<RenderStyle> m_overrideComputedStyle;
};

}

#endif


text:
package jalse.tags;

import java.util.Set;
import java.util.stream.Stream;

/**
 * Used identify any class that is exposing internal state through {@link Tag}.
 *
 * @author Elliot Ford
 *
 */
public interface Taggable {

    /**
     * Gets all tag state information.
     *
     * @return All tags or an empty set if none are found.
     */
    Set<Tag> getTags();

    /**
     * Streams all tag state information.
     *
     * @return Stream of all tags.
     */
    default Stream<Tag> streamTags() {
	return getTags().stream();
    }
}


text:
import assert from 'assert'
import concat from 'concat-stream'
import { Transform } from 'stream'
import helper from './helper'
import QueryStream from '../src'

helper('concat', function (client) {
  it('concats correctly', function (done) {
    const stream = new QueryStream('SELECT * FROM generate_series(0, 200) num', [])
    const query = client.query(stream)
    query
      .pipe(
        new Transform({
          transform(chunk, _, callback) {
            callback(null, chunk.num)
          },
          objectMode: true,
        })
      )
      .pipe(
        concat(function (result) {
          const total = result.reduce(function (prev, cur) {
            return prev + cur
          })
          assert.equal(total, 20100)
        })
      )
    stream.on('end', done)
  })
})


text:
/*	$NetBSD: makecontext.c,v 1.4 2012/03/22 17:32:22 christos Exp $	*/

/*-
 * Copyright (c) 2003 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Matt Thomas.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: makecontext.c,v 1.4 2012/03/22 17:32:22 christos Exp $");
#endif

#include <stddef.h>
#include <inttypes.h>
#include <ucontext.h>
#include "extern.h"

#include <stdarg.h>

void
makecontext(ucontext_t *ucp, void (*func)(void), int argc, ...)
{
	__greg_t *gr = ucp->uc_mcontext.__gregs;
	va_list ap;
	int *sp;
	int i;

	/* Compute and align stack pointer. */
	sp = (int *)
	    (((uintptr_t)ucp->uc_stack.ss_sp + ucp->uc_stack.ss_size) & ~0x3);

	/*
	 * Allocate necessary stack space for arguments including arg count
	 * and call frame
	 */
	sp -= argc + 1 + 5;

	va_start(ap, argc);
	sp[5] = argc;
	for (i = 1; argc > 0; argc--, i++)
		sp[5 + i] = va_arg(ap, int);
	va_end(ap);

	sp[0] = 0;			/* condition handler is null */
	sp[1] = 0x20000000;		/* make this a CALLS frame */
	sp[2] = 0;			/* saved argument pointer */
	sp[3] = 0;			/* saved frame pointer */
	sp[4] = (int)(uintptr_t)_resumecontext+2;/* return via trampoline code */

	gr[_REG_AP] = (__greg_t)(uintptr_t)(sp + 5);
	gr[_REG_SP] = (__greg_t)(uintptr_t)sp;
	gr[_REG_FP] = (__greg_t)(uintptr_t)sp;
	gr[_REG_PC] = (__greg_t)(uintptr_t)func+2;

}


text:
module Scorm
  VERSION = '1.0.4'
end

require 'scorm/package'


text:
BSLS_IDENT("$Id: $")

//@PURPOSE: Provide sequential memory using an external buffer and a fallback.
//
//@CLASSES:
//  bdlma::BufferedSequentialPool: pool using an external buffer and a fallback
//
//@SEE_ALSO: bdlma_buffermanager, bdlma_sequentialpool
//
//@DESCRIPTION: This component provides a maximally efficient sequential memory
// pool, 'bdlma::BufferedSequentialPool', that dispenses heterogeneous memory
// blocks (of varying, user-specified sizes) from an external buffer.  If an
// allocation request exceeds the remaining free memory space in the external
// buffer, the pool will fall back to a sequence of dynamically allocated
// buffers.  Users can optionally specify a growth strategy at construction
// that governs the growth rate of the dynamically-allocated buffers.  If no
// growth strategy is specified at construction, geometric growth is used.
// Users can also optionally specify an alignment strategy at construction that
// governs the alignment of allocated memory blocks.  If no alignment strategy
// is specified, natural alignment is used.  The 'release' method releases all
// memory allocated through the pool, as does the destructor.  The 'rewind'
// method releases all memory allocated through the pool and returns to the
// underlying allocator *only* memory that was allocated outside of the typical
// internal buffer growth of the pool (i.e., large blocks).  Note that
// individually allocated memory blocks cannot be separately deallocated.
//
// A 'bdlma::BufferedSequentialPool' is typically used when users have a
// reasonable estimation of the amount of memory needed.  This amount of memory
// would typically be created directly on the program stack, and used as the
// initial external buffer of the pool for fast memory allocation.  While the
// buffer has sufficient capacity, memory allocations using the pool will not
// trigger *any* dynamic memory allocation, will have optimal locality of
// reference, and will not require deallocation upon destruction.
//
// Once the external buffer is exhausted, subsequent allocation requests
// require dynamic memory allocation, and the performance of the pool degrades.
//
///Optional 'maxBufferSize' Parameter
/// - - - - - - - - - - - - - - - - -
// An optional 'maxBufferSize' parameter can be supplied at construction to
// specify the maximum size (in bytes) of the dynamically-allocated buffers for
// geometric growth.  Once the internal buffer grows up to the 'maxBufferSize',
// further requests that exceed this size will be served by a separate memory
// block instead of the internal buffer.  The behavior is undefined unless
// 'size <= maxBufferSize', where 'size' is the extent (in bytes) of the
// external buffer supplied at construction.
//
///Warning
///-------
// Note that, even when a buffer having 'n' bytes of memory is supplied at
// construction, it does *not* mean that 'n' bytes of memory are available
// before dynamic memory allocation is triggered.  This is due to memory
// alignment requirements.  If the buffer supplied is not aligned, the first
// call to the 'allocate' method may automatically skip one or more bytes such
// that the memory allocated is properly aligned.  The number of bytes that are
// wasted depends on whether natural alignment, maximum alignment, or 1-byte
// alignment is used (see 'bsls_alignment' for more details).
//
///Usage
///-----
// This section illustrates intended use of this component.
//
///Example 1: Using 'bdlma::BufferedSequentialPool' for Efficient Allocations
/// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Suppose we define a container class, 'my_BufferedIntDoubleArray', that holds
// both 'int' and 'double' values.  The class can be implemented using two
// parallel arrays: one storing the type information, and the other storing
// pointers to the 'int' and 'double' values.  Furthermore, if we can
// approximate the amount of memory needed, we can use a
// 'bdlma::BufferedSequentialPool' for memory allocation for maximum
// efficiency:
//..
//  // my_bufferedintdoublearray.h
//
//  class my_BufferedIntDoubleArray {
//      // This class implements an efficient container for an array that
//      // stores both 'int' and 'double' values.
//
//      // DATA
//      char  *d_typeArray_p;   // array indicating the type of corresponding
//                              // values stored in 'd_valueArray_p'
//
//      void **d_valueArray_p;  // array of pointers to the values stored
//
//      int    d_length;        // number of values stored
//
//      int    d_capacity;      // physical capacity of the type and value
//                              // arrays
//
//      bdlma::BufferedSequentialPool
//             d_pool;          // buffered sequential memory pool used to
//                              // supply memory
//
//    private:
//      // NOT IMPLEMENTED
//      my_BufferedIntDoubleArray(const my_BufferedIntDoubleArray&);
//
//    private:
//      // PRIVATE MANIPULATORS
//      void increaseCapacity();
//          // Increase the capacity of the internal arrays used to store
//          // elements added to this array by at least one element.
//
//    public:
//      // TYPES
//      enum Type { k_MY_INT, k_MY_DOUBLE };
//
//      // CREATORS
//      my_BufferedIntDoubleArray(char             *buffer,
//                                int               size,
//                                bslma::Allocator *basicAllocator = 0);
//          // Create a fast 'int'-'double' array that initially allocates
//          // memory sequentially from the specified 'buffer' having the
//          // specified 'size' (in bytes).  Optionally specify a
//          // 'basicAllocator' used to supply memory if 'buffer' capacity is
//          // exceeded.  If 'basicAllocator' is 0, the currently installed
//          // default allocator is used.
//
//      ~my_BufferedIntDoubleArray();
//          // Destroy this array and all elements held by it.
//
//      // ...
//
//      // MANIPULATORS
//      void appendInt(int value);
//          // Append the specified 'int' 'value' to this array.
//
//      void appendDouble(double value);
//          // Append the specified 'double' 'value' to this array.
//
//      void removeAll();
//          // Remove all elements from this array.
//
//      // ...
//  };
//..
// The use of a buffered sequential pool and the 'release' method allows the
// 'removeAll' method to quickly deallocate memory of all elements:
//..
//  // MANIPULATORS
//  inline
//  void my_BufferedIntDoubleArray::removeAll()
//  {
//      d_pool.release();  // *very* efficient if 'd_pool' has not exhausted
//                         // the buffer supplied at construction
//
//      d_length = 0;
//  }
//..
// The buffered sequential pool optimizes the allocation of memory by using a
// buffer supplied at construction.  As described in the "DESCRIPTION" section,
// the need for *all* dynamic memory allocations are eliminated provided that
// the buffer is not exhausted.  The pool provides maximal memory allocation
// efficiency:
//..
//  // my_bufferedintdoublearray.cpp
//
//  enum { k_INITIAL_SIZE = 1 };
//
//  // PRIVATE MANIPULATORS
//  void my_BufferedIntDoubleArray::increaseCapacity()
//  {
//      // Implementation elided.
//      // ...
//  }
//
//  // CREATORS
//  my_BufferedIntDoubleArray::my_BufferedIntDoubleArray(
//                                            char             *buffer,
//                                            int               size,
//                                            bslma::Allocator *basicAllocator)
//  : d_length(0)
//  , d_capacity(k_INITIAL_SIZE)
//  , d_pool(buffer, size, basicAllocator)
//  {
//      d_typeArray_p  = static_cast<char *>(
//                       d_pool.allocate(d_capacity * sizeof *d_typeArray_p));
//      d_valueArray_p = static_cast<void **>(
//                       d_pool.allocate(d_capacity * sizeof *d_valueArray_p));
//  }
//..
// Note that in the destructor, all outstanding memory blocks are deallocated
// automatically when 'd_pool' is destroyed:
//..
//  my_BufferedIntDoubleArray::~my_BufferedIntDoubleArray()
//  {
//      assert(0 <= d_length);
//      assert(0 <= d_capacity);
//      assert(d_length <= d_capacity);
//  }
//
//  // MANIPULATORS
//  void my_BufferedIntDoubleArray::appendDouble(double value)
//  {
//      if (d_length >= d_capacity) {
//          increaseCapacity();
//      }
//
//      double *item = static_cast<double *>(d_pool.allocate(sizeof *item));
//      *item = value;
//
//      d_typeArray_p[d_length]  = static_cast<char>(k_MY_DOUBLE);
//      d_valueArray_p[d_length] = item;
//
//      ++d_length;
//  }
//
//  void my_BufferedIntDoubleArray::appendInt(int value)
//  {
//      if (d_length >= d_capacity) {
//          increaseCapacity();
//      }
//
//      int *item = static_cast<int *>(d_pool.allocate(sizeof *item));
//      *item = value;
//
//      d_typeArray_p[d_length]  = static_cast<char>(k_MY_INT);
//      d_valueArray_p[d_length] = item;
//
//      ++d_length;
//  }
//..
//
///Example 2: Implementing an Allocator Using 'bdlma::BufferedSequentialPool'
/// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// 'bslma::Allocator' is used throughout the interfaces of BDE components.
// Suppose we would like to create a fast allocator, 'my_FastAllocator', that
// allocates memory from a buffer in a similar fashion to
// 'bdlma::BufferedSequentialPool'.  'bdlma::BufferedSequentialPool' can be
// used directly to implement such an allocator.
//
// Note that the documentation for this class is simplified for this usage
// example.  Please see 'bdlma_bufferedsequentialallocator' for full
// documentation of a similar class.
//..
//  class my_FastAllocator : public bslma::Allocator {
//      // This class implements the 'bslma::Allocator' protocol to provide a
//      // fast allocator of heterogeneous blocks of memory (of varying,
//      // user-specified sizes) from an external buffer whose address and size
//      // are supplied at construction.
//
//      // DATA
//      bdlma::BufferedSequentialPool d_pool;  // memory manager for allocated
//                                             // memory blocks
//
//      // CREATORS
//      my_FastAllocator(char             *buffer,
//                       int               size,
//                       bslma::Allocator *basicAllocator = 0);
//          // Create an allocator for allocating memory blocks from the
//          // specified external 'buffer' of the specified 'size' (in bytes).
//          // Optionally specify a 'basicAllocator' used to supply memory
//          // should the capacity of 'buffer' be exhausted.  If
//          // 'basicAllocator' is 0, the currently installed default allocator
//          // is used.
//
//      ~my_FastAllocator();
//          // Destroy this allocator.  All memory allocated from this
//          // allocator is released.
//
//      // MANIPULATORS
//      virtual void *allocate(size_type size);
//          // Return the address of a contiguous block of memory of the
//          // specified 'size' (in bytes).
//
//      virtual void deallocate(void *address);
//          // This method has no effect on the memory block at the specified
//          // 'address' as all memory allocated by this allocator is managed.
//          // The behavior is undefined unless 'address' was allocated by this
//          // allocator, and has not already been deallocated.
//  };
//
//  // CREATORS
//  inline
//  my_FastAllocator::my_FastAllocator(char             *buffer,
//                                     int               size,
//                                     bslma::Allocator *basicAllocator)
//  : d_pool(buffer, size, basicAllocator)
//  {
//  }
//
//  inline
//  my_FastAllocator::~my_FastAllocator()
//  {
//      d_pool.release();
//  }
//
//  // MANIPULATORS
//  inline
//  void *my_FastAllocator::allocate(size_type size)
//  {
//      return d_pool.allocate(size);
//  }
//
//  inline
//  void my_FastAllocator::deallocate(void *)
//  {
//  }
//..

#include <bdlscm_version.h>

#include <bdlma_buffermanager.h>
#include <bdlma_sequentialpool.h>

#include <bslma_allocator.h>

#include <bsls_alignment.h>
#include <bsls_assert.h>
#include <bsls_blockgrowth.h>
#include <bsls_platform.h>
#include <bsls_performancehint.h>
#include <bsls_types.h>

#include <bsl_cstddef.h>

namespace BloombergLP {
namespace bdlma {

                       // ============================
                       // class BufferedSequentialPool
                       // ============================

class BufferedSequentialPool {
    // This class implements a fast memory pool that efficiently dispenses
    // heterogeneous blocks of memory (of varying, user-specified sizes) from
    // an external buffer whose address and size (in bytes) are supplied at
    // construction.  If an allocation request exceeds the remaining free
    // memory space in the external buffer, memory will be supplied by an
    // (optional) allocator supplied also at construction; if no allocator is
    // supplied, the currently installed default allocator will be used.  This
    // class is *exception* *neutral*: If memory cannot be allocated, the
    // behavior is defined by the (optional) allocator supplied at
    // construction.  Note that in no case will the buffered sequential pool
    // attempt to deallocate the external buffer.

    // DATA
    BufferManager           d_bufferManager;    // memory manager for current
                                                // buffer

    bsls::Types::size_type  d_maxBufferSize;    // max buffer size parameter to
                                                // be passed to the sequential
                                                // allocator upon construction

    unsigned char           d_growthStrategy;   // the growth strategy to be
                                                // passed to the sequential
                                                // pool

    bool                    d_sequentialPoolIsCreated;
                                                // indicates whether the
                                                // sequential pool has been
                                                // created yet

    union {
        bslma::Allocator   *d_allocator_p;      // allocator we were
                                                // constructed with if the
                                                // sequential pool hasn't been
                                                // created

        SequentialPool     *d_pool_p;           // memory manager for
    };                                          // allocations not from the
                                                // buffer, if the sequential
                                                // pool has been created

  private:
    // NOT IMPLEMENTED
    BufferedSequentialPool(const BufferedSequentialPool&);
    BufferedSequentialPool& operator=(const BufferedSequentialPool&);

  private:
    // PRIVATE MANIPULATORS
    void createSequentialPool(bsls::Types::size_type currentAllocationSize);
        // Allocate and construct the sequential pool, using a block size of
        // 'bufferManager.bufferSize()'.  Use the specified
        // 'currentAllocationSize' to determine if the current allocation
        // attempt will fit in the first block, and thus what boolean value to
        // pass to the sequental pool's 'allocateInitialBuffer' argument.

    // PRIVATE ACCESSORS
    bsls::Alignment::Strategy alignmentStrategy() const;
        // Return the alignment strategy to be used by the sequential pool.

    bsls::BlockGrowth::Strategy growthStrategy() const;
        // Return the growth strategy to be used by the sequential pool.

  public:
    // CREATORS
    BufferedSequentialPool(char                   *buffer,
                           bsls::Types::size_type  size,
                           bslma::Allocator       *basicAllocator = 0);
    BufferedSequentialPool(char                        *buffer,
                           bsls::Types::size_type       size,
                           bsls::BlockGrowth::Strategy  growthStrategy,
                           bslma::Allocator            *basicAllocator = 0);
    BufferedSequentialPool(char                      *buffer,
                           bsls::Types::size_type     size,
                           bsls::Alignment::Strategy  alignmentStrategy,
                           bslma::Allocator          *basicAllocator = 0);
    BufferedSequentialPool(char                        *buffer,
                           bsls::Types::size_type       size,
                           bsls::BlockGrowth::Strategy  growthStrategy,
                           bsls::Alignment::Strategy    alignmentStrategy,
                           bslma::Allocator            *basicAllocator = 0);
        // Create a buffered sequential pool for allocating memory blocks from
        // the specified external 'buffer' having the specified 'size' (in
        // bytes), or from an internal buffer (after the external 'buffer' is
        // exhausted).  Optionally specify a 'growthStrategy' used to control
        // buffer growth.  If a 'growthStrategy' is not specified, geometric
        // growth is used.  Optionally specify an 'alignmentStrategy' used to
        // align allocated memory blocks.  If an 'alignmentStrategy' is not
        // specified, natural alignment is used.  Optionally specify a
        // 'basicAllocator' used to supply memory should the capacity of
        // 'buffer' be exhausted.  If 'basicAllocator' is 0, the currently
        // installed default allocator is used.  The behavior is undefined
        // unless '0 < size', and 'buffer' has at least 'size' bytes.  Note
        // that, due to alignment effects, it is possible that not all 'size'
        // bytes of memory in 'buffer' can be used for allocation.  Also note
        // that no limit is imposed on the size of the internal buffers when
        // geometric growth is used.  Also note that when constant growth is
        // used, the size of the internal buffers will always be the same as
        // 'size'.

    BufferedSequentialPool(char                   *buffer,
                           bsls::Types::size_type  size,
                           bsls::Types::size_type  maxBufferSize,
                           bslma::Allocator       *basicAllocator = 0);
    BufferedSequentialPool(char                        *buffer,
                           bsls::Types::size_type       size,
                           bsls::Types::size_type       maxBufferSize,
                           bsls::BlockGrowth::Strategy  growthStrategy,
                           bslma::Allocator            *basicAllocator = 0);
    BufferedSequentialPool(char                      *buffer,
                           bsls::Types::size_type     size,
                           bsls::Types::size_type     maxBufferSize,
                           bsls::Alignment::Strategy  alignmentStrategy,
                           bslma::Allocator          *basicAllocator = 0);
    BufferedSequentialPool(char                        *buffer,
                           bsls::Types::size_type       size,
                           bsls::Types::size_type       maxBufferSize,
                           bsls::BlockGrowth::Strategy  growthStrategy,
                           bsls::Alignment::Strategy    alignmentStrategy,
                           bslma::Allocator            *basicAllocator = 0);
        // Create a buffered sequential pool for allocating memory blocks from
        // the specified external 'buffer' having the specified 'size' (in
        // bytes), or from an internal buffer (after the external 'buffer' is
        // exhausted) where the buffer growth is limited to the specified
        // 'maxBufferSize' (in bytes).  Optionally specify a 'growthStrategy'
        // used to control buffer growth.  If a 'growthStrategy' is not
        // specified, geometric growth is used.  Optionally specify an
        // 'alignmentStrategy' used to align allocated memory blocks.  If an
        // 'alignmentStrategy' is not specified, natural alignment is used.
        // Optionally specify a 'basicAllocator' used to supply memory should
        // the capacity of 'buffer' be exhausted.  If 'basicAllocator' is 0,
        // the currently installed default allocator is used.  The behavior is
        // undefined unless '0 < size', 'size <= maxBufferSize', and 'buffer'
        // has at least 'size' bytes.  Note that, due to alignment effects, it
        // is possible that not all 'size' bytes of memory in 'buffer' can be
        // used for allocation.  Also note that when constant growth is used,
        // the size of the internal buffers will always be the same as 'size'.

    ~BufferedSequentialPool();
        // Destroy this buffered sequential pool.  All memory allocated from
        // this pool is released.

    // MANIPULATORS
    void *allocate(bsls::Types::size_type size);
        // Return the address of a contiguous block of memory of the specified
        // 'size' (in bytes) according to the alignment strategy specified at
        // construction.  If 'size' is 0, no memory is allocated and 0 is
        // returned.  If the allocation request exceeds the remaining free
        // memory space in the external buffer supplied at construction, use
        // memory obtained from the allocator supplied at construction.

    template <class TYPE>
    void deleteObject(const TYPE *object);
        // Destroy the specified 'object'.  Note that this method has the same
        // effect as the 'deleteObjectRaw' method (since no deallocation is
        // involved), and exists for consistency across memory pools.

    template <class TYPE>
    void deleteObjectRaw(const TYPE *object);
        // Destroy the specified 'object'.  Note that memory associated with
        // 'object' is not deallocated because there is no 'deallocate' method
        // in 'BufferedSequentialPool'.

    void release();
        // Release all memory allocated through this pool and return to the
        // underlying allocator *all* memory except the external buffer
        // supplied at construction.  The pool is reset to its
        // default-constructed state, making the memory from the entire
        // external buffer supplied at construction available for subsequent
        // allocations, retaining the alignment and growth strategies, and the
        // initial and maximum buffer sizes in effect following construction.
        // The effect of subsequently - to this invokation of 'release' - using
        // a pointer obtained from this object prior to this call to 'release'
        // is undefined.

    void rewind();
        // Release all memory allocated through this pool and return to the
        // underlying allocator *only* memory that was allocated outside of the
        // typical internal buffer growth of this pool (i.e., large blocks).
        // All retained memory will be used to satisfy subsequent allocations.
        // The effect of subsequently - to this invokation of 'rewind' - using
        // a pointer obtained from this object prior to this call to 'rewind'
        // is undefined.

    // ACCESSORS
    bslma::Allocator *allocator() const;
        // Return the allocator used by this object to allocate memory.  Note
        // that this allocator can not be used to deallocate memory allocated
        // through this pool.
};

}  // close package namespace
}  // close enterprise namespace

// Note that the 'new' and 'delete' operators are declared outside the
// 'BloombergLP' namespace so that they do not hide the standard placement
// 'new' and 'delete' operators (i.e.,
// 'void *operator new(bsl::size_t, void *)' and
// 'void operator delete(void *)').
//
// Also note that only the scalar versions of operators 'new' and 'delete' are
// provided, because overloading 'new' (and 'delete') with their array versions
// would cause dangerous ambiguity.  Consider what would have happened had we
// overloaded the array version of 'operator new':
//..
//   void *operator new[](bsl::size_t                                 size,
//                        BloombergLP::bdlma::BufferedSequentialPool& pool);
//..
// The user of the pool class would have expected to be able to use operator
// 'new' as follows:
//..
//   new (*pool) my_Type[...];
//..
// The problem is that this expression returns an array that cannot be safely
// deallocated.  On the one hand, there is no syntax in C++ to invoke an
// overloaded 'operator delete'; on the other hand, the pointer returned by
// 'operator new' cannot be passed to the 'deallocate' method directly because
// the pointer is different from the one returned by the 'allocate' method.
// The compiler offsets the value of this pointer by a header, which is used to
// maintain the number of objects in the array (so that the 'operator delete'
// can destroy the right number of objects).

// FREE OPERATORS
void *operator new(bsl::size_t                                 size,
                   BloombergLP::bdlma::BufferedSequentialPool& pool);
    // Return a block of memory of the specified 'size' (in bytes) allocated
    // from the specified 'pool'.  Note that an object may allocate additional
    // memory internally, requiring the allocator to be passed in as a
    // constructor argument:
    //..
    //  my_Type *newMyType(bdlma::BufferedSequentialPool *pool,
    //                     bslma::Allocator              *basicAllocator)
    //  {
    //      return new (*pool) my_Type(..., basicAllocator);
    //  }
    //..
    // Also note that the analogous version of 'operator delete' should not be
    // called directly.  Instead, this component provides a static template
    // member function, 'deleteObject', parameterized by 'TYPE' that performs
    // the following:
    //..
    //  void deleteMyType(bdlma::BufferedSequentialPool *pool, my_Type *t)
    //  {
    //      t->~my_Type();
    //  }
    //..

void operator delete(void                                        *address,
                     BloombergLP::bdlma::BufferedSequentialPool&  pool);
    // Use the specified 'pool' to deallocate the memory at the specified
    // 'address'.  The behavior is undefined unless 'address' was allocated
    // using 'pool' and has not already been deallocated.  This operator is
    // supplied solely to allow the compiler to arrange for it to be called in
    // case of an exception.

// ============================================================================
//                             INLINE DEFINITIONS
// ============================================================================

namespace BloombergLP {
namespace bdlma {

                       // ----------------------------
                       // class BufferedSequentialPool
                       // ----------------------------

// PRIVATE ACCESSORS
inline
bsls::Alignment::Strategy BufferedSequentialPool::alignmentStrategy() const
{
    return d_bufferManager.alignmentStrategy();
}

inline
bsls::BlockGrowth::Strategy BufferedSequentialPool::growthStrategy() const
{
    return static_cast<bsls::BlockGrowth::Strategy>(d_growthStrategy);
}

// CREATORS
inline
BufferedSequentialPool::~BufferedSequentialPool()
{
    // 'd_bufferManager' doesn't need to be released, it will destroy itself
    // just fine.

    if (d_sequentialPoolIsCreated) {
        d_pool_p->allocator()->deleteObjectRaw(d_pool_p);
    }
}

// MANIPULATORS
inline
void *BufferedSequentialPool::allocate(bsls::Types::size_type size)
{
    if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(0 == size)) {
        BSLS_PERFORMANCEHINT_UNLIKELY_HINT;
        return 0;                                                     // RETURN
    }

    void *result = d_bufferManager.allocate(size);
    if (BSLS_PERFORMANCEHINT_PREDICT_LIKELY(result)) {
        return result;                                                // RETURN
    }

    if (false == d_sequentialPoolIsCreated) {
        this->createSequentialPool(size);
    }

    return d_pool_p->allocate(size);
}

template <class TYPE>
inline
void BufferedSequentialPool::deleteObject(const TYPE *object)
{
    this->deleteObjectRaw(object);
}

template <class TYPE>
inline
void BufferedSequentialPool::deleteObjectRaw(const TYPE *object)
{
    if (0 != object) {
#ifndef BSLS_PLATFORM_CMP_SUN
        object->~TYPE();
#else
        const_cast<TYPE *>(object)->~TYPE();
#endif
    }
}

inline
void BufferedSequentialPool::release()
{
    d_bufferManager.release();  // Reset the internal cursor in the current
                                // block.

    if (d_sequentialPoolIsCreated) {
        // Note that 'd_pool_p' and 'd_allocator_p' fit in the same footprint
        // in an anonymous union.

        bslma::Allocator *alloc_p = d_pool_p->allocator();
        alloc_p->deleteObjectRaw(d_pool_p);
        d_allocator_p = alloc_p;

        d_sequentialPoolIsCreated = false;
    }
}

inline
void BufferedSequentialPool::rewind()

{
    d_bufferManager.release();  // Reset the internal cursor in the current
                                // block.

    if (d_sequentialPoolIsCreated) {
        d_pool_p->rewind();
    }
}

// ACCESSORS
inline
bslma::Allocator *BufferedSequentialPool::allocator() const
{
    return d_sequentialPoolIsCreated ? d_pool_p->allocator()
                                     : d_allocator_p;
}

}  // close package namespace
}  // close enterprise namespace

// FREE OPERATORS
inline
void *operator new(bsl::size_t                                 size,
                   BloombergLP::bdlma::BufferedSequentialPool& pool)
{
    return pool.allocate(size);
}

inline
void operator delete(void *, BloombergLP::bdlma::BufferedSequentialPool&)
{
    // NOTE: there is no deallocation from this allocation mechanism.
}

#endif

// ----------------------------------------------------------------------------
// Copyright 2016 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------