text:
package monix.eval.internal

import java.util.concurrent.TimeoutException
import java.util.concurrent.locks.AbstractQueuedSynchronizer

import monix.eval.Task.{Async, Context, Error, Eval, FlatMap, Map, Now, Suspend}
import monix.eval.internal.TaskRunLoop._
import monix.eval.Task
import monix.execution.{Callback, Scheduler}
import monix.execution.internal.collection.ArrayStack
import scala.util.control.NonFatal

import scala.concurrent.blocking
import scala.concurrent.duration.{Duration, FiniteDuration}

private[eval] object TaskRunSyncUnsafe {
  /** Run-loop specialization that evaluates the given task and blocks for the result
    * if the given task is asynchronous.
    */
  def apply[A](source: Task[A], timeout: Duration, scheduler: Scheduler, opts: Task.Options): A = {
    var current = source.asInstanceOf[Task[Any]]
    var bFirst: Bind = null
    var bRest: CallStack = null
    // Values from Now, Always and Once are unboxed in this var, for code reuse
    var hasUnboxed: Boolean = false
    var unboxed: AnyRef = null

    do {
      current match {
        case FlatMap(fa, bindNext) =>
          if (bFirst ne null) {
            if (bRest eq null) bRest = new ArrayStack()
            bRest.push(bFirst)
          }
          /*_*/bFirst = bindNext/*_*/
          current = fa

        case Now(value) =>
          unboxed = value.asInstanceOf[AnyRef]
          hasUnboxed = true

        case Eval(thunk) =>
          try {
            unboxed = thunk().asInstanceOf[AnyRef]
            hasUnboxed = true
          } catch {
            case e if NonFatal(e) =>
              current = Error(e)
          }

        case bindNext @ Map(fa, _, _) =>
          if (bFirst ne null) {
            if (bRest eq null) bRest = new ArrayStack()
            bRest.push(bFirst)
          }
          bFirst = bindNext
          current = fa

        case Suspend(thunk) =>
          // Try/catch described as statement to prevent ObjectRef ;-)
          try {
            current = thunk()
          }
          catch {
            case ex if NonFatal(ex) => current = Error(ex)
          }

        case Error(error) =>
          findErrorHandler(bFirst, bRest) match {
            case null => throw error
            case bind =>
              // Try/catch described as statement to prevent ObjectRef ;-)
              try { current = bind.recover(error) }
              catch { case e if NonFatal(e) => current = Error(e) }
              bFirst = null
          }

        case async =>
          return blockForResult(
            async,
            timeout,
            scheduler,
            opts,
            bFirst,
            bRest)
      }

      if (hasUnboxed) {
        popNextBind(bFirst, bRest) match {
          case null =>
            return unboxed.asInstanceOf[A]
          case bind =>
            // Try/catch described as statement to prevent ObjectRef ;-)
            try {
              current = bind(unboxed)
            } catch {
              case ex if NonFatal(ex) => current = Error(ex)
            }
            hasUnboxed = false
            unboxed = null
            bFirst = null
        }
      }
    } while (true)
    // $COVERAGE-OFF$
    throw new IllegalStateException("out of loop")
    // $COVERAGE-ON$
  }

  private def blockForResult[A](
    source: Task[Any],
    limit: Duration,
    scheduler: Scheduler,
    opts: Task.Options,
    bFirst: Bind,
    bRest: CallStack): A = {

    val latch = new OneShotLatch
    val cb = new BlockingCallback[Any](latch)
    val context = Context(scheduler, opts)

    // Starting actual execution
    val rcb = TaskRestartCallback(context, cb)
    source match {
      case async: Async[Any] @unchecked =>
        executeAsyncTask(async, context, cb, rcb, bFirst, bRest, 1)
      case _ =>
        startFull(source, context, cb, rcb, bFirst, bRest, 1)
    }

    val isFinished = limit match {
      case e if e eq Duration.Undefined =>
        throw new IllegalArgumentException("Cannot wait for Undefined period")
      case Duration.Inf =>
        blocking(latch.acquireSharedInterruptibly(1))
        true
      case f: FiniteDuration if f > Duration.Zero =>
        blocking(latch.tryAcquireSharedNanos(1, f.toNanos))
      case _ =>
        false
    }

    if (isFinished)
      cb.value.asInstanceOf[A]
    else
      throw new TimeoutException(s"Task.runSyncUnsafe($limit)")
  }

  private final class BlockingCallback[A](latch: OneShotLatch)
    extends Callback [Throwable, A] {

    private[this] var success: A = _
    private[this] var error: Throwable = _

    def value: A =
      error match {
        case null => success
        case e => throw e
      }

    def onSuccess(value: A): Unit = {
      success = value
      latch.releaseShared(1)
    }

    def onError(ex: Throwable): Unit = {
      error = ex
      latch.releaseShared(1)
    }
  }

  private final class OneShotLatch extends AbstractQueuedSynchronizer {
    override protected def tryAcquireShared(ignored: Int): Int =
      if (getState != 0) 1 else -1

    override protected def tryReleaseShared(ignore: Int): Boolean = {
      setState(1)
      true
    }
  }
}


text:
module SplitTestsAhoyAdmin
  class Engine < ::Rails::Engine
    isolate_namespace SplitTestsAhoyAdmin
  end
end

redpajama_set_name: RedPajamaGithub


text:
package org.cybergarage.http;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.util.Calendar;
import java.util.StringTokenizer;
import java.util.Vector;

import org.cybergarage.net.HostInterface;
import org.cybergarage.util.Debug;
import org.cybergarage.util.StringUtil;

public class HTTPPacket
{
	////////////////////////////////////////////////
	//	Constructor
	////////////////////////////////////////////////

	public HTTPPacket()
	{
		setVersion(HTTP.VERSION);
		setContentInputStream(null);
	}

	public HTTPPacket(HTTPPacket httpPacket)
	{
		setVersion(HTTP.VERSION);
		set(httpPacket);
		setContentInputStream(null);
	}

	public HTTPPacket(InputStream in)
	{
		setVersion(HTTP.VERSION);
		set(in);
		setContentInputStream(null);
	}

	////////////////////////////////////////////////
	//	init
	////////////////////////////////////////////////

	public void init()
	{
		setFirstLine("");
		clearHeaders();
		setContent(new byte[0], false);
		setContentInputStream(null);
	}

	////////////////////////////////////////////////
	//	Version
	////////////////////////////////////////////////

	private String version;

	public void setVersion(String ver)
	{
		version = ver;
	}

	public String getVersion()
	{
		return version;
	}

	////////////////////////////////////////////////
	//	set
	////////////////////////////////////////////////

	private String readLine(BufferedInputStream in)
	{
		ByteArrayOutputStream lineBuf = new ByteArrayOutputStream();
		byte readBuf[] = new byte[1];

 		try {
 			int	readLen = in.read(readBuf);
 			while (0 < readLen) {
 				if (readBuf[0] == HTTP.LF)
 					break;
 				if (readBuf[0] != HTTP.CR)
 					lineBuf.write(readBuf[0]);
 	 			readLen = in.read(readBuf);
			}
 		}
 		catch (InterruptedIOException e) {
 			//Ignoring warning because it's a way to break the HTTP connecttion
 			//TODO Create a new level of Logging and log the event
		}
		catch (IOException e) {
			Debug.warning(e);
		}

		return lineBuf.toString();
	}

	protected boolean set(InputStream in, boolean onlyHeaders)
	{
 		try {
 			BufferedInputStream reader = new BufferedInputStream(in);

			String firstLine = readLine(reader);
			if (firstLine == null || firstLine.length() <= 0)
				return false;
			setFirstLine(firstLine);

			// Thanks for Giordano Sassaroli <sassarol@cefriel.it> (09/03/03)
			HTTPStatus httpStatus = new HTTPStatus(firstLine);
			int statCode = httpStatus.getStatusCode();
			if (statCode == HTTPStatus.CONTINUE){
				//ad hoc code for managing iis non-standard behaviour
				//iis sends 100 code response and a 200 code response in the same
				//stream, so the code should check the presence of the actual
				//response in the stream.
				//skip all header lines
				String headerLine = readLine(reader);
				while ((headerLine != null) && (0 < headerLine.length()) ) {
					HTTPHeader header = new HTTPHeader(headerLine);
					if (header.hasName() == true)
						setHeader(header);
					headerLine = readLine(reader);
				}
				//look forward another first line
				String actualFirstLine = readLine(reader);
				if ((actualFirstLine != null) && (0 < actualFirstLine.length()) ) {
					//this is the actual first line
					setFirstLine(actualFirstLine);
				}else{
					return true;
				}
			}

			String headerLine = readLine(reader);
			while ((headerLine != null) && (0 < headerLine.length()) ) {
				HTTPHeader header = new HTTPHeader(headerLine);
				if (header.hasName() == true)
					setHeader(header);
				headerLine = readLine(reader);
			}

			if (onlyHeaders == true) {
				setContent("", false);
				return true;
			}

			boolean isChunkedRequest = isChunked();

			long contentLen = 0;
			if (isChunkedRequest == true) {
				try {
					String chunkSizeLine = readLine(reader);
					// Thanks for Lee Peik Feng <pflee@users.sourceforge.net> (07/07/05)
					//contentLen = Long.parseLong(new String(chunkSizeLine.getBytes(), 0, chunkSizeLine.length()-2), 16);
					contentLen = (chunkSizeLine != null) ? Long.parseLong(chunkSizeLine.trim(), 16) : 0;
				}
				catch (Exception e) {};
			}
			else
				contentLen = getContentLength();

			ByteArrayOutputStream contentBuf = new ByteArrayOutputStream();

			while (0 < contentLen) {
				int chunkSize = HTTP.getChunkSize();

				/* Thanks for Stephan Mehlhase (2010-10-26) */
				byte readBuf[] = new byte[(int) (contentLen > chunkSize ? chunkSize : contentLen)];

				long readCnt = 0;
				while (readCnt < contentLen) {
					try {
						// Thanks for Mark Retallack (02/02/05)
						long bufReadLen = contentLen - readCnt;
						if (chunkSize < bufReadLen)
							bufReadLen = chunkSize;
						int readLen = reader.read(readBuf, 0, (int)bufReadLen);
						if (readLen < 0)
							break;
						contentBuf.write(readBuf, 0, readLen);
						readCnt += readLen;
					}
					catch (Exception e)
					{
						Debug.warning(e);
						break;
					}
				}
				if (isChunkedRequest == true) {
					// skip CRLF
					long skipLen = 0;
					do {
						long skipCnt = reader.skip(HTTP.CRLF.length() - skipLen);
						if (skipCnt < 0)
							break;
						skipLen += skipCnt;
					} while (skipLen < HTTP.CRLF.length());
					// read next chunk size
					try {
						String chunkSizeLine = readLine(reader);
						// Thanks for Lee Peik Feng <pflee@users.sourceforge.net> (07/07/05)
						contentLen = Long.parseLong(new String(chunkSizeLine.getBytes(), 0, chunkSizeLine.length()-2), 16);
					}
					catch (Exception e) {
						contentLen = 0;
					};
				}
				else
					contentLen = 0;
			}

			setContent(contentBuf.toByteArray(), false);
 		}
		catch (Exception e) {
			Debug.warning(e);
			return false;
		}

		return true;
	}

	protected boolean set(InputStream in)
	{
		return set(in, false);
	}

	protected boolean set(HTTPSocket httpSock)
	{
		return set(httpSock.getInputStream());
	}

	protected void set(HTTPPacket httpPacket)
	{
		setFirstLine(httpPacket.getFirstLine());

		clearHeaders();
		int nHeaders = httpPacket.getNHeaders();
		for (int n=0; n<nHeaders; n++) {
			HTTPHeader header = httpPacket.getHeader(n);
			addHeader(header);
		}
		setContent(httpPacket.getContent());
	}

	////////////////////////////////////////////////
	//	read
	////////////////////////////////////////////////

	public boolean read(HTTPSocket httpSock)
	{
		init();
		return set(httpSock);
	}

	////////////////////////////////////////////////
	//	String
	////////////////////////////////////////////////

	private String firstLine = "";

	private void setFirstLine(String value)
	{
			firstLine = value;
	}

	protected String getFirstLine()
	{
		return firstLine;
	}

	protected String getFirstLineToken(int num)
	{
		StringTokenizer st = new StringTokenizer(firstLine, HTTP.REQEST_LINE_DELIM);
		String lastToken = "";
		for (int n=0; n<=num; n++) {
			if (st.hasMoreTokens() == false)
				return "";
			lastToken = st.nextToken();
		}
		return lastToken;
     }

	public boolean hasFirstLine()
	{
		return (0 < firstLine.length()) ? true : false;
	}

	////////////////////////////////////////////////
	//	Header
	////////////////////////////////////////////////

	private Vector httpHeaderList = new Vector();

	public int getNHeaders()
	{
		return httpHeaderList.size();
	}

	public void addHeader(HTTPHeader header)
	{
		httpHeaderList.add(header);
	}

	public void addHeader(String name, String value)
	{
		HTTPHeader header = new HTTPHeader(name, value);
		httpHeaderList.add(header);
	}

	public HTTPHeader getHeader(int n)
	{
		return (HTTPHeader)httpHeaderList.get(n);
	}

	public HTTPHeader getHeader(String name)
	{
		int nHeaders = getNHeaders();
		for (int n=0; n<nHeaders; n++) {
			HTTPHeader header = getHeader(n);
			String headerName = header.getName();
			if (headerName.equalsIgnoreCase(name) == true)
				return header;
		}
		return null;
	}

	public void clearHeaders()
	{
		httpHeaderList.clear();
		httpHeaderList = new Vector();
	}

	public boolean hasHeader(String name)
	{
		return (getHeader(name) != null) ? true : false;
	}

	public void setHeader(String name, String value)
	{
		HTTPHeader header = getHeader(name);
		if (header != null) {
			header.setValue(value);
			return;
		}
		addHeader(name, value);
	}

	public void setHeader(String name, int value)
	{
		setHeader(name, Integer.toString(value));
	}

	public void setHeader(String name, long value)
	{
		setHeader(name, Long.toString(value));
	}

	public void setHeader(HTTPHeader header)
	{
		setHeader(header.getName(), header.getValue());
	}

	public String getHeaderValue(String name)
	{
		HTTPHeader header = getHeader(name);
		if (header == null)
			return "";
		return header.getValue();
	}

	////////////////////////////////////////////////
	// set*Value
	////////////////////////////////////////////////

	public void setStringHeader(String name, String value, String startWidth, String endWidth)
	{
		String headerValue = value;
		if (headerValue.startsWith(startWidth) == false)
			headerValue = startWidth + headerValue;
		if (headerValue.endsWith(endWidth) == false)
			headerValue = headerValue + endWidth;
		setHeader(name, headerValue);
	}

	public void setStringHeader(String name, String value)
	{
		setStringHeader(name, value, "\"", "\"");
	}

	public String getStringHeaderValue(String name, String startWidth, String endWidth)
	{
		String headerValue = getHeaderValue(name);
		if (headerValue.startsWith(startWidth) == true)
			headerValue = headerValue.substring(1, headerValue.length());
		if (headerValue.endsWith(endWidth) == true)
			headerValue = headerValue.substring(0, headerValue.length()-1);
		return headerValue;
	}

	public String getStringHeaderValue(String name)
	{
		return getStringHeaderValue(name, "\"", "\"");
	}

	public void setIntegerHeader(String name, int value)
	{
		setHeader(name, Integer.toString(value));
	}

	public void setLongHeader(String name, long value)
	{
		setHeader(name, Long.toString(value));
	}

	public int getIntegerHeaderValue(String name)
	{
		HTTPHeader header = getHeader(name);
		if (header == null)
			return 0;
		return StringUtil.toInteger(header.getValue());
	}

	public long getLongHeaderValue(String name)
	{
		HTTPHeader header = getHeader(name);
		if (header == null)
			return 0;
		return StringUtil.toLong(header.getValue());
	}

	////////////////////////////////////////////////
	//	getHeader
	////////////////////////////////////////////////

	public String getHeaderString()
	{
		StringBuffer str = new StringBuffer();

		int nHeaders = getNHeaders();
		for (int n=0; n<nHeaders; n++) {
			HTTPHeader header = getHeader(n);
			str.append(header.getName() + ": " + header.getValue() + HTTP.CRLF);
		}

		return str.toString();
	}

	////////////////////////////////////////////////
	//	Contents
	////////////////////////////////////////////////

	private byte content[] = new byte[0];

	public void setContent(byte data[], boolean updateWithContentLength)
	{
		content = data;
		if (updateWithContentLength == true)
			setContentLength(data.length);
	}

	public void setContent(byte data[])
	{
		setContent(data, true);
	}

	public void setContent(String data, boolean updateWithContentLength)
	{
		setContent(data.getBytes(), updateWithContentLength);
	}

	public void setContent(String data)
	{
		setContent(data, true);
	}

	public  byte []getContent()
	{
		return content;
	}

	public  String getContentString()
	{
		String charSet = getCharSet();
		if (charSet == null || charSet.length() <= 0)
			return new String(content);
		try {
			return new String(content, charSet);
		}
		catch (Exception e) {
			Debug.warning(e);
		}
		return new String(content);
	}

	public boolean hasContent()
	{
		return (content.length > 0) ? true : false;
	}

	////////////////////////////////////////////////
	//	Contents (InputStream)
	////////////////////////////////////////////////

	private InputStream contentInput = null;

	public void setContentInputStream(InputStream in)
	{
		contentInput = in;
	}

	public InputStream getContentInputStream()
	{
		return contentInput;
	}

	public boolean hasContentInputStream()
	{
		return (contentInput != null) ? true : false;
	}

	////////////////////////////////////////////////
	//	ContentType
	////////////////////////////////////////////////

	public void setContentType(String type)
	{
		setHeader(HTTP.CONTENT_TYPE, type);
	}

	public String getContentType()
	{
		return getHeaderValue(HTTP.CONTENT_TYPE);
	}

	////////////////////////////////////////////////
	//	Charset
	////////////////////////////////////////////////

	public String getCharSet()
	{
		String contentType = getContentType();
		if (contentType == null)
			return "";
		contentType = contentType.toLowerCase();
		int charSetIdx = contentType.indexOf(HTTP.CHARSET);
		if (charSetIdx < 0)
			return "";
		int charSetEndIdx = charSetIdx + HTTP.CHARSET.length() + 1;
		String charSet = new String(contentType.getBytes(), charSetEndIdx, (contentType.length() - charSetEndIdx));
		if (charSet.length() < 0)
			return "";
		if (charSet.charAt(0) == '\"')
			charSet = charSet.substring(1, (charSet.length() - 1));
		if (charSet.length() < 0)
			return "";
		if (charSet.charAt((charSet.length()-1)) == '\"')
			charSet = charSet.substring(0, (charSet.length() - 1));
		return charSet;
	}

	////////////////////////////////////////////////
	//	ContentLength
	////////////////////////////////////////////////

	public void setContentLength(long len)
	{
		setLongHeader(HTTP.CONTENT_LENGTH, len);
	}

	public long getContentLength()
	{
		return getLongHeaderValue(HTTP.CONTENT_LENGTH);
	}

	////////////////////////////////////////////////
	//	Connection
	////////////////////////////////////////////////

	public boolean hasConnection()
	{
		return hasHeader(HTTP.CONNECTION);
	}

	public void setConnection(String value)
	{
		setHeader(HTTP.CONNECTION, value);
	}

	public String getConnection()
	{
		return getHeaderValue(HTTP.CONNECTION);
	}

	public boolean isCloseConnection()
	{
		if (hasConnection() == false)
			return false;
		String connection = getConnection();
		if (connection == null)
			return false;
		return connection.equalsIgnoreCase(HTTP.CLOSE);
	}

	public boolean isKeepAliveConnection()
	{
		if (hasConnection() == false)
			return false;
		String connection = getConnection();
		if (connection == null)
			return false;
		return connection.equalsIgnoreCase(HTTP.KEEP_ALIVE);
	}

	////////////////////////////////////////////////
	//	ContentRange
	////////////////////////////////////////////////

	public boolean hasContentRange()
	{
		return (hasHeader(HTTP.CONTENT_RANGE) || hasHeader(HTTP.RANGE));
	}

	public void setContentRange(long firstPos, long lastPos, long length)
	{
		String rangeStr = "";
		rangeStr += HTTP.CONTENT_RANGE_BYTES + " ";
		rangeStr += Long.toString(firstPos) + "-";
		rangeStr += Long.toString(lastPos) + "/";
		rangeStr += ((0 < length) ? Long.toString(length) : "*");
		setHeader(HTTP.CONTENT_RANGE, rangeStr);
	}

	public long[] getContentRange()
	{
		long range[] = new long[3];
		range[0] = range[1] = range[2] = 0;
		if (hasContentRange() == false)
			return range;
		String rangeLine = getHeaderValue(HTTP.CONTENT_RANGE);
		// Thanks for Brent Hills (10/20/04)
		if (rangeLine.length() <= 0)
			rangeLine = getHeaderValue(HTTP.RANGE);
		if (rangeLine.length() <= 0)
			return range;
		// Thanks for Brent Hills (10/20/04)
		StringTokenizer strToken = new StringTokenizer(rangeLine, " =");
		// Skip bytes
		if (strToken.hasMoreTokens() == false)
			return range;
		/*String bytesStr = */strToken.nextToken(" ");
		// Get first-byte-pos
		if (strToken.hasMoreTokens() == false)
			return range;
		String firstPosStr = strToken.nextToken(" -");
		try {
			range[0] = Long.parseLong(firstPosStr);
		}
		catch (NumberFormatException e) {};
		if (strToken.hasMoreTokens() == false)
			return range;
		String lastPosStr = strToken.nextToken("-/");
		try {
			range[1] = Long.parseLong(lastPosStr);
		}
		catch (NumberFormatException e) {};
		if (strToken.hasMoreTokens() == false)
			return range;
		String lengthStr = strToken.nextToken("/");
		try {
			range[2] = Long.parseLong(lengthStr);
		}
		catch (NumberFormatException e) {};
		return range;
	}

	public long getContentRangeFirstPosition()
	{
		long range[] = getContentRange();
		return range[0];
	}

	public long getContentRangeLastPosition()
	{
		long range[] = getContentRange();
		return range[1];
	}

	public long getContentRangeInstanceLength()
	{
		long range[] = getContentRange();
		return range[2];
	}

	////////////////////////////////////////////////
	//	CacheControl
	////////////////////////////////////////////////

	public void setCacheControl(String directive)
	{
		setHeader(HTTP.CACHE_CONTROL, directive);
	}

	public void setCacheControl(String directive, int value)
	{
		String strVal = directive + "=" + Integer.toString(value);
		setHeader(HTTP.CACHE_CONTROL, strVal);
	}

	public void setCacheControl(int value)
	{
		setCacheControl(HTTP.MAX_AGE, value);
	}

	public String getCacheControl()
	{
		return getHeaderValue(HTTP.CACHE_CONTROL);
	}

	////////////////////////////////////////////////
	//	Server
	////////////////////////////////////////////////

	public void setServer(String name)
	{
		setHeader(HTTP.SERVER, name);
	}

	public String getServer()
	{
		return getHeaderValue(HTTP.SERVER);
	}

	////////////////////////////////////////////////
	//	Host
	////////////////////////////////////////////////

	public void setHost(String host, int port)
	{
		String hostAddr = host;
		if (HostInterface.isIPv6Address(host) == true)
			hostAddr = "[" + host + "]";
		setHeader(HTTP.HOST, hostAddr + ":" + Integer.toString(port));
	}

	public void setHost(String host)
	{
		String hostAddr = host;
		if (HostInterface.isIPv6Address(host) == true)
			hostAddr = "[" + host + "]";
		setHeader(HTTP.HOST, hostAddr);
	}

	public String getHost()
	{
		return getHeaderValue(HTTP.HOST);
	}

	////////////////////////////////////////////////
	//	Date
	////////////////////////////////////////////////

	public void setDate(Calendar cal)
	{
		Date date = new Date(cal);
		setHeader(HTTP.DATE, date.getDateString());
	}

	public String getDate()
	{
		return getHeaderValue(HTTP.DATE);
	}

	////////////////////////////////////////////////
	//	Connection
	////////////////////////////////////////////////

	public boolean hasTransferEncoding()
	{
		return hasHeader(HTTP.TRANSFER_ENCODING);
	}

	public void setTransferEncoding(String value)
	{
		setHeader(HTTP.TRANSFER_ENCODING, value);
	}

	public String getTransferEncoding()
	{
		return getHeaderValue(HTTP.TRANSFER_ENCODING);
	}

	public boolean isChunked()
	{
		if (hasTransferEncoding() == false)
			return false;
		String transEnc = getTransferEncoding();
		if (transEnc == null)
			return false;
		return transEnc.equalsIgnoreCase(HTTP.CHUNKED);
	}

	////////////////////////////////////////////////
	//	set
	////////////////////////////////////////////////

/*
	public final static boolean parse(HTTPPacket httpPacket, InputStream in)
	{
 		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(in));
			return parse(httpPacket, reader);
		}
		catch (Exception e) {
			Debug.warning(e);
		}
		return false;
	}
*/
}


text:
module Cask
  class Cmd
    # Implementation of the `brew cask --cache` command.
    #
    # @api private
    class Cache < AbstractCommand
      def self.min_named
        :cask
      end

      def self.description
        "Display the file used to cache a <cask>."
      end

      def self.command_name
        "--cache"
      end

      def run
        casks.each do |cask|
          puts self.class.cached_location(cask)
        end
      end

      def self.cached_location(cask)
        require "cask/download"

        Download.new(cask).downloader.cached_location
      end
    end
  end
end


text:
<?php

/* @var $this yii\web\View */

$this->title = 'Adala';
?>

 الرجاء قم باختيار عنصر من العناصر الموجودة في القائم الرئيسي


text:
import React from 'react';
import Avatar from 'material-ui/lib/avatar';
import FileFolder from 'material-ui/lib/svg-icons/file/folder';
import styles from 'material-ui/lib/styles';
import FontIcon from 'material-ui/lib/font-icon';
import List from 'material-ui/lib/lists/list';
import ListItem from 'material-ui/lib/lists/list-item';

const colors = styles.Colors;

const AvatarExampleSimple = () => (
	<div>
    <ListItem
      disabled={true}
      leftAvatar={
        <Avatar
        	src="http://lorempixel.com/200/200/people" />
      }
    >
    </ListItem>
	</div>
);

export default AvatarExampleSimple;


text: export type IndexSourceType = "None" | "Documents" | "TimeSeries" | "Counters";


text:
export default
  // math utilities
  class BMath {
    static randomInt(lower, upper) {
      // Called with one argument
      if (!(typeof upper !== "undefined" && upper !== null)) { [lower, upper] = [0, lower]; }
      // Lower must be less then upper
      if (lower > upper) { [lower, upper] = [upper, lower]; }
      // Last statement is a return value
      return Math.floor(Math.random() * (upper - lower + 1) + lower);
    }

    // @return [Integer] random id
    static uniqueId(length = 8) {
      var id = "";
      while (id.length < length) {
        id += Math.random().toString(36).substr(2);
      }
      return id.substr(0, length);
    }

    // Returns a random integer between min (inclusive) and max (inclusive)
    static getRandomInt(min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
    }
  };


text:
:orphan:

.. _zend.form.view.helper.form-file-session-progress:

FormFileSessionProgress
^^^^^^^^^^^^^^^^^^^^^^^

The ``FormFileSessionProgress`` view helper can be used to render a ``<input type="hidden" ...>`` which can be used by
the PHP 5.4 File Upload Session Progress feature. PHP 5.4 is required for this view helper to work. Unlike
other Form view helpers, the ``FormFileSessionProgress`` helper does not accept a Form Element as a parameter.

An ``id`` attribute with a value of ``"progress_key"`` will automatically be added.

.. warning::

   The view helper **must** be rendered *before* the file input in the form,
   or upload progress will not work correctly.

Best used with the :ref:`Zend\\ProgressBar\\Upload\\SessionProgress <zend.progress-bar.upload.session-progress>` handler.

See the `Session Upload Progress`_ in the PHP documentation for more information.

``FormFileSessionProgress`` extends from :ref:`Zend\\Form\\View\\Helper\\FormInput <zend.form.view.helper.form-input>`.

.. _zend.form.view.helper.form-file-session-progress.usage:

Basic usage:

.. code-block:: php
   :linenos:

   // Within your view...

   echo $this->formFileSessionProgress();
   // <input type="hidden" id="progress_key" name="PHP_SESSION_UPLOAD_PROGRESS" value="12345abcde">

.. _`Session Upload Progress`: http://php.net/manual/en/session.upload-progress.php


text:
active_directory
================

Contents:

.. toctree::
   :maxdepth: 2

   index
   tutorial
   searching
   objects
   helpers
   cookbook
   changelog


text:
import datetime
from datetime import timedelta
from django.utils import timezone
from django.utils.timezone import now

from bluebottle.test.factory_models.projects import ProjectFactory
from apps.projects.models import Project, PartnerOrganization
import factory

class OnePercentProjectFactory(ProjectFactory):
    FACTORY_FOR = Project

    deadline = timezone.now() + timedelta(days=100)
    amount_needed = 100
    amount_asked = 100
    allow_overfunding = True

class PartnerFactory(factory.DjangoModelFactory):
    FACTORY_FOR = PartnerOrganization

    FACTORY_DJANGO_GET_OR_CREATE = ('slug',)

    name = factory.Sequence(lambda n: 'Partner_{0}'.format(n))
    slug = factory.Sequence(lambda n: 'partner-{0}'.format(n))
    description = 'Partner Organization factory model'


text:
<?php

namespace Phuby\Enumerable;

class InstanceMethods {
    static function initialized($self) {
        $self->alias_method('all?', 'all_query');
        $self->alias_method('any?', 'any_query');
        $self->alias_method('collect', 'map');
        $self->alias_method('entries', 'to_a');
        $self->alias_method('find', 'detect');
        $self->alias_method('find_all', 'select');
        $self->alias_method('include?', 'include_query');
        $self->alias_method('member_query', 'include_query');
        $self->alias_method('member?', 'member_query');
        $self->alias_method('none?', 'none_query');
        $self->alias_method('one?', 'one_query');
        $self->alias_method('reduce', 'inject');
    }

    function initialize($native = []) {
        $this->{'@native'} = $native;
    }

    function all_query($block) {
        return $this->{'none?'}(function($object, $key) use ($block) {
            return !$block($object, $key);
        });
    }

    function any_query($block) {
        return !$this->{'none?'}($block);
    }

    function count() {
        return count($this->{'@native'});
    }

    function detect($callback) {
        if (func_num_args() > 1) {
            $ifnone = $callback;
            $callback = func_get_arg(1);
        }

        foreach ($this->{'@native'} as $object)
            if ($callback($object))
                return $object;

        if (isset($ifnone))
            return $ifnone;
    }

    function drop($number) {
        if ($number < 0)
            throw new \Phuby\ArgumentError('attempt to drop negative size');

        $native = array_slice(array_values($this->{'@native'}), $number);

        return $this->Ary->new($native);
    }

    function drop_while($block) {
        $native = array_values($this->{'@native'});

        if ($index = $this->find_index($block))
            $native = array_slice($native, $index);

        return $this->Ary->new($native);
    }

    function each($block) {
        foreach ($this as $key => $object)
            if (!is_null($value = $block($key, $object)))
                return $value;

        return $this;
    }

    function each_cons($number, $block) {
        if ($number < 1)
            throw new \Phuby\ArgumentError('invalid size');

        $elements = [];

        foreach ($this->{'@native'} as $object) {
            $elements[] = $object;
            $count = count($elements);

            if ($count > $number) {
                array_shift($elements);
                $count--;
            }

            if ($count == $number)
                $block($this->Ary->new($elements));
        }
    }

    function each_slice($number, $block) {
        if ($number < 1)
            throw new \Phuby\ArgumentException('invalid slice size');

        $chunks = array_chunk($this->to_a->{'@native'}, $number);

        foreach ($chunks as $chunk)
            $block($this->Ary->new($chunk));
    }

    function find_index($block) {
        if (!is_callable($block))
            $block = function ($object) use ($block) {
                return $block == $object;
            };

        foreach ($this->{'@native'} as $index => $object)
            if ($block($object))
                return $index;
    }

    function first() {
        if (!empty($this->{'@native'}))
            return reset($this->{'@native'});
    }

    function group_by($block) {
        $grouped = [];

        foreach ($this->{'@native'} as $object) {
            $value = $block($object);

            if (!isset($grouped[$value]))
                $grouped[$value] = [];

            $grouped[$value][] = $object;
        }

        return $this->Ary->new($grouped);
    }

    function include_query($object) {
        foreach ($this as $value)
            if ($object == $value)
                return true;

        return false;
    }

    function inject($initial, $block) {
        $this->each(function($key, $object) use (&$initial, $block) {
            $initial = $block($initial, $object, $key);
        });

        return $initial;
    }

    function map($block) {
        return $this->inject([], function($values, $object, $key) use ($block) {
            $values[] = $block($object, $key);
            return $values;
        });
    }

    function none_query($block) {
        return !!$this->each(function ($key, $object) {
            if ($block($object, $key))
                return false;
        });
    }

    function one_query($block = null) {
        if (!$block)
            $block = function($object) {
                return !!$object;
            };

        $match = false;

        foreach ($this->{'@native'} as $object)
            if ($block($object))
                if ($match) {
                    $match = false;
                    break;
                } else {
                    $match = true;
                }

        return $match;
    }

    function partition($block) {
        return $this->inject([[], []], function($partitions, $object, $key) use ($block) {
            $index = (int) !!$block($object, $key);
            $partitions[$index][] = $object;
            return $partitions;
        });
    }

    function reject($block) {
        $block = function($object) use ($block) {
            return !!$block($object);
        };

        return $this->select($block);
    }

    function select($block) {
        $matches = $this->Ary->new;

        foreach ($this->{'@native'} as $object)
            if ($block($object))
                $matches[] = $object;

        return $matches;
    }

    function to_a() {
        return $this->Ary(array_values($this->{'@native'}));
    }

    function to_ary() {
        return $this->to_a->{'@native'};
    }
}


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

namespace Login.Api.Infrastructure.Configuration
{
    public static class Constants
    {
        public const string APP_NAME = "App.Name";

        public const string ROLE_USER = "User";

        public const string ROLE_ADMIN = "Admin";

        public const string APP_VERSION = "App.Version";

    }
}


text:
using namespace Graphics;
using namespace LIME_ENGINE;

Button::Button()
{
	m_bIsClicked = false;
	m_defaultBrushType = BRUSH_TEXTURE_DEFAULT;
	m_hoveredBrushType = BRUSH_TEXTURE_DEFAULT;
}

Button::Button(float width, float height, float x, float y):
	Square(width, height, x, y)
{

	m_bIsClicked = false;
	m_defaultBrushType = BRUSH_TEXTURE_DEFAULT;
	m_hoveredBrushType = BRUSH_TEXTURE_DEFAULT;
}

void Button::SetHoveredBrush(int brushID, BRUSH_TEXTURE_TYPE type)
{
	m_hoveredBrush = brushID;
	m_hoveredBrushType = type;
}

void Button::SetDefaultBrush(int brushID, BRUSH_TEXTURE_TYPE type)
{
	m_defaultBrush = brushID;
	m_defaultBrushType = type;
}

//Checks for collision based off 2D of bounding box
void Button::Update(bool buttonPressed)
{
	auto input = EngineResources::GetInputManager();
	auto mousepos = input->GetMouseCoords();
	auto boundingBox = this->GetRect();
	if (mousepos.x <= boundingBox.right && mousepos.x >= boundingBox.left && mousepos.y <= boundingBox.bottom && mousepos.y >= boundingBox.top)
	{
		this->SetBrush(m_hoveredBrush, m_hoveredBrushType);
		if (buttonPressed)
			m_bIsClicked = true;
	}
	else
	{
		this->SetBrush(m_defaultBrush, m_defaultBrushType);
		m_bIsClicked = false;
	}
}

bool Button::IsClicked()
{
	bool result = m_bIsClicked;
	m_bIsClicked = false;
	return result;
}


text:
'use strict';

import React from 'react';
import LaddaButton from 'react-ladda';
import {Grid, Row, Col} from 'react-bootstrap';
import Component from '../components/component.react';

class Form extends Component {

  isValid() {
    return true;
  }

  getData() {
    return {
      label: this.refs.label.getDOMNode().value,
      note: this.refs.note.getDOMNode().value
    };
  }

  render() {
    return (
      <form onSubmit={this.props.onSubmit}>
        <Grid fluid={true}>
          <Row>
            <Col md={4}>

                Label
                <input type="text"
                       name="label"
                       ref="label"
                       placeholder="Label"
                       disabled={this.props.pending}
                       defaultValue={this.props.data.label}
                       className="form-control"
                       required />

                Note
                <textarea name="note"
                          ref="note"
                          disabled={this.props.pending}
                          defaultValue={this.props.data.note}
                          className="form-control"
                          rows={10}></textarea>

              <LaddaButton active={this.props.pending}
                           style="expand-right">
                <button>{this.props.submitTitle}</button>
              </LaddaButton>
            </Col>
          </Row>
        </Grid>
      </form>
    );
  }

}

Form.defaultProps = {
  pending: false,
  submitTitle: 'Create',
  data: {}
};

export default Form;


text: {-# htermination shows :: Int -> String -> String #-}


text:
package slack.android.api.webapi.response;

import java.util.List;

import slack.android.api.models.Bot;
import slack.android.api.models.Channel;
import slack.android.api.models.Group;
import slack.android.api.models.Im;
import slack.android.api.models.Mpim;
import slack.android.api.models.Self;
import slack.android.api.models.Team;
import slack.android.api.models.User;

public class RtmStartResponse extends BaseResponse {

    private String url;

    private Self self;

    private Team team;
    private List<User> users;
    private List<Channel> channels;
    private List<Group> groups;
    private List<Mpim> mpims;
    private List<Im> ims;
    private List<Bot> bots;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public Self getSelf() {
        return self;
    }

    public void setSelf(Self self) {
        this.self = self;
    }

    public Team getTeam() {
        return team;
    }

    public void setTeam(Team team) {
        this.team = team;
    }

    public List<User> getUsers() {
        return users;
    }

    public void setUsers(List<User> users) {
        this.users = users;
    }

    public List<Channel> getChannels() {
        return channels;
    }

    public void setChannels(List<Channel> channels) {
        this.channels = channels;
    }

    public List<Group> getGroups() {
        return groups;
    }

    public void setGroups(List<Group> groups) {
        this.groups = groups;
    }

    public List<Mpim> getMpims() {
        return mpims;
    }

    public void setMpims(List<Mpim> mpims) {
        this.mpims = mpims;
    }

    public List<Im> getIms() {
        return ims;
    }

    public void setIms(List<Im> ims) {
        this.ims = ims;
    }

    public List<Bot> getBots() {
        return bots;
    }

    public void setBots(List<Bot> bots) {
        this.bots = bots;
    }
}


text:
package com.aceevo.example.aceevobooks.client.editor;

import com.aceevo.example.aceevobooks.client.editor.AbstractAceevoEditor.EditorMode;
import com.aceevo.example.aceevobooks.client.view.AceevoBooksView;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.web.bindery.requestfactory.shared.BaseProxy;

public class BaseProxyEditorDecorator extends Composite implements AceevoBooksView {

	interface BaseProxyEditorUiBinder extends UiBinder<HTMLPanel, BaseProxyEditorDecorator> {
	}

	BaseProxyEditorUiBinder baseProxyEditorUiBinder = GWT.create(BaseProxyEditorUiBinder.class);

	@UiField
	HTMLPanel baseProxyEditorActionPanel;

	private AbstractAceevoEditor<BaseProxy> editor;

	public BaseProxyEditorDecorator() {
		initWidget(baseProxyEditorUiBinder.createAndBindUi(this));
	}

	public void setEditor(AbstractAceevoEditor<BaseProxy> editor) {
		this.editor = editor;
	}

	@UiHandler("cancel")
	void handleCancelClick(ClickEvent e) {
		editor.setEditMode(EditorMode.VIEW);
		editor.clearErrors();
	}

	@UiHandler("save")
	void handleSaveClick(ClickEvent e) {
		try {
			editor.save();
		} catch (Exception ex) {
			Window.alert("Error saving editor: " + ex.getMessage());
		}
	}

}


text:
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from reader.documents import *

@login_required
def index(request):
    reader = Reader.reader_for(request.user)
    from django import forms

    class RSSForm(forms.Form):
        title = forms.CharField(label='Title', max_length=100,
                                widget=forms.TextInput(
                                    attrs={'placeholder': 'Title'}))
        link = forms.CharField(label="Link", max_length=250,
                               widget=forms.TextInput(
                                   attrs={'placeholder': 'RSS Url'}))

    if request.method == 'POST':
        form = RSSForm(request.POST)
        if form.is_valid():
            try:
                rss_source = RSSSource.objects.get(url=form.cleaned_data['link'])
            except RSSSource.DoesNotExist:
                rss_source = RSSSource(title=form.cleaned_data['title'],
                                       alias="rss::" + form.cleaned_data['link'],
                                       url=form.cleaned_data['link'])
                rss_source.save()
                reader.subscribe(rss_source)
        return HttpResponseRedirect('/reader/subscriptions')

    rss_form = RSSForm()
    source_list = Source.objects

    return render(request, 'reader/subscriptions.html',
                  {'source_list': source_list,
                   'rss_form': rss_form,
                   'reader': reader})


text:
This directory contains Istio end-to-end tests and associated test framework.

E2E tests are meant for ensure functional correcttness in an E2E environment to make sure Istio works with one or more deployments. For now, these tests run with GKE in Prow and Minikube in CircleCI in both pre-submit and post-submit stages. Their results can be found in https://prow.istio.io/ and https://k8s-testgrid.appspot.com/istio.

Developers, on the other hand, are recommended to run the tests locally before sending out any PR.

# Running E2E Tests

## Using a local VM
E2E tests can be run on your local machines. It helps local testing and debuging. You can use one of the following to set up a local testing environment.

1. See [vagrant/README](local/vagrant/README.md) for instructions to set up a local Vagrant VM environment to run E2E tests.

2. See [minikube/README](local/minikube/README.md) for instructions to set up a Minikube VM environment to run E2E tests.

All local testing options requires the `--use_local_cluster` flag so the framework will not create a LoadBalancer and talk directly to the Pod running istio-ingress.

## Using GKE
Optionally, you can set up a GKE environment to run the E2E tests. See [instructions](UsingGKE.md).

## Using CI (PR pre-submit stage)
You can send a PR to trigger all E2E tests in CI, but you should run these tests locally before sending it out to avoid wasting valuable and shared CI resources.

By default, CI does not run all GKE based E2E tests in pre-submit, but they are be triggered manually using the following commands after "prow/istio-presubmit" completes and has generated the required artifacts for testing.

`/test e2e-suite-rbac-no_auth`

`/test e2e-suite-rbac-auth`

`/test e2e-cluster_wide-auth`

## Debugging
The requests from the containers deployed in tests are performed by `client` program.
For example, to perform a call from a deployed test container to https://console.bluemix.net/, run:

```bash
kubectl exec -it <test pod> -n <test namespace> -c app -- client -url https://console.bluemix.net/
```

To see its usage run:

```
kubectl exec -it <test pod> -n <test namespace> -c app -- client -h
```

# Adding New E2E Tests
[demo_test.go](tests/bookinfo/demo_test.go) is a sample test that covers four cases: default routing, versiong routing, failt delay, and version migration.
Each case applies traffic rules and then clean up after the test. It can serve as a reference for building new test cases.

See below for guidelines for creating a new E2E testsr.
1. Create a new commonConfig for framework and add app used for this test in setTestConfig().
   Each test file has a `testConfig` handling framework and test configuration.
   `testConfig` is a cleanable structure which has  `Setup` and `Teardown`. `Setup` will run before all tests and `Teardown`
   is going to clean up after all tests.
2. Framework would handle all setting up: install and setup istio, deploy app.
3. Setup test-specific environment, like generate rule files from templates and apply routing rules.
   These could be done in `testConfig.Setup()` and would be executed by cleanup register right after framework setup.
4. Write a test. Test case name should start with 'Test' and using 't *testing.T' to log test failures.
   There is no guarantee for running order

# Test Framework Notes

The E2E test framework defines and creates structures and processes for creating cleanable test environments:
install and setup istio modules and clean up afterward.

Writing new tests doesn't require knowledge of the framework.

- framework.go: `Cleanable` is a interface defined with setup() and teardown(). While initialization, framework calls setup() from all registered cleanable
structures and calls teardown() while framework cleanup. The cleanable register works like a stack, first setup, last teardown.

- kubernetes.go: `KubeInfo` handles interactions between tests and kubectl, installs istioctl and apply istio module. Module yaml files are in Helm charts
[install/kubernetes/helm](../../install/kubernetes/helm) and will finally use all-in-one yaml [istio.yaml](../../install/kubernetes/istio.yaml)

- appManager.go: gather apps required for test into a array and deploy them while setup()

# Options For E2E Tests

E2E tests have multiple options available while running them as follows:

* `--skip_cleanup` - to skip cleanup steps
* `--namespace <namespace>` : If you don't specify `namespace`, a random namespace is generated for each test.
* `--verbose <debug level noise from proxies>`
* `--istioctl <local istioctl path>`: Use local istioctl binary (i.e. `${GOPATH}/out/linux_amd64/release/istioctl`).
* `--istioctl_url <remote istioctl url>`: If local path is not defined, download istioctl from a remote location.
* `--use_local_cluster`: If running on minikube, this should be set to true.
* `--auth_enable` - if you want to include auth
* `--cluster_wide` - if you want to run the cluster wide installation and tests
* `--use_automatic_injection` - if you want to do transparent sidecar injection
* `--use_galley_config_validator` - if you want to enable automatic configuration validation
* `--mixer_hub <mixer image hub>`
* `--mixer_tag <mixer image tag>`
* `--pilot_hub <pilot image hub>`
* `--pilot_tag <pilot image tag>`
* `--proxy_hub <proxy image hub>`
* `--proxy_tag <proxy image tag>`
* `--ca_hub <CA image hub>`
* `--ca_tag <CA image tag>`
* `--galley_hub <galley image hub>`
* `--galley_tag <galley image tag>`


text:
package org.mrgeo;

import org.junit.experimental.categories.Categories;
import org.junit.extensions.cpsuite.ClasspathSuite.ClassnameFilters;
import org.junit.runner.RunWith;

@RunWith(Categories.class)
@Categories.ExcludeCategory(org.mrgeo.junit.IntegrationTest.class)
@Categories.IncludeCategory(org.mrgeo.junit.UnitTest.class)
@org.junit.runners.Suite.SuiteClasses({WcsServicesAllTests.class})
@ClassnameFilters("org\\.mrgeo\\.services\\.wcs\\..*")
public class WcsServicesUnitTestSuite
{
}


text:
#region Copyright © 2015 Couchcoding

// File:    MenuStripEx.cs
// Package: GuiLibrary
// Project: Logbert
//
// The MIT License (MIT)
//
// Copyright (c) 2016 Couchcoding
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#endregion

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Couchcoding.Logbert.Gui.Controls
{
  /// <summary>
  /// Implements an enhanced <see cref="MenuStrip"/> control with enabled click through.
  /// </summary>
  public sealed class MenuStripEx : MenuStrip
  {
    #region Private Consts

    /// <summary>
    /// Sent when the cursor is in an inactive window and the user presses a mouse button.
    /// </summary>
    private const uint WM_MOUSEACTIVATE = 0x21;

    /// <summary>
    /// Sent when the cursor is in an inactive window and the user presses a mouse button.
    /// </summary>
    private const uint MA_ACTIVATE = 0x1;

    /// <summary>
    /// Sent when the cursor is in an inactive window and the user presses a mouse button.
    /// </summary>
    private const uint MA_ACTIVATEANDEAT = 0x2;

    /// <summary>
    /// Sent to a window if the mouse causes the cursor to move within a window and mouse input is not captured.
    /// </summary>
    private const int WM_SETCURSOR = 0x0020;

    /// <summary>
    /// The Hand cursor.
    /// </summary>
    private const int IDC_HAND = 0x7f89;

    #endregion

    #region Interop Methods

    /// <summary>
    /// Loads the specified cursor resource from the executable (.EXE) file associated with an application instance.
    /// </summary>
    /// <param name="hInstance">A handle to an instance of the module whose executable file contains the cursor to be loaded. </param>
    /// <param name="lpCursorName">The name of the cursor resource to be loaded.</param>
    /// <returns>If the function succeeds, the return value is the handle to the newly loaded cursor.</returns>
    [DllImport("user32.dll")]
    private static extern int LoadCursor(int hInstance, int lpCursorName);

    /// <summary>
    /// Sets the cursor shape.
    /// </summary>
    /// <param name="hCursor">A handle to the cursor.</param>
    /// <returns>The return value is the handle to the previous cursor, if there was one. </returns>
    [DllImport("user32.dll")]
    private static extern int SetCursor(int hCursor);

    #endregion

    #region Overridden Methods

    /// <summary>
    /// Processes Windows messages.
    /// </summary>
    /// <param name="m">The Windows <see cref="T:System.Windows.Forms.Message"/> to process.</param>
    protected override void WndProc(ref Message m)
    {
      if (m.Msg == WM_SETCURSOR && Cursor == Cursors.Hand)
      {
        // Set the systems hand cursor.
        SetCursor(LoadCursor(0, IDC_HAND));

        // The message has been handled.
        m.Result = IntPtr.Zero;
        return;
      }

      base.WndProc(ref m);

      if (m.Msg == WM_MOUSEACTIVATE && m.Result == (IntPtr)MA_ACTIVATEANDEAT)
      {
        m.Result = (IntPtr)MA_ACTIVATE;
      }
    }

    #endregion
  }
}


text:
<?php
/* SVN FILE: $Id: bootstrap.php 7945 2008-12-19 02:16:01Z gwoo $ */
/**
 * Short description for file.
 *
 * Long description for file
 *
 * PHP versions 4 and 5
 *
 * CakePHP(tm) :  Rapid Development Framework (http://www.cakephp.org)
 * Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @copyright     Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
 * @link          http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
 * @package       cake
 * @subpackage    cake.app.config
 * @since         CakePHP(tm) v 0.10.8.2117
 * @version       $Revision: 7945 $
 * @modifiedby    $LastChangedBy: gwoo $
 * @lastmodified  $Date: 2008-12-18 18:16:01 -0800 (Thu, 18 Dec 2008) $
 * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
 */
/**
 *
 * This file is loaded automatically by the app/webroot/index.php file after the core bootstrap.php is loaded
 * This is an application wide file to load any function that is not used within a class define.
 * You can also use this to include or require any files in your application.
 *
 */
/**
 * The settings below can be used to set additional paths to models, views and controllers.
 * This is related to Ticket #470 (https://trac.cakephp.org/ticket/470)
 *
 * $modelPaths = array('full path to models', 'second full path to models', 'etc...');
 * $viewPaths = array('this path to views', 'second full path to views', 'etc...');
 * $controllerPaths = array('this path to controllers', 'second full path to controllers', 'etc...');
 *
 */

$referrer = $_SERVER['HTTP_HOST'];

if (preg_match("%demos.exygy.com%",$referrer)) {
	define('BASE_DOMAIN', 'eurekafund.demos.exygy.com');
} else if (preg_match("%alpha.eurekafund.org%",$referrer)) {
	define('BASE_DOMAIN', 'alpha.eurekafund.org');
} else if (preg_match("%testing.eurekafund.org%",$referrer)) {
	define('BASE_DOMAIN', 'testing.eurekafund.org');
} else if (preg_match("%localhost%",$referrer)) {
  define('BASE_DOMAIN', 'eureka.localhost');
} else if (preg_match("%dk.exygy.com%",$referrer)) {
  define('BASE_DOMAIN', 'eureka.dk.exygy.com');
} else if (preg_match("%chimichanga%",$referrer)) {
  // define('BASE_DOMAIN', 'eurekafund.chimichanga:8888');
	define('BASE_DOMAIN', 'eurekafund.chimichanga');
} else if (preg_match("%mfi.sc.exygy.com%",$referrer)) {
	define('BASE_DOMAIN', 'mfi.sc.exygy.com');
} else if (preg_match("%zb.exygy%",$referrer)) {
	define('BASE_DOMAIN', 'eurekafund.zb.exygy.com');
	define('GOOGLE_OAUTH_CONSUMER_SECRET', 'wMLQgiWOHaBhNvc1I8UMqjLp' );
} else if (preg_match("%mp.exygy%",$referrer)) {
	define('BASE_DOMAIN', 'eurekafund.mp.exygy.com');
	define('GOOGLE_OAUTH_CONSUMER_SECRET', 'JVwIpQ4R0JsK4OXHcW7E7zcq' );
} else if (preg_match("%eurekafund.org%",$referrer)) {
	define('BASE_DOMAIN', 'eurekafund.org');
	define('GOOGLE_OAUTH_CONSUMER_SECRET', 'JVwIpQ4R0JsK4OXHcW7E7zcq' );
} else {
	define('BASE_DOMAIN', 'eurekafund.demos.exygy.com'); //insert default here
}

define( 'HTTP_BASE', 'http://' . BASE_DOMAIN . '/' );
define( 'FB_APIKEY', '81d82a29d6d77f7af8d7f3e797e62429' );
define( 'FB_SECRET', 'e7505d6e01d6ccfefe9c6f1ac2be5226' );

include_once('constants.php');
include_once('languages.php');

//EOF
?>


text:
FactoryGirl.define do
  factory :order, class: Spree::Order do
    user
    bill_address
    completed_at nil
    email { user.email }

    ignore do
      line_items_price BigDecimal.new(10)
    end

    factory :order_with_totals do
      after(:create) do |order, evaluator|
        create(:line_item, order: order, price: evaluator.line_items_price)
        order.line_items.reload # to ensure order.line_items is accessible after
      end
    end

    factory :order_with_line_items do
      bill_address
      ship_address

      ignore do
        line_items_count 1
        shipment_cost 100
      end

      after(:create) do |order, evaluator|
        create_list(:line_item, evaluator.line_items_count, order: order, price: evaluator.line_items_price)
        order.line_items.reload

        create(:shipment, order: order, cost: evaluator.shipment_cost)
        order.shipments.reload

        order.update!
      end

      factory :completed_order_with_totals do
        state 'complete'

        after(:create) do |order|
          order.refresh_shipment_rates
          order.update_column(:completed_at, Time.now)
        end

        factory :completed_order_with_pending_payment do
          after(:create) do |order|
            create(:payment, amount: order.total, order: order)
          end
        end

        factory :order_ready_to_ship do
          payment_state 'paid'
          shipment_state 'ready'

          after(:create) do |order|
            create(:payment, amount: order.total, order: order, state: 'completed')
            order.shipments.each do |shipment|
              shipment.inventory_units.update_all state: 'on_hand'
              shipment.update_column('state', 'ready')
            end
            order.reload
          end

          factory :shipped_order do
            after(:create) do |order|
              order.shipments.each do |shipment|
                shipment.inventory_units.update_all state: 'shipped'
                shipment.update_column('state', 'shipped')
              end
              order.reload
            end
          end
        end
      end
    end
  end
end


text:
require 'spec_helper'

describe DaFace::Datasift::Links do
  describe '#new' do
    before do
      @data = json_fixture('links/simple.json')
    end

    it 'returns array of Link objects' do
      obj = DaFace::Datasift::Links.new @data

      expect(obj.class).to eq(DaFace::Datasift::Links)
      obj.each do |o|
        expect(o.class).to eq(DaFace::Datasift::Link)
      end
    end

    it 'cereates empty Links' do
      expect(Proc.new{DaFace::Datasift::Links.new}).not_to raise_error
    end
  end

  describe '#get_values' do
    before do
      @hash = {
        'key_1' => [1,2],
        'key_2' => {'key_3' => [3,4]},
        'key_4' => {'key_5' => {'key_6' => [5,6]}}
      }
    end
    it 'returns specific elements of arrays inside the hash' do
      new_hash = DaFace::Datasift::Links.get_values(0, @hash.keys, @hash)

      expect(new_hash['key_1'].class).not_to eq(Array)
      expect(new_hash['key_1']).to eq(1)
      expect(new_hash['key_2'].class).to eq(Hash)
      expect(new_hash['key_2']['key_3']).to eq(3)
      expect(new_hash['key_4']['key_5']['key_6']).to eq(5)
    end
  end

  describe '#get_elements' do
    context 'for single link' do
      before do
        @data = json_fixture('links/simple.json')
      end

      it 'gets first (0) elements of embebbed arrays' do
        hashed_links = DaFace::Datasift::Links.get_elements @data

        expect(hashed_links.class).to eq(Array)
        expect(hashed_links.size).to eq(1)
      end

    end

    context 'for multiples links' do
      before do
        @data = json_fixture('links/multiples.json')
      end

      it 'gets first (0) elements of embebbed arrays' do
        hashed_links = DaFace::Datasift::Links.get_elements @data

        expect(hashed_links.class).to eq(Array)
        expect(hashed_links.size).to eq(2)
      end
    end
  end
end


text:
from abc import ABCMeta, abstractmethod
from collections import Mapping

import numpy as np

from gtd.utils import EqualityMixin

class Vocab(object):
    __metaclass__ = ABCMeta

    @abstractmethod
    def word2index(self, w):
        pass

    @abstractmethod
    def index2word(self, i):
        pass

class SimpleVocab(Vocab, EqualityMixin):
    """A simple vocabulary object."""

    def __init__(self, tokens):
        """Create a vocab.

        Args:
            tokens (list[unicode]): a unique list of unicode tokens

        If t = tokens[i], this vocab will map token t to the integer i.
        """
        if not isinstance(tokens, list):
            raise ValueError('tokens must be a list')

        # build mapping
        word2index = {}
        for i, tok in enumerate(tokens):
            word2index[tok] = i

        if len(tokens) != len(word2index):
            raise ValueError('tokens must be unique')

        self._index2word = list(tokens)  # make a copy
        self._word2index = word2index

    @property
    def tokens(self):
        """Return the full list of tokens sorted by their index."""
        return self._index2word

    def __iter__(self):
        """Iterate through the full list of tokens."""
        return iter(self._index2word)

    def __len__(self):
        """Total number of tokens indexed."""
        return len(self._index2word)

    def __contains__(self, w):
        """Check if a token has been indexed by this vocab."""
        return w in self._word2index

    def word2index(self, w):
        return self._word2index[w]

    def index2word(self, i):
        return self._index2word[i]

    def words2indices(self, words):
        return map(self.word2index, words)

    def indices2words(self, indices):
        return [self.index2word(i) for i in indices]

    def save(self, path):
        """Save SimpleVocab to file path.

        Args:
            path (str)
        """
        with open(path, 'w') as f:
            for word in self._index2word:
                f.write(word)
                f.write('\n')

    @classmethod
    def load(cls, path):
        """Load SimpleVocab from file path.

        Args:
            path (str)

        Returns:
            SimpleVocab
        """
        strip_newline = lambda s: s[:-1]
        with open(path, 'r') as f:
            tokens = [strip_newline(line) for line in f]
        return cls(tokens)

class SimpleEmbeddings(Mapping):
    def __init__(self, array, vocab):
        """Create embeddings object.

        Args:
            array (np.array): has shape (vocab_size, embed_dim)
            vocab (SimpleVocab): a Vocab object
        """
        assert len(array.shape) == 2
        assert array.shape[0] == len(vocab)  # entries line up

        self.array = array
        self.vocab = vocab

    def __contains__(self, w):
        return w in self.vocab

    def __getitem__(self, w):
        idx = self.vocab.word2index(w)
        return np.copy(self.array[idx])

    def __iter__(self):
        return iter(self.vocab)

    def __len__(self):
        return len(self.vocab)

    @property
    def embed_dim(self):
        return self.array.shape[1]


text:
// @ts-check

const fs = require("fs");
const md = require("../markdown");

/**
 * @param {string[]} input
 * @param {boolean} isSync
 */
function transformValue(input, isSync) {
  const out = [];
  const suffix = [];
  for (let line of input) {
    let match = line.match(/const { (\w+) } = require\('playwright'\);/);
    if (match) {
      if (isSync) {
        out.push('from playwright.sync_api import sync_playwright');
        out.push('');
        out.push('def run(playwright):');
        out.push(`    ${match[1]} = playwright.${match[1]}`);
        suffix.push(``);
        suffix.push(`with sync_playwright() as playwright:`);
        suffix.push(`    run(playwright)`);
      } else {
        out.push('import asyncio');
        out.push('from playwright.async_api import async_playwright');
        out.push('');
        out.push('async def run(playwright):');
        out.push(`    ${match[1]} = playwright.${match[1]}`);
        suffix.push(``);
        suffix.push(`async def main():`);
        suffix.push(`    async with async_playwright() as playwright:`);
        suffix.push(`        await run(playwright)`);
        suffix.push(`asyncio.run(main())`);
      }
      continue;
    }
    if (line.trim() === '(async () => {' || line.trim() === '})();')
      continue;
    if (!line)
      continue;
    if (line.trim() === '}')
      continue;
    line = line.replace(/\$\$eval/g, 'eval_on_selector_all');
    line = line.replace(/\$eval/g, 'eval_on_selector');
    line = line.replace(/\$\$/g, 'query_selector_all');
    line = line.replace(/\$/g, 'query_selector');
    line = line.replace(/([a-zA-Z$]+)/g, (match, p1) => toSnakeCase(p1));
    line = line.replace(/try {/, 'try:');
    line = line.replace(/async \(([^)]+)\) => {/, 'lambda $1:');
    line = line.replace(/} catch \(e\) {/, 'except Error as e:');
    line = line.replace(/;$/, '');
    line = line.replace(/  /g, '    ');
    line = line.replace(/'/g, '"');
    line = line.replace(/const /g, '');
    line = line.replace(/{\s*(\w+):\s*([^} ]+)\s*}/, "$1=$2");
    line = line.replace(/\/\/ /, "# ");
    line = line.replace(/\(\) => /, 'lambda: ');
    line = line.replace(/console.log/, 'print');
    line = line.replace(/function /, 'def ');
    line = line.replace(/{$/, '');
    if (isSync)
      line = line.replace(/await /g, "")
    out.push(line)
  }
  return [...out, ...suffix].join("\n");
}

/**
 *
 * @param {md.MarkdownNode} node
 * @param {boolean} isSync
 */
function generateComment(node, isSync) {
  const commentNode = md.clone(node)
  commentNode.codeLang = isSync ? "python sync" : "python async";
  commentNode.lines = ['# FIXME', ...transformValue(node.lines, isSync).split("\n")];
  return commentNode;
}

/**
 *
 * @param {md.MarkdownNode[]} spec
 */
function multiplyComment(spec) {
  const children = []
  for (const node of (spec || [])) {
    if (node.codeLang === "js")
      children.push(node, generateComment(node, false), generateComment(node, true));
    else
      children.push(node);
  }
  return children;
}

/**
 * @param {string} name
 */
function toSnakeCase(name) {
  const toSnakeCaseRegex = /((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))/g;
  return name.replace(toSnakeCaseRegex, `_$1`).toLowerCase();
}

for (const name of fs.readdirSync("docs/src")) {
  if (!name.endsWith(".md"))
    continue;
  const inputFile = `docs/src/${name}`;
  const fileContent = fs.readFileSync(inputFile).toString();
  const nodes = md.parse(fileContent);

  md.visitAll(nodes, node => {
    if (node.children)
      node.children = multiplyComment(node.children);
  });

  const out = md.render(nodes, 120);
  fs.writeFileSync(inputFile, out);
}


text:
#region copyright
// (C) Copyright 2015 Dinu Marius-Constantin (http://dinu.at) and others.
//
// 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.
//
// Contributors:
//     Dinu Marius-Constantin
//     Wurm Florian
#endregion
namespace UFO.Server.Dal.Common
{
    /// <summary>
    /// Defines the available DAO methods for the DAL.
    /// </summary>
    public interface IDaoProviderFactory
    {
        IArtistDao CreateArtistDao();

        IPerformanceDao CreatePerformanceDao();

        IUserDao CreateUserDao();

        IVenueDao CreateVenueDao();

        ICategoryDao CreateCategoryDao();

        ICountryDao CreateCountryDao();

        ILocationDao CreateLocationDao();
    }
}


text:
module SpreeVendors
  module_function

  # Returns the version of the currently loaded SpreeVendors as a
  # <tt>Gem::Version</tt>.
  def version
    Gem::Version.new VERSION::STRING
  end

  module VERSION
    MAJOR = 0
    MINOR = 0
    TINY  = 1
    PRE   = 'alpha'.freeze

    STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
  end
end


text:
module PipelineDeals
  # Custom error class for rescuing from all PipelineDeals errors
  class Errors < StandardError; end

  # Raised when PipelineDeals returns the HTTP status code 400
  class BadRequest < Errors; end

  # Raised when PipelineDeals returns the HTTP status code 404
  class NotFound < Errors; end

  # Raised when PipelineDeals returns the HTTP status code 500
  class InternalServerError < Errors; end

  # Raised when PipelineDeals returns the HTTP status code 503
  class ServiceUnavailable < Errors; end

  # Raised when a subscription payload hash is invalid
  class InvalidSignature < Errors; end

  # Raised when an api_key is not configured
  class MissingApiKey < Errors; end
end


text:
<?php
/**
 * Dropbox adapter that extends much of the FileSystemLocal logic
 *
 * This class defines the functionality defined by FileSystemInterface for a plain Filesystem.
 * @author Hub Figuiere <hub@figuiere.net>
 * @author Jaisen Mathai <jaisen@jmathai.com>
 */
class FileSystemLocalDropbox extends FileSystemLocal implements FileSystemInterface
{
  private $root;
  private $urlBase;
  private $dropbox;

  public function __construct()
  {
    parent::__construct();
    $fsConfig = getConfig()->get('localfs');
    $this->root = $fsConfig->fsRoot;
    $this->host = $fsConfig->fsHost;
    $this->dropbox = new FileSystemDropboxBase($this);
  }

  public function deletePhoto($photo)
  {
    return $this->dropbox->deletePhoto($photo) && parent::deletePhoto($photo);
  }

  public function downloadPhoto($photo)
  {
    return $this->dropbox->getFilePointer($photo);
  }

  /**
    * Gets diagnostic information for debugging.
    *
    * @return array
    */
  public function diagnostics()
  {
    return array_merge($this->dropbox->diagnostics(), parent::diagnostics());
  }

  /**
    * Executes an upgrade script
    *
    * @return void
    */
  public function executeScript($file, $filesystem)
  {
    if($filesystem == 'dropbox')
      echo file_get_contents($file);
    else
      parent::executeScript($file, $filesystem);
  }

  /**
   * Get photo will copy the photo to a temporary file.
   *
   */
  public function getPhoto($filename)
  {
    return parent::getPhoto($filename);
  }

  public function putPhoto($localFile, $remoteFile, $dateTaken)
  {
    $parentStatus = true;
    if(strpos($remoteFile, '/original/') === false)
      $parentStatus = parent::putPhoto($localFile, $remoteFile, $dateTaken);

    return $this->dropbox->putPhoto($localFile, $remoteFile, $dateTaken) && $parentStatus;
  }

  public function putPhotos($files)
  {
    $parentFiles = array();
    foreach($files as $file)
    {
      list($localFile, $remoteFileArr) = each($file);
      $remoteFile = $remoteFileArr[0];
      $dateTaken = $remoteFileArr[1];
      if(strpos($remoteFile, '/original/') === false)
        $parentFiles[] = $file;
    }
    return $this->dropbox->putPhotos($files) && parent::putPhotos($parentFiles);
  }

  /**
    * Get the hostname for the remote filesystem to be used in constructing public URLs.
    * @return string
    */
  public function getHost()
  {
    return $this->host;
  }

  /**
    * Return any meta data which needs to be stored in the photo record
    * @return array
    */
  public function getMetaData($localFile)
  {
    return array();
  }

  public function initialize($isEditMode)
  {
    return $this->dropbox->initialize($isEditMode) && parent::initialize($isEditMode);
  }

  /**
    * Identification method to return array of strings.
    *
    * @return array
    */
  public function identity()
  {
    return array_merge(array('dropbox'), parent::identity());
  }

  public function normalizePath($path)
  {
    return parent::normalizePath($path);
  }
}


text:
/**
 * @fileoverview Disallow attempted uses of undefined translation strings.
 */

'use strict';

const eslintPluginVueUtils = require('eslint-plugin-vue/lib/utils');

const get = require('lodash/get');
const utils = require('../utils');

const $TR_FUNCTION = '$tr';

const create = context => {
  let hasTemplate;
  let definitionNodes = [];
  let usedStringNodes = [];

  const initialize = {
    Program(node) {
      if (!utils.checkVueEslintParser(context)) {
        return;
      }
      hasTemplate = Boolean(node.templateBody);
    },
  };

  const scriptVisitor = Object.assign(
    {},
    // Check for a use within an $tr() function - a 'true use' of the string.
    {
      'CallExpression[callee.type="MemberExpression"]'(node) {
        if (node.callee.property.name == $TR_FUNCTION && node.arguments.length) {
          node.arguments.forEach(arg => {
            if (arg.type == 'Literal') {
              usedStringNodes.push(arg);
            }
          });
        }
      },
    },
    {
      ObjectExpression(node) {
        if (get(node, 'parent.key.name') === '$trs') {
          node.properties.forEach(prop => {
            definitionNodes.push({ name: prop.key.name });
          });
        }
      },
    },
    eslintPluginVueUtils.executeOnVue(context, () => {
      if (!hasTemplate) {
        utils.reportUseOfUndefinedTranslation(context, definitionNodes, usedStringNodes);
      }
    })
  );

  const templateVisitor = Object.assign(
    {},
    {
      'CallExpression[callee.type="Identifier"]'(node) {
        if (node.callee.name == $TR_FUNCTION && node.arguments.length) {
          node.arguments.forEach(arg => {
            if (arg.type == 'Literal') {
              usedStringNodes.push(arg);
            }
          });
        }
      },
    },
    utils.executeOnRootTemplateEnd(() => {
      utils.reportUseOfUndefinedTranslation(context, definitionNodes, usedStringNodes);
    })
  );

  return Object.assign(
    {},
    initialize,
    eslintPluginVueUtils.defineTemplateBodyVisitor(context, templateVisitor, scriptVisitor)
  );
};

module.exports = {
  meta: {
    docs: {
      description: 'Disallow attempted uses of undefined translation strings.',
    },
    fixable: null,
  },
  create,
};


text:
<?php

namespace Kenny\GbbmBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class KennyGbbmBundle extends Bundle
{
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>

<link rel="stylesheet" href="<?php echo base_url(); ?>assets/adminlte/plugins/datepicker/datepicker3.css" media="screen" title="no title" charset="utf-8">

<link rel="stylesheet" href="<?php echo base_url() ?>assets/adminlte/plugins/datatables/dataTables.bootstrap.css">

<link rel="stylesheet" href="<?php echo base_url() ?>assets/adminlte/plugins/select2/select2.min.css">

      Ajukan Tim
      <?php echo $nama ?>

<a href="<?php echo base_url('home') ?>"> Home

<a href="<?php echo base_url('proposal/logbook_pengajuan_proposal_lomba') ?>">Proposal

Ajukan Tim

Upload Nim Tim Anda

                            <form role="form" method="post" action="<?php echo base_url("proposal/upload_tim"); ?>" enctype="multipart/form-data">

                                                #

                                                NIM - Nama

                                                Aksi

                                        <?php $i = 1; ?>

                                            <?php echo ($i); ?>
                                                <?php $i++ ?>

                                                <select id="select2_<?php echo ($i); ?>" class="select2 form-control" name="nim[]" value=""></select>

                                      Tambah
                                    <button type="submit" class="btn btn-primary">Submit  </button>

                            </form>

';
    }
    ?>
});
</script>


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Created by ModBuddy on 9/27/2013 7:18:11 PM -->
<GameData>
	<!-- Adding a new CityState entry. -->
	<MinorCivilizations>
		<Row>
			<Type>MINOR_CIV_DUBAI</Type>
			<Description>TXT_KEY_CITYSTATE_DUBAI</Description>
			<ShortDescription>TXT_KEY_CITYSTATE_DUBAI</ShortDescription>
			<Adjective>TXT_KEY_CITYSTATE_DUBAI_ADJ</Adjective>
			<Civilopedia>TXT_KEY_CITYSTATE_DUBAI_PEDIA</Civilopedia>
			<DefaultPlayerColor>PLAYERCOLOR_MINOR_BLUE</DefaultPlayerColor>
			<ArtDefineTag>ART_DEF_CIVILIZATION_MINOR</ArtDefineTag>
			<ArtStyleType>ARTSTYLE_MIDDLE_EAST</ArtStyleType>
			<ArtStyleSuffix>_AFRI</ArtStyleSuffix>
			<ArtStylePrefix>AFRICAN</ArtStylePrefix>
			<MinorCivTrait>MINOR_TRAIT_INTELLECTUAL</MinorCivTrait>
		</Row>
	</MinorCivilizations>
	<MinorCivilization_CityNames>
		<Row>
			<MinorCivType>MINOR_CIV_DUBAI</MinorCivType>
			<CityName>TXT_KEY_CITYSTATE_DUBAI</CityName>
		</Row>
	</MinorCivilization_CityNames>
	<MinorCivilization_Flavors>
		<Row>
			<MinorCivType>MINOR_CIV_DUBAI</MinorCivType>
			<FlavorType>FLAVOR_EXPANSION</FlavorType>
			<Flavor>3</Flavor>
		</Row>
		<Row>
			<MinorCivType>MINOR_CIV_DUBAI</MinorCivType>
			<FlavorType>FLAVOR_CITY_DEFENSE</FlavorType>
			<Flavor>8</Flavor>
		</Row>
		<Row>
			<MinorCivType>MINOR_CIV_DUBAI</MinorCivType>
			<FlavorType>FLAVOR_DEFENSE</FlavorType>
			<Flavor>5</Flavor>
		</Row>
		<Row>
			<MinorCivType>MINOR_CIV_DUBAI</MinorCivType>
			<FlavorType>FLAVOR_WONDER</FlavorType>
			<Flavor>9</Flavor>
		</Row>
	</MinorCivilization_Flavors>
	<Language_en_US>

		<Row Tag="TXT_KEY_CITYSTATE_DUBAI_ADJ">
			<Text>Dubai</Text>
		</Row>
		<Row Tag="TXT_KEY_CITYSTATE_DUBAI_PEDIA">
			<Text>No entry available! Sorry.</Text>
		</Row>
	</Language_en_US>
</GameData>


text:
package com.github.ambry.clustermap;

import com.codahale.metrics.MetricRegistry;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.List;

/**
 * The ClusterMap provides a high-level interface to {@link DataNodeId}s, {@link PartitionId}s and {@link ReplicaId}s.
 */
public interface ClusterMap {

  /**
   * Gets PartitionId based on serialized bytes.
   * @param stream data input stream that contains the serialized partition bytes
   * @return deserialized PartitionId
   */
  public PartitionId getPartitionIdFromStream(DataInputStream stream) throws IOException;

  /**
   * Gets a list of partitions that are available for writes.
   */
  public List<PartitionId> getWritablePartitionIds();

  /**
   * Checks if datacenter name corresponds to some datacenter in this cluster map's hardware layout.
   *
   * @param datacenterName name of datacenter
   * @return true if datacenter with datacenterName is in the hardware layout of this cluster map.
   */
  public boolean hasDatacenter(String datacenterName);

  /**
   * Gets a specific DataNodeId by its hostname and port.
   *
   * @param hostname of the DataNodeId
   * @param port of the DataNodeId
   * @return DataNodeId for this hostname and port.
   */
  public DataNodeId getDataNodeId(String hostname, int port);

  /**
   * Gets the ReplicaIds stored on the specified DataNodeId.
   *
   * @param dataNodeId
   * @return list of ReplicaIds on the specified dataNodeId
   */
  public List<ReplicaId> getReplicaIds(DataNodeId dataNodeId);

  /**
   * Gets the DataNodeIds for all nodes in the cluster.
   *
   * @return list of all DataNodeIds
   */
  public List<DataNodeId> getDataNodeIds();

  /**
   * Gets the MetricRegistry that other users of the ClusterMap ought to use for metrics.
   *
   * @return MetricRegistry
   */
  public MetricRegistry getMetricRegistry();

  /**
   * Performs the required action for a replica related event.
   */
  public void onReplicaEvent(ReplicaId replicaId, ReplicaEventType event);
}


text:
var path = require('path');
var util = require('../build-scripts/util')

var buildPath = './_build'

util.rm('-rf', buildPath)
util.run(path.join(__dirname, 'node_modules/.bin/tsc') + ' --outDir ' + buildPath);

util.cp(path.join(__dirname, 'package.json'), buildPath);
util.cp(path.join(__dirname, 'package-lock.json'), buildPath);
util.cp(path.join(__dirname, 'module.json'), buildPath);
util.cp('-r', 'Strings', buildPath);
util.cp('-r', 'node_modules', buildPath);


text:
from tsbp.consts import operations, USER_SYSTEM
from tsbp_core.models import Process

def login_process_start(strategy, details, user=None, *args, **kwargs):
    process = Process.objects.create(operation_id=operations.SOCIAL_LOGIN, issued_by_id=USER_SYSTEM)
    return {
        'process': process
    }

def get_user_name(strategy, details, user=None, *args, **kwargs):
    pass


text:
var database = require('../lib/database')

var Task = function () {}

/**
 * Get all the tasks with their respective list names
 * @param {Function} callback
 * @api public
 */
Task.prototype.getToDo = function (callback) {
  var query =
    'SELECT lists.name as listName, tasks.name, tasks.id, tasks.important '
  query += 'FROM tasks, lists '
  query += 'WHERE tasks.done=0 AND tasks.deleted=0 AND tasks.list_id=lists.id '
  query += 'ORDER BY lists.id'
  database.all(query, function (err, rows) {
    if (err) {
      return callback(err)
    } else {
      var result = {}
      result.rows = rows
      return callback(null, result)
    }
  })
}

/**
 * Get all the done not deleted tasks with their list names
 * @param {Integer} limit the number of most recent done tasks
 * @param {Function} callback
 * @api public
 */
Task.prototype.getDone = function (limit, callback) {
  var query =
    'SELECT lists.name as listName, tasks.* FROM tasks, lists WHERE done=1 '
  query +=
    'AND tasks.deleted=0 AND tasks.list_id=lists.id ORDER BY tasks.done_date DESC'
  if (limit) {
    query += ' LIMIT ' + limit
  }
  database.all(query, function (err, rows) {
    if (err) {
      return callback(err)
    } else {
      var result = {}
      result.rows = rows
      return callback(null, result)
    }
  })
}

/**
 * Get all the deleted tasks
 * @param {Function} callback
 * @api public
 */
Task.prototype.getDeleted = function (limit, callback) {
  var query = 'SELECT * FROM tasks WHERE deleted=1'
  if (limit) {
    query += ' LIMIT ' + limit
  }
  database.all(query, function (err, rows) {
    if (err) {
      return callback(err)
    } else {
      var result = {}
      result.rows = rows
      return callback(null, result)
    }
  })
}

/**
 * Get a task and its list name with the given id
 * @param {Integer} taskId the id of the task to retrieve
 * @api public
 */
Task.prototype.get = function (taskId, callback) {
  var query = 'SELECT lists.name as listName, tasks.* FROM tasks, lists '
  query += 'WHERE tasks.id=? AND lists.id=tasks.list_id'
  database.get(query, taskId, function (err, row) {
    if (err) {
      return callback(err)
    } else {
      var result = {}
      result.row = row
      return callback(null, result)
    }
  })
}

/**
 * Adds a new task
 * @param {Object} task the new task to be added
 * @param {Function} callback
 * @api public
 */
Task.prototype.add = function (task, callback) {
  database.get('SELECT id FROM lists WHERE name=?', task.list, function (
    err,
    row
  ) {
    if (err) {
      return callback(err)
    }
    if (!row) {
      return callback('Unknown list.')
    }
    var query = 'INSERT INTO tasks (name, list_id, date) values(?, ?, ?)'
    database.run(query, [task.name, row.id, task.dueDate], function (err) {
      if (err) {
        return callback(err)
      } else {
        var result = {}
        result.lastId = this.lastID
        return callback(null, result)
      }
    })
    return true // understand why?
  })
}

/**
 * Marks a task with the given id as deleted
 * @param {Integer} taskId the id of the task to mark as deleted
 * @param {Function} callback
 * @api public
 */
Task.prototype.remove = function (taskId, callback) {
  var query = 'UPDATE tasks SET deleted=1 WHERE id=?'
  database.run(query, taskId, function (err) {
    if (err) {
      return callback(err)
    } else {
      var result = {}
      result.affected = this.changes
      return callback(null, result)
    }
  })
}

/**
 * Removes deleted status from task
 * @param {Integer} taskId the id of the task restore
 * @param {Function} callback
 * @api public
 */
Task.prototype.restore = function (taskId, callback) {
  var query = 'UPDATE tasks SET deleted=0 WHERE id=?'
  database.run(query, taskId, function (err) {
    if (err) {
      return callback(err)
    } else {
      var result = {}
      result.affected = this.changes
      return callback(null, result)
    }
  })
}

/**
 * Moves a task from its current list to another list
 * @param {Integer} taskId the id of the task to move
 * @param {String} listName the name of the list to move that task to
 * @param {Function} callback
 * @api public
 */
Task.prototype.move = function (taskId, listName, callback) {
  database.get('SELECT id FROM lists WHERE name=?', listName, function (
    err,
    row
  ) {
    if (err) {
      return callback(err)
    }
    if (!row) {
      return callback('Unknown list')
    }
    var query = 'UPDATE tasks SET list_id=? WHERE id=?'
    database.run(query, [row.id, taskId], function (err) {
      if (err) {
        return callback(err)
      } else {
        var result = {}
        result.affected = this.changes
        return callback(null, result)
      }
    })
  })
}

/**
 * Mark a task with the given id as done
 * @param {Integer} taskId the id of the task to mark as done
 * @param {Integer} doneValue 1 if task is done 0 otherwise
 * @param {Function} callback
 * @api public
 */
Task.prototype.setDone = function (taskId, doneValue, callback) {
  // convert to unix timestamp
  var doneDate = doneValue === 1 ? Math.round(Date.now() / 1000) : 0
  var query = 'UPDATE tasks SET done=?, done_date=? WHERE id=?'
  database.run(query, [doneValue, doneDate, taskId], function (err) {
    if (err) {
      return callback(err)
    } else {
      var result = {}
      result.affected = this.changes
      return callback(null, result)
    }
  })
}

/**
 * Mark a task with the given id as starred
 * @param {Integer} taskId the id of the task to mark as starred
 * @param {Integer} starValue 1 if task is starred 0 otherwise
 * @param {Function} callback
 * @api public
 */
Task.prototype.setStar = function (taskId, starValue, callback) {
  var query = 'UPDATE tasks SET important=? WHERE id=?'
  database.run(query, [starValue, taskId], function (err) {
    if (err) {
      return callback(err)
    } else {
      var result = {}
      result.affected = this.changes
      return callback(null, result)
    }
  })
}

/**
 * Sets a due date to given task
 * @param {Integer} taskId the id of the task to set a due date
 * @param {Integer} dateValue the date to set due
 * @param {Function} callback
 * @api public
 */
Task.prototype.setDue = function (taskId, dateValue, callback) {
  var query = 'UPDATE tasks SET date=? WHERE id=?'
  database.run(query, [dateValue, taskId], function (err) {
    if (err) {
      return callback(err)
    } else {
      var result = {}
      result.affected = this.changes
      return callback(null, result)
    }
  })
}

module.exports = Task


text:
using System;

namespace DragonSpark.Runtime
{
	public class DelegatedDisposable : DisposableBase
	{
		readonly Action action;
		public DelegatedDisposable( Action action )
		{
			this.action = action;
		}

		protected override void OnDispose( bool disposing )
		{
			if ( disposing )
			{
				action();
			}
		}
	}
}


text:
package pl.edu.uwb.mobiuwb.view.contact;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import pl.edu.uwb.mobiuwb.R;
import pl.edu.uwb.mobiuwb.configuration.StartupConfig;
import pl.edu.uwb.mobiuwb.parsers.xml.parser.Coordinates;

/**
 * Created by sennajavie on 2015-05-15.
 */
public class ContactActivity extends Activity
{
    private TextView unitName;
    private TextView postalCodeAndCity;
    private TextView streetAndNumber;

    private LinearLayout emailButton;
    private TextView emailTextView;

    private LinearLayout call1Button;
    private TextView call1TextView;

    private LinearLayout call2Button;
    private TextView call2TextView;

    private LinearLayout faxButton;
    private TextView faxTextView;

    private LinearLayout mapButton;
    private TextView mapTextView;

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

    @Override protected void onPostCreate(Bundle savedInstanceState)
    {
        super.onPostCreate(savedInstanceState);
        init();
    }

    private void init()
    {
        initContactFields();

        initEmailElement();

        initPhone1Element();

        initPhone2Element();

        initFaxElement();

        initMapElement();
    }

    private void initMapElement()
    {
        mapButton = (LinearLayout)findViewById(R.id.map_button);
        mapTextView = (TextView)findViewById(R.id.map_text_view);
        mapTextView.setText(getString(R.string.contact_map_element_text));
        mapButton.setOnClickListener(mapOnClickListener);
    }

    View.OnClickListener mapOnClickListener = new View.OnClickListener()
    {
        @Override public void onClick(View view)
        {
            Coordinates coords = StartupConfig.
                    configXmlResult.
                    getCurrentUniversityUnit().
                    getMobiUwBMap().
                    getCoordinates();
            Uri gmmIntentUri = Uri.parse("geo:"+coords.getLongtitude()+","+coords.getLattitude());
            Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
            mapIntent.setPackage("com.google.android.apps.maps");
            if (mapIntent.resolveActivity(getPackageManager()) != null) {
                startActivity(mapIntent);
            }
        }
    };

    private void initFaxElement()
    {
        faxButton = (LinearLayout)findViewById(R.id.fax_button);
        faxTextView = (TextView)findViewById(R.id.fax_text_view);
        faxTextView.setText(StartupConfig.configXmlResult.getCurrentUniversityUnit().getFax());
        faxButton.setOnClickListener(faxOnClickListener);
    }

    private View.OnClickListener faxOnClickListener = new View.OnClickListener()
    {
        @Override public void onClick(View view)
        {
            call(StartupConfig.configXmlResult.getCurrentUniversityUnit().getFax());
        }
    };

    private void initPhone1Element()
    {
        call1Button = (LinearLayout)findViewById(R.id.call_1_button);
        call1TextView = (TextView)findViewById(R.id.call_1_text_view);
        call1TextView.setText(StartupConfig.configXmlResult.getCurrentUniversityUnit().getTel1());
        call1Button.setOnClickListener(phone1OnClickListener);
    }

    private View.OnClickListener phone1OnClickListener = new View.OnClickListener()
    {
        @Override public void onClick(View view)
        {
            call(StartupConfig.configXmlResult.getCurrentUniversityUnit().getTel1());
        }
    };

    private void initPhone2Element()
    {
        if (StartupConfig.configXmlResult.getCurrentUniversityUnit().getTel2() != null)
        {
            call2Button = (LinearLayout) findViewById(R.id.call_2_button);
            call2TextView = (TextView) findViewById(R.id.call_2_text_view);
            call2TextView.setText(StartupConfig.configXmlResult.getCurrentUniversityUnit().getTel2());
            call2Button.setOnClickListener(phone2OnClickListener);
            call2Button.setVisibility(View.VISIBLE);
        }
    }

    private View.OnClickListener phone2OnClickListener = new View.OnClickListener()
    {
        @Override public void onClick(View view)
        {
            call(StartupConfig.configXmlResult.getCurrentUniversityUnit().getTel2());
        }
    };

    private void initEmailElement()
    {
        emailButton = (LinearLayout)findViewById(R.id.email_button);
        emailTextView = (TextView)findViewById(R.id.email_text_view);
        emailTextView.setText(StartupConfig.configXmlResult.getCurrentUniversityUnit().getEmail());

        emailButton.setOnClickListener(emailOnClickListener);
    }
    private View.OnClickListener emailOnClickListener = new View.OnClickListener()
    {
        @Override public void onClick(View view)
        {
            String[] adresses = new String[1];
            adresses[0] = StartupConfig.configXmlResult.getCurrentUniversityUnit().getEmail();
            composeEmail(adresses,"");
        }
    };

    private void initContactFields()
    {
        unitName = (TextView)findViewById(R.id.unit_name);
        String unitNameString = StartupConfig.
                configXmlResult.
                getCurrentUniversityUnit().
                getName();
        unitName.setText(unitNameString);

        postalCodeAndCity = (TextView)findViewById(R.id.postal_code_and_city);
        String unitPostalCodeString = StartupConfig.
                configXmlResult.
                getCurrentUniversityUnit().
                getAddress().
                getPostalCode();
        String unitCityString = StartupConfig.
                configXmlResult.
                getCurrentUniversityUnit().
                getAddress().
                getCity();
        postalCodeAndCity.setText(unitPostalCodeString + " " + unitCityString);

        streetAndNumber = (TextView)findViewById(R.id.street_and_number);
        String unitStreetString = StartupConfig.
                configXmlResult.
                getCurrentUniversityUnit().
                getAddress().
                getStreet();
        String unitNumberString = StartupConfig.
                configXmlResult.
                getCurrentUniversityUnit().
                getAddress().
                getNumber();
        streetAndNumber.setText(unitStreetString + " " + unitNumberString);
    }

    public void composeEmail(String[] addresses, String subject)
    {
        Intent intent = new Intent(Intent.ACTION_SENDTO);
        intent.setData(Uri.parse("mailto:")); // only email apps should handle this
        intent.putExtra(Intent.EXTRA_EMAIL, addresses);
        intent.putExtra(Intent.EXTRA_SUBJECT, subject);
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivity(intent);
        }
    }

    public void call(String phone) {
        Intent callIntent = new Intent(Intent.ACTION_DIAL);
        callIntent.setData(Uri.parse("tel:" + phone));
        startActivity(callIntent);
    }

}


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

<module xmlns="urn:jboss:module:1.1" name="com.amadeus.${project.artifactId}">
	<resources>
		<resource-root path="${project.build.finalName}-shaded.jar"/>
	</resources>
    <dependencies>
        <module name="javax.api"/>
        <module name="javax.servlet.api"/>
        <module name="sun.jdk"/>
        <module name="org.apache.log4j"/>
    </dependencies>
</module>


text:
redirect_to: https://anvio.org/help/7.1/artifacts/metagenomics-workflow
---


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('cdadmap', '0018_surveypanel_languages_other'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='meetingpanel',
            name='Occurances',
        ),
        migrations.RemoveField(
            model_name='meetingpanel',
            name='On1',
        ),
        migrations.RemoveField(
            model_name='meetingpanel',
            name='Repeat1',
        ),
        migrations.RemoveField(
            model_name='meetingpanel',
            name='RepeatEvery',
        ),
        migrations.RemoveField(
            model_name='meetingpanel',
            name='Time1',
        ),
        migrations.AddField(
            model_name='meetingpanel',
            name='all_day',
            field=models.BooleanField(default=False),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='meetingpanel',
            name='end_repeat',
            field=models.DateField(null=True, blank=True),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='meetingpanel',
            name='repeat',
            field=models.CharField(default=b'NEVER', max_length=15, choices=[(b'NEVER', b'Never'), (b'DAILY', b'Every Day'), (b'WEEKDAY', b'Every Weekday'), (b'WEEKLY', b'Every Week'), (b'BIWEEKLY', b'Every 2 Weeks'), (b'MONTHLY', b'Every Month'), (b'YEARLY', b'Every Year')]),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='meetingpanel',
            name='EndsOn',
            field=models.DateTimeField(),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='meetingpanel',
            name='StartOn',
            field=models.DateTimeField(),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='meetingpanel',
            name='hasMeeting',
            field=models.BooleanField(default=False),
            preserve_default=True,
        ),
    ]


text:
module ThreatExchange
  VERSION = "0.0.5"
end


text:
      <live-icon></live-icon>
      {{input.noun}}.js

      <live-hero></live-hero>

      <form method="get" action="">
          Enter site name
          <input type="text" value="hammer" id="sn" name="sn" placeholder="type a noun" ng-model="input.noun" ng-change="update()">.js
          <button type="submit" class="is-hidden">Generate Site</button>
        </form>

Build faster with {{input.noun}}.js!

        <lipsum></lipsum>

Be on budget with {{input.noun}}.js!

        <lipsum></lipsum>

{{input.noun}}.js will shorten meetings!

        <lipsum></lipsum>

      <lipsum></lipsum>

        <lipsum></lipsum>

      <lipsum></lipsum>

Copyright 2014 {{input.noun}}.js