text: package io.joynr.arbitration;

redpajama_set_name: RedPajamaGithub


text:
package com.heaven7.databinding.demo.bean;

import com.heaven7.adapter.ISelectable;
import com.heaven7.databinding.anno.DatabindingClass;

/**
 * Created by heaven7 on 2015/11/5.
 */
@DatabindingClass
public class User extends Person implements ISelectable {

    // moved to super
    // private String username ;
    //  private String nickname ;

    private boolean male ;       //man or woman
    private boolean select;

    public User(String username, boolean male) {
        this.username = username;
        this.male = male;
    }

    public User(String username, boolean male, String nickname) {
        this.username = username;
        this.male = male;
        this.nickname = nickname;
    }

    public boolean isMale() {
        return male;
    }

    public void setMale(boolean male) {
        this.male = male;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
//moved to super
  /*  public String getNickname(){
        return nickname;
    }
    public void setNickname(String nickname) {
        this.nickname = nickname;
    }*/

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", male=" + male +
                ", nickname='" + nickname + '\'' +
                '}';
    }

    @Override
    public void setSelected(boolean selected) {
        this.select = selected;
    }
    @Override
    public boolean isSelected() {
        return select;
    }
}


text:
package org.apache.spark.sql.execution.datasources.jdbc.connection

import java.sql.{Connection, Driver}
import java.util.Properties

import scala.collection.JavaConverters._

import org.apache.spark.internal.Logging
import org.apache.spark.sql.execution.datasources.jdbc.JDBCOptions
import org.apache.spark.sql.jdbc.JdbcConnectionProvider

private[jdbc] class BasicConnectionProvider extends JdbcConnectionProvider with Logging {
  /**
   * Additional properties for data connection (Data source property takes precedence).
   */
  def getAdditionalProperties(options: JDBCOptions): Properties = new Properties()

  override val name: String = "basic"

  override def canHandle(driver: Driver, options: Map[String, String]): Boolean = {
    val jdbcOptions = new JDBCOptions(options)
    jdbcOptions.keytab == null || jdbcOptions.principal == null
  }

  override def getConnection(driver: Driver, options: Map[String, String]): Connection = {
    val jdbcOptions = new JDBCOptions(options)
    val properties = getAdditionalProperties(jdbcOptions)
    jdbcOptions.asConnectionProperties.asScala.foreach { case(k, v) =>
      properties.put(k, v)
    }
    logDebug(s"JDBC connection initiated with URL: ${jdbcOptions.url} and properties: $properties")
    driver.connect(jdbcOptions.url, properties)
  }

  override def modifiesSecurityContext(
    driver: Driver,
    options: Map[String, String]
  ): Boolean = {
    // BasicConnectionProvider is the default unsecure connection provider, so just return false
    false
  }
}


text:
package org.apache.camel.component.hazelcast.queue;

import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.IQueue;

import org.apache.camel.Endpoint;
import org.apache.camel.Processor;
import org.apache.camel.component.hazelcast.HazelcastDefaultConsumer;
import org.apache.camel.component.hazelcast.listener.CamelItemListener;

/**
 *
 */
public class HazelcastQueueConsumer extends HazelcastDefaultConsumer {

    public HazelcastQueueConsumer(Endpoint endpoint, Processor processor, String cacheName) {
        super(endpoint, processor, cacheName);

        IQueue<Object> queue = Hazelcast.getQueue(cacheName);
        queue.addItemListener(new CamelItemListener(this, cacheName), true);
    }

}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Diderma mussooriense K. S. Thind & Manocha, 1964

### Remarks
null


text:
package org.eclipse.net4j.util.om;

import org.eclipse.net4j.internal.util.bundle.OM;
import org.eclipse.net4j.util.om.trace.ContextTracer;

import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;

import java.util.concurrent.CountDownLatch;

/**
 * A default implementation of an OSGi {@link IApplication application}.
 *
 * @author Eike Stepper
 */
public class OSGiApplication implements IApplication
{
  private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG_OM, OSGiApplication.class);

  private String applicationID;

  private IApplicationContext context;

  private CountDownLatch stopLatch;

  public OSGiApplication(String applicationID)
  {
    this.applicationID = applicationID;
  }

  public String getApplicationID()
  {
    return applicationID;
  }

  public IApplicationContext getApplicationContext()
  {
    return context;
  }

  public boolean isRunning()
  {
    return stopLatch != null;
  }

  public final Object start(IApplicationContext context) throws Exception
  {
    this.context = context;
    traceStart(applicationID);

    try
    {
      doStart();
    }
    catch (Error error)
    {
      OM.LOG.error(error);
      throw error;
    }
    catch (Exception ex)
    {
      OM.LOG.error(ex);
      throw ex;
    }

    if (context != null)
    {
      context.applicationRunning();
    }

    stopLatch = new CountDownLatch(1);
    stopLatch.await();
    stopLatch = null;
    return EXIT_OK;
  }

  public final void stop()
  {
    traceStop(applicationID);

    try
    {
      doStop();
    }
    catch (Error error)
    {
      OM.LOG.error(error);
      throw error;
    }
    catch (Exception ex)
    {
      OM.LOG.error(ex);
    }

    context = null;
    if (stopLatch != null)
    {
      stopLatch.countDown();
    }
  }

  protected void doStart() throws Exception
  {
  }

  protected void doStop() throws Exception
  {
  }

  public static void traceStart(String applicationID)
  {
    try
    {
      if (TRACER.isEnabled())
      {
        TRACER.format("Starting application {0}", applicationID); //$NON-NLS-1$
      }
    }
    catch (RuntimeException ignore)
    {
    }
  }

  public static void traceStop(String applicationID)
  {
    try
    {
      if (TRACER.isEnabled())
      {
        TRACER.format("Stopping application {0}", applicationID); //$NON-NLS-1$
      }
    }
    catch (RuntimeException ignore)
    {
    }
  }
}


text:
'use strict';

const yesno = require('../gutil').yesno;

const setcomment = {
  handle: 'util::setcomment',
  exec: function setcomment (data) {
    const comment = typeof data.comment === 'string' ? data.comment : '';

    this.client.connection.sendMessage('UserState', { comment });
  },
  commands: [{
    handle: 'comment',
    exec: function comment (data) {
      this.execute('util::setcomment', { comment: data.message });
    },
    info: () => `

USAGE: comment MESSAGE

Sets the comment with the value of MESSAGE.

`
  }]
};

const channelid = {
  handle: 'channel-id',
  exec: function channelid (data) {
    const id = data.user.channel.id;
    data.user.sendMessage(`You are in room [ ${id} ].`);
  },
  info: () => `

USAGE: channel-id

Returns the numeric ID of the
invoking user's channel.

`
};

const userdetails = {
  handle: 'user-details',
  exec: function userdetails (data) {
    const user = (
      data.message
      ? this.client.userByName(data.message)
      : data.user
    );

    if (!user)
      return void data.user.sendMessage(`User [ ${data.message} ] not found.`);

    data.user.sendMessage(`

Name          ${user.name}
ID            ${user.id || 'N/A'}
Hash          ${user.hash || 'N/A'}

In Channel    ${user.channel.name}

Can Talk?     ${yesno(user.canTalk())}
Can Hear?     ${yesno(user.canHear())}
Recording?    ${yesno(user.recording)}

`);
  },
  info: () => `

USAGE: comment MESSAGE

Sets the comment with the value of MESSAGE.

`
};

module.exports = {
  handle: 'util',
  extensions: [setcomment],
  commands: [channelid, userdetails]
};


text:
<?php

namespace yii\web;

use Yii;
use yii\base\Component;
use yii\helpers\Json;

/**
 * JsonResponseFormatter formats the given data into a JSON or JSONP response content.
 *
 * It is used by [[Response]] to format response data.
 *
 * To configure properties like [[encodeOptions]] or [[prettyPrint]], you can configure the `response`
 * application component like the following:
 *
 * ```php
 * 'response' => [
 *     // ...
 *     'formatters' => [
 *         \yii\web\Response::FORMAT_JSON => [
 *              'class' => 'yii\web\JsonResponseFormatter',
 *              'prettyPrint' => YII_DEBUG, // use "pretty" output in debug mode
 *              // ...
 *         ],
 *     ],
 * ],
 * ```
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class JsonResponseFormatter extends Component implements ResponseFormatterInterface
{
    /**
     * JSON Content Type
     * @since 2.0.14
     */
    const CONTENT_TYPE_JSONP = 'application/javascript; charset=UTF-8';
    /**
     * JSONP Content Type
     * @since 2.0.14
     */
    const CONTENT_TYPE_JSON = 'application/json; charset=UTF-8';
    /**
     * HAL JSON Content Type
     * @since 2.0.14
     */
    const CONTENT_TYPE_HAL_JSON = 'application/hal+json; charset=UTF-8';

    /**
     * @var string|null custom value of the `Content-Type` header of the response.
     * When equals `null` default content type will be used based on the `useJsonp` property.
     * @since 2.0.14
     */
    public $contentType;
    /**
     * @var bool whether to use JSONP response format. When this is true, the [[Response::data|response data]]
     * must be an array consisting of `data` and `callback` members. The latter should be a JavaScript
     * function name while the former will be passed to this function as a parameter.
     */
    public $useJsonp = false;
    /**
     * @var int the encoding options passed to [[Json::encode()]]. For more details please refer to
     * <http://www.php.net/manual/en/function.json-encode.php>.
     * Default is `JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE`.
     * This property has no effect, when [[useJsonp]] is `true`.
     * @since 2.0.7
     */
    public $encodeOptions = 320;
    /**
     * @var bool whether to format the output in a readable "pretty" format. This can be useful for debugging purpose.
     * If this is true, `JSON_PRETTY_PRINT` will be added to [[encodeOptions]].
     * Defaults to `false`.
     * This property has no effect, when [[useJsonp]] is `true`.
     * @since 2.0.7
     */
    public $prettyPrint = false;

    /**
     * Formats the specified response.
     * @param Response $response the response to be formatted.
     */
    public function format($response)
    {
        if ($this->contentType === null) {
            $this->contentType = $this->useJsonp
                ? self::CONTENT_TYPE_JSONP
                : self::CONTENT_TYPE_JSON;
        } elseif (strpos($this->contentType, 'charset') === false) {
            $this->contentType .= '; charset=UTF-8';
        }
        $response->getHeaders()->set('Content-Type', $this->contentType);

        if ($this->useJsonp) {
            $this->formatJsonp($response);
        } else {
            $this->formatJson($response);
        }
    }

    /**
     * Formats response data in JSON format.
     * @param Response $response
     */
    protected function formatJson($response)
    {
        if ($response->data !== null) {
            $options = $this->encodeOptions;
            if ($this->prettyPrint) {
                $options |= JSON_PRETTY_PRINT;
            }
            $response->content = Json::encode($response->data, $options);
        } else {
            $response->content = 'null';
        }
    }

    /**
     * Formats response data in JSONP format.
     * @param Response $response
     */
    protected function formatJsonp($response)
    {
        if (is_array($response->data)
            && isset($response->data['data'], $response->data['callback'])
        ) {
            $response->content = sprintf(
                '%s(%s);',
                $response->data['callback'],
                Json::htmlEncode($response->data['data'])
            );
        } elseif ($response->data !== null) {
            $response->content = '';
            Yii::warning(
                "The 'jsonp' response requires that the data be an array consisting of both 'data' and 'callback' elements.",
                __METHOD__
            );
        }
    }
}


text:
from __future__ import print_function, division, absolute_import

from .reference_coding_sequence_key import ReferenceCodingSequenceKey
from .logging import get_logger

logger = get_logger(__name__)

##########################
#
# ReferenceContext
# ----------------
#
# Includes all the fields of ReferenceCodingSequenceKey in addition to which
# variant we're examining and all transcripts overlapping that variant
# which produced this particular sequence context and reading frame.
#
##########################

class ReferenceContext(ReferenceCodingSequenceKey):
    """
    Representation of the sequence preceding a variant and its associated
    reading frame.
    """

    # additional fields on top of slots for ReferenceCodingSequenceKey
    __slots__ = ["variant", "transcripts"]

    def __init__(
            self,
            strand,
            sequence_before_variant_locus,
            sequence_at_variant_locus,
            sequence_after_variant_locus,
            offset_to_first_complete_codon,
            contains_start_codon,
            overlaps_start_codon,
            contains_five_prime_utr,
            amino_acids_before_variant,
            variant,
            transcripts):
        ReferenceCodingSequenceKey.__init__(
            self,
            strand=strand,
            sequence_before_variant_locus=sequence_before_variant_locus,
            sequence_at_variant_locus=sequence_at_variant_locus,
            sequence_after_variant_locus=sequence_after_variant_locus,
            offset_to_first_complete_codon=offset_to_first_complete_codon,
            contains_start_codon=contains_start_codon,
            overlaps_start_codon=overlaps_start_codon,
            contains_five_prime_utr=contains_five_prime_utr,
            amino_acids_before_variant=amino_acids_before_variant)
        self.variant = variant
        self.transcripts = tuple(transcripts)

    @classmethod
    def from_reference_coding_sequence_key(cls, key, variant, transcripts):
        """
        Construct a ReferenceContext object from a ReferenceSequenceKey, variant,
        and a set of transcript.

        Parameters
        ----------
        key : ReferenceSequenceKey
        variant : varcode.Variant
        transcripts : list of pyensembl.Transcript

        Returns ReferenceContext
        """
        return ReferenceContext(
            strand=key.strand,
            sequence_before_variant_locus=key.sequence_before_variant_locus,
            sequence_at_variant_locus=key.sequence_at_variant_locus,
            sequence_after_variant_locus=key.sequence_after_variant_locus,
            offset_to_first_complete_codon=key.offset_to_first_complete_codon,
            contains_start_codon=key.contains_start_codon,
            overlaps_start_codon=key.overlaps_start_codon,
            contains_five_prime_utr=key.contains_five_prime_utr,
            amino_acids_before_variant=key.amino_acids_before_variant,
            variant=variant,
            transcripts=transcripts)

    def sort_key_decreasing_max_length_transcript_cds(self):
        """
        Used to sort a sequence of ReferenceContext objects by the longest CDS
        in each context's list of transcripts.
        """
        return -max(len(t.coding_sequence) for t in self.transcripts)

    @property
    def mitochondrial(self):
        """
        Is this a reference context for a variant in the mitochondrial
        genome?
        """
        return self.variant.contig.lower() in {"chrm", "m", "chrmt", "mt"}


text:
<title>Member List - OGRE Documentation</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link type="text/css" rel="stylesheet" href="doxygen.css">
<link type="text/css" rel="stylesheet" href="tabs.css">

Main Page

Related Pages

Modules

Namespaces

Classes

Files

Directories

Class List

Class Index

Class Hierarchy

Class Members

OgreView Member List

This is the complete list of members for OgreView, including all inherited members.

- 	initWithFrame:	OgreView

- 	initWithFrame:	OgreView

- 	initWithGLiPhoneWindow:	OgreView

- 	initWithGLOSXWindow:	OgreView

- 	ogreWindow	OgreView

- 	ogreWindow	OgreView

- 	setFrameSize:	OgreView

- 	setFrameSize:	OgreView

- 	setOgreWindow:	OgreView

- 	setOgreWindow:	OgreView

	window	OgreView	 [protected]

Copyright © 2012 Torus Knot Software Ltd

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

Last modified Sun Sep 2 2012 07:27:25


text:
package com.replica.replicaisland;

import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;

import android.content.Context;
import android.content.res.XmlResourceParser;
import android.text.TextUtils;

public final class ConversationUtils {
	private static final int MAX_CHARACTERS_PER_PAGE = 250;

	public static class ConversationPage {
        public int imageResource;
        public CharSequence text;
        public String title;
    }

	public static class Conversation {
		public ArrayList<ConversationPage> pages = new ArrayList<ConversationPage>();
		public boolean splittingComplete;
	}

	public final static ArrayList<Conversation> loadDialog(int resource, Context context) {
        XmlResourceParser parser = context.getResources().getXml(resource);

        ArrayList<Conversation> dialog = null;
        Conversation currentConversation = null;

        try {
            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                if (eventType == XmlPullParser.START_TAG) {
                	if (parser.getName().equals("conversation")) {
                		if (dialog == null) {
                			dialog = new ArrayList<Conversation>();
                		}
                		currentConversation = new Conversation();
                		currentConversation.splittingComplete = false;
                		dialog.add(currentConversation);
                	} else if (parser.getName().equals("page")) {
                        ConversationPage page = new ConversationPage();
                        for (int i=0; i < parser.getAttributeCount(); i++) {
                                final int value = parser.getAttributeResourceValue(i, -1);
                                if (value != -1) {
                                    if (parser.getAttributeName(i).equals("image")) {
                                        page.imageResource = value;
                                    }
                                    if (parser.getAttributeName(i).equals("text")) {
                                        page.text = context.getText(value);
                                    }
                                    if (parser.getAttributeName(i).equals("title")) {
                                        page.title = context.getString(value);
                                    }
                                }
                        }
                        currentConversation.pages.add(page);
                    }
                }
                eventType = parser.next();
            }
        } catch(Exception e) {
                DebugLog.e("LoadDialog", e.getStackTrace().toString());
        } finally {
            parser.close();
        }

        return dialog;
    }

}


text:
package com.senla.bolkunets.autoservice.utils.realtions;

public interface Relation {

}


text:
<?php
namespace Bpost;

use Bpost\BpostApiClient\Bpost\Order\Box\Option\Signature;

class SignatureTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Create a generic DOM Document
     *
     * @return \DOMDocument
     */
    private static function createDomDocument()
    {
        $document = new \DOMDocument('1.0', 'utf-8');
        $document->preserveWhiteSpace = false;
        $document->formatOutput = true;

        return $document;
    }

    /**
     * Tests Signature->toXML
     */
    public function testToXML()
    {
        $expectedDocument = self::createDomDocument();
        $expectedDocument->appendChild(
            $expectedDocument->createElement('signed')
        );

        $actualDocument = self::createDomDocument();
        $signature = new Signature();
        $actualDocument->appendChild(
            $signature->toXML($actualDocument)
        );

        $this->assertEquals($expectedDocument, $actualDocument);

        $expectedDocument = self::createDomDocument();
        $expectedDocument->appendChild(
            $expectedDocument->createElement('foo:signed')
        );

        $actualDocument = self::createDomDocument();
        $signature = new Signature();
        $actualDocument->appendChild(
            $signature->toXML($actualDocument, 'foo')
        );

        $this->assertSame($expectedDocument->saveXML(), $actualDocument->saveXML());
    }
}


text:
/* */
"format global";
ko.nativeTemplateEngine = function () {
    this['allowTemplateRewriting'] = false;
}

ko.nativeTemplateEngine.prototype = new ko.templateEngine();
ko.nativeTemplateEngine.prototype.constructor = ko.nativeTemplateEngine;
ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options, templateDocument) {
    var useNodesIfAvailable = !(ko.utils.ieVersion < 9), // IE<9 cloneNode doesn't work properly
        templateNodesFunc = useNodesIfAvailable ? templateSource['nodes'] : null,
        templateNodes = templateNodesFunc ? templateSource['nodes']() : null;

    if (templateNodes) {
        return ko.utils.makeArray(templateNodes.cloneNode(true).childNodes);
    } else {
        var templateText = templateSource['text']();
        return ko.utils.parseHtmlFragment(templateText, templateDocument);
    }
};

ko.nativeTemplateEngine.instance = new ko.nativeTemplateEngine();
ko.setTemplateEngine(ko.nativeTemplateEngine.instance);

ko.exportSymbol('nativeTemplateEngine', ko.nativeTemplateEngine);


text:
/**
 * @file OldTemplateAStar.h
 * @package hog2
 * @brief A templated version of the original HOG's genericAstar.h
 * @author Nathan Sturtevant
 * @author Modified by Renee Jansen to work with templates for HOG2's
 * SearchEnvironment
 * @date 3/22/06, modified 06/13/2007
 *
 * This file is part of HOG2.
 * HOG : http://www.cs.ualberta.ca/~nathanst/hog.html
 * HOG2: http://code.google.com/p/hog2/
 *
 * HOG2 is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * HOG2 is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with HOG2; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#ifndef OldTemplateAStar_H
#define OldTemplateAStar_H

#define __STDC_CONSTANT_MACROS
#include <stdint.h>
// this is defined in stdint.h, but it doesn't always get defined correctly
// even when __STDC_CONSTANT_MACROS is defined before including stdint.h
// because stdint might be included elsewhere first...
#ifndef UINT32_MAX
#define UINT32_MAX        4294967295U
#endif

#include "FPUtil.h"
#include <ext/hash_map>
#include "OpenClosedList.h"
//#include "SearchEnvironment.h" // for the SearchEnvironment class
#include "float.h"

#include <algorithm> // for vector reverse

#include "GenericSearchAlgorithm.h"

//int discardcount;
namespace OldOldTemplateAStarUtil
{
	/**
	 * A search node class to use with hash maps
	 */
	template <class state>
	class SearchNode {
	public:
		SearchNode(state &curr, state &prev, double _fCost, double _gCost, uint64_t key)
		:fCost(_fCost), gCost(_gCost), currNode(curr), prevNode(prev), hashKey(key){}

		SearchNode(state &curr, uint64_t key)
		:fCost(0), gCost(0), currNode(curr), prevNode(curr), hashKey(key) {}

		// This probably needs to be fixed. Problem is you can't set the states to
		// 0 - so how to initialize?
		SearchNode()
		:fCost(0), gCost(0), hashKey(0) {}

		double fCost;
		double gCost;
		state currNode;
		state prevNode;
		uint64_t hashKey;
	};

	template <class state>
	struct SearchNodeEqual {
		bool operator()(const SearchNode<state> &i1, const SearchNode<state> &i2) const
	{ return (i1.currNode == i2.currNode); } };

	template <class state>
	struct SearchNodeCompare {
		bool operator()(const SearchNode<state> &i1, const SearchNode<state> &i2) const
		{
			if (fequal(i1.fCost, i2.fCost))
			{
				return (fless(i1.gCost, i2.gCost));
			}
			return (fgreater(i1.fCost, i2.fCost));
		} };

	template <class state>
	struct SearchNodeHash {
		size_t operator()(const SearchNode<state> &x) const
		{ return (size_t)(x.hashKey); }
	};
}

/**
 * A templated version of A*, based on HOG genericAStar
 */
template <class state, class action, class environment>
class OldTemplateAStar : public GenericSearchAlgorithm<state,action,environment> {
public:
	OldTemplateAStar() { env = 0; useBPMX = false; radius = 4.0; stopAfterGoal = true; weight=1; useRadius=false; useOccupancyInfo=false; radEnv = 0;}
	virtual ~OldTemplateAStar() {}
	void GetPath(environment *env, state& from, state& to, std::vector<state> &thePath);

	void GetPath(environment *, state& , state& , std::vector<action> & ) { assert(false); };

	typedef OpenClosedList<OldOldTemplateAStarUtil::SearchNode<state>, OldOldTemplateAStarUtil::SearchNodeHash<state>,
		OldOldTemplateAStarUtil::SearchNodeEqual<state>, OldOldTemplateAStarUtil::SearchNodeCompare<state> > PQueue;

	typedef __gnu_cxx::hash_map<uint64_t, OldOldTemplateAStarUtil::SearchNode<state>, Hash64 > NodeLookupTable;

	PQueue openQueue;
	NodeLookupTable closedList; //openList
	state goal, start;

	typedef typename NodeLookupTable::const_iterator closedList_iterator;

	bool InitializeSearch(environment *env, state& from, state& to, std::vector<state> &thePath);
	bool DoSingleSearchStep(std::vector<state> &thePath);
	void AddAdditionalStartState(state& newState);

	state CheckNextNode();
	void ExtractPathToStart(state& n, std::vector<state> &thePath);
	void DoAbstractSearch(){useOccupancyInfo = false; useRadius = false;}
	virtual const char *GetName();

	void PrintStats();
	//long GetNodesExpanded() { return nodesExpanded; }
	//long GetNodesTouched() { return nodesTouched; }
	void ResetNodeCount() { nodesExpanded = nodesTouched = 0; }
	int GetMemoryUsage();

	//closedList_iterator GetClosedListIter() const;
	void GetClosedListIter(closedList_iterator);
	bool ClosedListIterNext(closedList_iterator& it, state& next) const;
	bool GetClosedListGCost(state &val, double &gCost) const;

	void SetUseBPMX(bool use) { useBPMX = use; }
	bool GetUsingBPMX() { return useBPMX; }

	//state ClosedListIterNext(closedList_iterator&) const;
	uint64_t GetNodesExpanded() { return nodesExpanded; }
	uint64_t GetNodesTouched() { return nodesTouched; }

	void LogFinalStats(StatCollection *) {}

	void SetRadius(double rad) {radius = rad;}
	double GetRadius() { return radius; }

	void SetRadiusEnvironment(environment *e) {radEnv = e;}

	void SetStopAfterGoal(bool val) { stopAfterGoal = val; }
	bool GetStopAfterGoal() { return stopAfterGoal; }

	void OpenGLDraw() const;

	/** Use weighted A* and set the weight
	 *
	 * Use f = g + weight * h during search
	 *
	 * @author Renee Jansen
	 * @date 10/23/2007
	 */
	void SetWeight (double w){weight = w;}
private:
	uint64_t nodesTouched, nodesExpanded;
	bool GetNextNode(state &next);
	//state Node();
	void UpdateClosedNode(environment *env, state& currOpenNode, state& neighbor);
	void UpdateWeight(environment *env, state& currOpenNode, state& neighbor);
	void AddToOpenList(environment *env, state& currOpenNode, state& neighbor);

	std::vector<state> neighbors;
	environment *env;
	bool stopAfterGoal;

	double radius; // how far around do we consider other agents?
	double weight;

	bool useOccupancyInfo;// = false;
	bool useRadius;// = false;
	bool firstRound;
	bool useBPMX;
	environment *radEnv;
};

using namespace OldOldTemplateAStarUtil;
static const bool verbose = false;
/**
 * Return the name of the algorithm.
 * @author Nathan Sturtevant
 * @date 03/22/06
 *
 * @return The name of the algorithm
 */

template <class state, class action, class environment>
const char *OldTemplateAStar<state,action,environment>::GetName()
{
	static char name[32];
	sprintf(name, "OldTemplateAStar[]");
	return name;
}

/**
 * Perform an A* search between two states.
 * @author Nathan Sturtevant
 * @date 03/22/06
 *
 * @param _env The search environment
 * @param from The start state
 * @param to The goal state
 * @param thePath A vector of states which will contain an optimal path
 * between from and to when the function returns, if one exists.
 */
template <class state, class action, class environment>
void OldTemplateAStar<state,action,environment>::GetPath(environment *_env, state& from, state& to, std::vector<state> &thePath)
{
	//discardcount=0;
  	if (!InitializeSearch(_env, from, to, thePath))
  	{
  		return;
  	}
  	while (!DoSingleSearchStep(thePath)) {}
}

/**
 * Initialize the A* search
 * @author Nathan Sturtevant
 * @date 03/22/06
 *
 * @param _env The search environment
 * @param from The start state
 * @param to The goal state
 * @return TRUE if initialization was successful, FALSE otherwise
 */
template <class state, class action, class environment>
bool OldTemplateAStar<state,action,environment>::InitializeSearch(environment *_env, state& from, state& to, std::vector<state> &thePath)
{
	thePath.resize(0);
	//if (useRadius)
	//std::cout<<"Using radius\n";
	firstRound = true;
	env = _env;
	if (!radEnv)
		radEnv = _env;
	closedList.clear();
	openQueue.reset();
	assert(openQueue.size() == 0);
	assert(closedList.size() == 0);
	nodesTouched = nodesExpanded = 0;
	start = from;
	goal = to;

	if ((from == to) && (stopAfterGoal)) //assumes that from and to are valid states
	{
		return false;
	}

	//SearchNode<state> first(env->heuristic(goal, start), 0, start, start);
	SearchNode<state> first(start, start, weight*env->HCost(start, goal), 0, env->GetStateHash(start));
	openQueue.Add(first);

	return true;
}

/**
 * Add additional start state to the search. This should only be called after Initialize Search and before DoSingleSearchStep.
 * @author Nathan Sturtevant
 * @date 01/06/08
 */
template <class state, class action, class environment>
void OldTemplateAStar<state,action,environment>::AddAdditionalStartState(state& newState)
{
	SearchNode<state> first(newState, newState, weight*env->HCost(goal, newState), 0,env->GetStateHash(newState));
	openQueue.Add(first);
}

/**
 * Expand a single node.
 * @author Nathan Sturtevant
 * @date 03/22/06
 *
 * @param thePath will contain an optimal path from start to goal if the
 * function returns TRUE
 * @return TRUE if there is no path or if we have found the goal, FALSE
 * otherwise
 */
template <class state, class action, class environment>
bool OldTemplateAStar<state,action,environment>::DoSingleSearchStep(std::vector<state> &thePath)
{
	state currentOpenNode;

	if (openQueue.size() == 0)
	{
		thePath.resize(0); // no path found!
		//closedList.clear();
		return true;
	}

	// get top of queue
	if (!GetNextNode(currentOpenNode))
	{
		printf("Oh no! No more open nodes!\n");
	}
	//env->OutputXY(currentOpenNode);
	//std::cout<<std::endl;
	if ((stopAfterGoal) && (env->GoalTest(currentOpenNode, goal)))
	{
		ExtractPathToStart(currentOpenNode, thePath);
		// Path is backwards - reverse
		reverse(thePath.begin(), thePath.end());
		//		closedList.clear();
		//		openQueue.reset();
		//		env = 0;
		return true;
	}

 	neighbors.resize(0);
 	env->GetSuccessors(currentOpenNode, neighbors);

	if (useBPMX) // propagate best child to parent
	{
		SearchNode<state> currNode = closedList[env->GetStateHash(currentOpenNode)];
		double oldf = currNode.fCost;
		for (unsigned int x = 0; x < neighbors.size(); x++)
		{
			double newh = env->HCost(neighbors[x], goal)-env->GCost(currentOpenNode, neighbors[x]);
			if (fgreater(newh, currNode.fCost-currNode.gCost))
				currNode.fCost = currNode.gCost + newh;
		}
		//		std::cout << "Updating parent (" << currNode.currNode << ") f-cost from " << oldf << " to " << currNode.fCost << std::endl;
		closedList[env->GetStateHash(currentOpenNode)].fCost = currNode.fCost;
	}
	//printf("Expanding %d\n", currentOpenNode);

	// iterate over all the children
	for (unsigned int x = 0; x < neighbors.size(); x++)
	{
		nodesTouched++;
		state neighbor = neighbors[x];

		if (closedList.find(env->GetStateHash(neighbor)) != closedList.end())
		{
			//UpdateClosedNode(env, currentOpenNode, neighbor);
		}
		else if (openQueue.IsIn(SearchNode<state>(neighbor, env->GetStateHash(neighbor))))
		{
			UpdateWeight(env, currentOpenNode, neighbor);
		}
		else if (useRadius && useOccupancyInfo && env->GetOccupancyInfo() && radEnv && (radEnv->HCost(start, neighbor) < radius) &&(env->GetOccupancyInfo()->GetStateOccupied(neighbor)) && ((!(radEnv->GoalTest(neighbor, goal)))))// || (currentOpenNode == start )) )
		{
			SearchNode<state> sn(neighbor, env->GetStateHash(neighbor));
			closedList[env->GetStateHash(neighbor)] = sn;
		}
		else {
			AddToOpenList(env, currentOpenNode, neighbor);
		}

		firstRound = false;
	}

	if ((openQueue.size() == 0) && (stopAfterGoal == false))
	{
		ExtractPathToStart(currentOpenNode, thePath);
		// Path is backwards - reverse
		reverse(thePath.begin(), thePath.end());
		return true;
	}

	//	std::cout<<std::endl;
	return false;
}

/**
 * Returns the next state on the open list (but doesn't pop it off the queue).
 * @author Nathan Sturtevant
 * @date 03/22/06
 *
 * @return The first state in the open list.
 */
template <class state, class action, class environment>
state OldTemplateAStar<state, action,environment>::CheckNextNode()
{
	return openQueue.top().currNode;
}

/**
 * Removes the top node from the open list
 * @author Nathan Sturtevant
 * @date 03/22/06
 *
 * @param state will contain the next state in the open list
 * @return TRUE if next contains a valid state, FALSE if there is no  more states in the
 * open queue
 */
template <class state, class action, class environment>
bool OldTemplateAStar<state,action,environment>::GetNextNode(state &next)
{
	nodesExpanded++;
	if (openQueue.Empty())
		return false;
	SearchNode<state> it = openQueue.Remove();
	//if (it == openQueue.end())
	//	return false;
	next = it.currNode;
	//printf("h-cost\t%f\n", it.fCost-it.gCost);

	//	std::cout << "Current open node " << next << " f-cost: " << it.fCost << " g-cost: " << it.gCost <<
	//	" h-value: " << env->HCost(next, goal) << "/" << it.fCost-it.gCost << std::endl;

	closedList[env->GetStateHash(next)] = it;
	//	std::cout<<"Getting "<<it.gCost<<" ";
	return true;
}

/**
 * Check and update the weight of a closed node.
 * @author Nathan Sturtevant
 * @date 11/10/08
 *
 * @param currOpenNode The node that's currently being expanded
 * @param neighbor The node whose weight will be updated
 */
template <class state, class action, class environment>
void OldTemplateAStar<state,action,environment>::UpdateClosedNode(environment *e, state &currOpenNode, state &neighbor)
{
	//printf("Found in closed list!\n");
	SearchNode<state> prev = closedList[e->GetStateHash(neighbor)];
	//openQueue.find(SearchNode<state>(neighbor, e->GetStateHash(neighbor)));
	SearchNode<state> alt = closedList[e->GetStateHash(currOpenNode)];
	double edgeWeight = e->GCost(currOpenNode, neighbor);
	double altCost = alt.gCost+edgeWeight+(prev.fCost-prev.gCost);
	if (fgreater(prev.fCost, altCost))
	{
		//std::cout << "Reopening node " << neighbor << " setting parent to " << currOpenNode << std::endl;
		//printf("Reopening node %d setting parent to %d - %f vs. %f\n", neighbor, currOpenNode, prev.fCost, altCost);
		prev.fCost = altCost;
		prev.gCost = alt.gCost+edgeWeight;
	 	prev.prevNode = currOpenNode;
		// this is generally unneeded. But, in a search space where two
		// nodes may be "equal" but not identical, it is important.
		prev.currNode = neighbor;
		closedList.erase(e->GetStateHash(neighbor));
		assert(closedList.find(e->GetStateHash(neighbor)) == closedList.end());
		openQueue.Add(prev);
	}
}

/**
 * Update the weight of a node.
 * @author Nathan Sturtevant
 * @date 03/22/06
 *
 * @param currOpenNode The node that's currently being expanded
 * @param neighbor The node whose weight will be updated
 */
template <class state, class action, class environment>
void OldTemplateAStar<state,action,environment>::UpdateWeight(environment *e, state &currOpenNode, state &neighbor)
{
	//printf("Found in open list!\n");
	SearchNode<state> prev = openQueue.find(SearchNode<state>(neighbor, e->GetStateHash(neighbor)));
	SearchNode<state> alt = closedList[e->GetStateHash(currOpenNode)];
	double edgeWeight = e->GCost(currOpenNode, neighbor);
	double altCost = alt.gCost+edgeWeight+(prev.fCost-prev.gCost);
	if (fgreater(prev.fCost, altCost))
	{
		//		std::cout << "Updating node " << neighbor << " setting parent to " << currOpenNode << std::endl;
		//printf("Resetting node %d setting parent to %d\n", neighbor, currOpenNode);
		prev.fCost = altCost;
		prev.gCost = alt.gCost+edgeWeight;
		prev.prevNode = currOpenNode;
		// this is generally unneeded. But, in a search space where two
		// nodes may be "equal" but not identical, it is important.
		prev.currNode = neighbor;
		openQueue.DecreaseKey(prev);
	}
}

/**
 * Add a node to the open list
 * @author Nathan Sturtevant
 * @date 03/22/06
 *
 * @param currOpenNode the state that's currently being expanded
 * @param neighbor the state to be added to the open list
 */
template <class state, class action,class environment>
void OldTemplateAStar<state, action,environment>::AddToOpenList(environment *e, state &currOpenNode, state &neighbor)
{
	//printf("Adding node %d setting parent to %d\n", neighbor, currOpenNode);
	//	std::cout << "Adding node " << neighbor << " setting parent to " << currOpenNode << std::endl;
	double edgeWeight = e->GCost(currOpenNode, neighbor);

	double oldfCost = closedList[e->GetStateHash(currOpenNode)].fCost;
	double oldgCost = closedList[e->GetStateHash(currOpenNode)].gCost;
	double gCost = oldgCost+edgeWeight;
	double fCost = gCost+weight*e->HCost(neighbor, goal);
	if (/*(useBPMX) && */(fgreater(oldfCost, fCost))) // pathmax rule
	{
		//		std::cout << "Adding node: (" << neighbor << ") f-cost from " << fCost << " to " << oldfCost
		//		<< " h-cost: " << fCost-gCost << " g-cost: " << gCost << " hash: " << e->GetStateHash(neighbor) << std::endl;
		fCost = oldfCost;
	}
	else {
		//		std::cout << "Adding node: (" << neighbor << ") f-cost " << fCost
		//		<< " h-cost: " << fCost-gCost << " g-cost: " << gCost << " hash: " << e->GetStateHash(neighbor) << std::endl;
	}
	SearchNode<state> n(neighbor, currOpenNode, fCost, gCost, e->GetStateHash(neighbor));

	openQueue.Add(n);
}

/**
 * Get the path from a goal state to the start state
 * @author Nathan Sturtevant
 * @date 03/22/06
 *
 * @param goalNode the goal state
 * @param thePath will contain the path from goalNode to the start state
 */
template <class state, class action,class environment>
void OldTemplateAStar<state, action,environment>::ExtractPathToStart(state &goalNode,
																  std::vector<state> &thePath)
{
	SearchNode<state> n;
	if (closedList.find(env->GetStateHash(goalNode)) != closedList.end())
	{
		n = closedList[env->GetStateHash(goalNode)];
	}
	else n = openQueue.find(SearchNode<state>(goalNode, env->GetStateHash(goalNode)));

	do {
		//std::cout << "Extracting " << n.currNode << " with parent " << n.prevNode << std::endl;
		//printf("Extracting %d with parent %d\n", n.currNode, n.prevNode);
		thePath.push_back(n.currNode);
		if (closedList.find(env->GetStateHash(n.prevNode)) != closedList.end())
		{
			n = closedList[env->GetStateHash(n.prevNode)];
		}
		else {
			printf("No backward path found!\n");
			break;
		}
	} while (!(n.currNode == n.prevNode));
	thePath.push_back(n.currNode);
}

/**
 * A function that prints the number of states in the closed list and open
 * queue.
 * @author Nathan Sturtevant
 * @date 03/22/06
 */
template <class state, class action, class environment>
void OldTemplateAStar<state, action,environment>::PrintStats()
{
	printf("%u items in closed list\n", (unsigned int)closedList.size());
	printf("%u items in open queue\n", (unsigned int)openQueue.size());
}

/**
 * Return the amount of memory used by OldTemplateAStar
 * @author Nathan Sturtevant
 * @date 03/22/06
 *
 * @return The combined number of elements in the closed list and open queue
 */
template <class state, class action, class environment>
int OldTemplateAStar<state, action,environment>::GetMemoryUsage()
{
	return closedList.size()+openQueue.size();
}

/**
 * Get an iterator for the closed list
 * @author Nathan Sturtevant
 * @date 06/13/07
 *
 * @return An iterator pointing to the first node in the closed list
 */
template <class state, class action,class environment>
//__gnu_cxx::hash_map<state, OldOldTemplateAStarUtil::SearchNode<state> >::const_iterator
void OldTemplateAStar<state, action,environment>::GetClosedListIter(closedList_iterator) //const
{
	return closedList.begin();
}

/**
 * Get the next state in the closed list
 * @author Nathan Sturtevant
 * @date 06/13/07
 *
 * @param it A closedList_iterator pointing at the current state in the closed
 * list
 * @return The next state in the closed list. Returns UINT_MAX if there's no
 * more states
 */
template <class state, class action, class environment>
bool OldTemplateAStar<state, action,environment>::ClosedListIterNext(closedList_iterator& it, state& next) const
{
	if (it == closedList.end())
		return false;
	next = (*it).first;
	it++;
	return true;
}

/**
 * Get state from the closed list
 * @author Nathan Sturtevant
 * @date 10/09/07
 *
 * @param val The state to lookup in the closed list
 * @gCost The g-cost of the node in the closed list
 * @return success Whether we found the value or not
 * more states
 */
template <class state, class action, class environment>
bool OldTemplateAStar<state, action,environment>::GetClosedListGCost(state &val, double &gCost) const
{
	if (closedList.find(env->GetStateHash(val)) != closedList.end())
	{
		gCost = closedList.find(env->GetStateHash(val))->second.gCost;
		return true;
	}
	return false;
}

/**
 * Draw the open/closed list
 * @author Nathan Sturtevant
 * @date 03/12/09
 *
 */
template <class state, class action, class environment>
void OldTemplateAStar<state, action,environment>::OpenGLDraw() const
{
	int x = 0;
	if (env == 0)
		return;
	//env->SetColor(0.0, 0.0, 0.0, 0.15);
	for (closedList_iterator it = closedList.begin(); it != closedList.end(); it++)
	{
		env->OpenGLDraw((*it).second.currNode);
	}
}

#endif


text:
package file

import (
	"path/filepath"

	"github.com/openshift/source-to-image/pkg/api"
	"github.com/openshift/source-to-image/pkg/scm/git"
	"github.com/openshift/source-to-image/pkg/util/fs"
	utilglog "github.com/openshift/source-to-image/pkg/util/glog"
)

var glog = utilglog.StderrLog

// File represents a simplest possible Downloader implementation where the
// sources are just copied from local directory.
type File struct {
	fs.FileSystem
}

// Download copies sources from a local directory into the working directory.
// Caller guarantees that config.Source.IsLocal() is true.
func (f *File) Download(config *api.Config) (*git.SourceInfo, error) {
	config.WorkingSourceDir = filepath.Join(config.WorkingDir, api.Source)

	copySrc := config.Source.LocalPath()
	if len(config.ContextDir) > 0 {
		copySrc = filepath.Join(copySrc, config.ContextDir)
	}

	glog.V(1).Infof("Copying sources from %q to %q", copySrc, config.WorkingSourceDir)
	if copySrc != config.WorkingSourceDir {
		err := f.CopyContents(copySrc, config.WorkingSourceDir)
		if err != nil {
			return nil, err
		}
	}

	return &git.SourceInfo{
		Location:   config.Source.LocalPath(),
		ContextDir: config.ContextDir,
	}, nil
}


text:
package com.carlomicieli.jtrains.util;

import java.text.Normalizer;
import java.util.Locale;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * It converts a string to a "slug".
 *
 * @see Original implementation
 * @author Carlo Micieli
 */
public interface Slug {
    static final Pattern NON_LATIN = Pattern.compile("[^\\w-]");
    static final Pattern WHITESPACE = Pattern.compile("[\\s]");
    static final String SEP = "-";

    /**
     * Checks whether the provided {@code slugValue} is not empty, otherwise the method
     * will use the {@code supplier} function to produce a value.
     *
     * @param slugValue the (possible empty or {@code null} slug value
     * @param supplier the slug supplier
     * @return the slug
     */
    public static String orElseGet(String slugValue, Supplier<String> supplier) {
        if (slugValue != null && !slugValue.isEmpty()) {
            return slugValue;
        }

        try {
            return supplier.get();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * Encodes the provided String as {@code slug}.
     * @param str the String to be encoded
     * @return the slug
     */
    public static String of(String str) {
        Objects.requireNonNull(str, "Slug: input string must be not null");
        String noWhitespace = WHITESPACE.matcher(str).replaceAll(SEP);
        String normalized = Normalizer.normalize(noWhitespace, Normalizer.Form.NFD);
        return NON_LATIN.matcher(normalized)
                .replaceAll("")
                .toLowerCase(Locale.ENGLISH);
    }

    /**
     * Joins the provided values and encode them as {@code slug}.
     * @param values the values to be joined and then encoded
     * @return the slug
     */
    public static String ofValues(Object... values) {
        Objects.requireNonNull(values, "Slug: input values must be not null");
        Predicate<Object> valueIsNotNull = obj -> !Objects.isNull(obj);
        return Stream.of(values)
                .filter(valueIsNotNull)
                .map(Object::toString)
                .map(Slug::of)
                .collect(Collectors.joining(SEP));
    }
}


text:
package quasar.niflheim

import quasar.precog.common._

import java.io.{File, IOException}
import java.nio.channels.{ReadableByteChannel, WritableByteChannel}

import scalaz._
import scalaz.syntax.monad._

case class CookedBlockMetadata(blockid: Long, length: Int, segments: Array[(SegmentId, File)]) {
  override def equals(that: Any): Boolean = that match {
    case CookedBlockMetadata(`blockid`, `length`, segments2) =>
      if (segments.length != segments2.length) return false
      var i = 0
      while (i < segments.length) {
        if (segments(i) != segments2(i)) return false
        i += 1
      }
      true
    case _ =>
      false
  }
}

trait CookedBlockFormat {
  def readCookedBlock(channel: ReadableByteChannel): Validation[IOException, CookedBlockMetadata]
  def writeCookedBlock(channel: WritableByteChannel, metadata: CookedBlockMetadata): Validation[IOException, Unit]
}

object V1CookedBlockFormat extends CookedBlockFormat with Chunker {
  val verify = true

  val FileCodec = Codec.Utf8Codec.as[File](_.getPath(), new File(_))
  val CPathCodec = Codec.Utf8Codec.as[CPath](_.toString, CPath(_))
  val CTypeCodec = Codec.ArrayCodec(Codec.ByteCodec).as[CType](CTypeFlags.getFlagFor, CTypeFlags.cTypeForFlag)
  val ColumnRefCodec = Codec.CompositeCodec[CPath, CType, (CPath, CType)](CPathCodec, CTypeCodec,
    identity, { (a: CPath, b: CType) => (a, b) })

  val SegmentIdCodec = Codec.CompositeCodec[Long, (CPath, CType), SegmentId](
    Codec.LongCodec, ColumnRefCodec,
    { id: SegmentId => (id.blockid, (id.cpath, id.ctype)) },
    { case (blockid, (cpath, ctype)) => SegmentId(blockid, cpath, ctype) })

  val SegmentsCodec = Codec.ArrayCodec({
    Codec.CompositeCodec[SegmentId, File, (SegmentId, File)](SegmentIdCodec, FileCodec, identity, _ -> _)
  })

  def writeCookedBlock(channel: WritableByteChannel, metadata: CookedBlockMetadata) = {
    val maxSize = SegmentsCodec.maxSize(metadata.segments) + 12

    write(channel, maxSize) { buffer =>
      buffer.putLong(metadata.blockid)
      buffer.putInt(metadata.length)
      SegmentsCodec.writeUnsafe(metadata.segments, buffer)
    }
  }

  def readCookedBlock(channel: ReadableByteChannel): Validation[IOException, CookedBlockMetadata] = {
    read(channel) map { buffer =>
      val blockid = buffer.getLong()
      val length = buffer.getInt()
      val segments = SegmentsCodec.read(buffer)
      CookedBlockMetadata(blockid, length, segments)
    }
  }
}

case class VersionedCookedBlockFormat(formats: Map[Int, CookedBlockFormat]) extends CookedBlockFormat with Versioning {
  val magic: Short = 0xB10C.toShort
  val (version, format) = {
    val (ver, fmt) = formats.maxBy(_._1)
    (ver.toShort, fmt)
  }

  def writeCookedBlock(channel: WritableByteChannel, segments: CookedBlockMetadata) = {
    for {
      _ <- writeVersion(channel)
      _ <- format.writeCookedBlock(channel, segments)
    } yield ()
  }

  def readCookedBlock(channel: ReadableByteChannel): Validation[IOException, CookedBlockMetadata] = {
    readVersion(channel) flatMap { version =>
      formats get version map { format =>
        format.readCookedBlock(channel)
      } getOrElse {
        Failure(new IOException(
          "Invalid version found. Expected one of %s, found %d." format (formats.keys mkString ",", version)))
      }
    }
  }
}


text:
<!DOCTYPE html>

    <title>Installing Guest Additions For Osgeo8 – Ant Beck – Research Fellow (Nottingham University), Director (GeoLytics Ltd.)</title>

        <meta charset="utf-8" />
    <meta content='text/html; charset=utf-8' http-equiv='Content-Type'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0'>

    <meta name="description" content="Installing Guest additions
" />
    <meta property="og:description" content="Installing Guest additions
" />

    <meta name="author" content="Ant Beck" />

    <meta property="og:title" content="Installing Guest Additions For Osgeo8" />
    <meta property="twitter:title" content="Installing Guest Additions For Osgeo8" />

    <link rel="stylesheet" type="text/css" href="/style.css" />
    <link rel="alternate" type="application/rss+xml" title="Ant Beck - Research Fellow (Nottingham University), Director (GeoLytics Ltd.)" href="/feed.xml" />

Ant Beck

Research Fellow (Nottingham University), Director (GeoLytics Ltd.)

            Blog
            About

Installing Guest Additions For Osgeo8

Installing Guest additions

sudo apt-get update
sudo apt-get upgrade
sudo apt-get install virtualbox-guest-dkms
sudo apt-get install dkms
sudo apt-get install virtualbox-guest-x11
sudo apt-get install virtualbox-guest-utils
cd /media
ls
cd user/
ls
cd VBOXADDITIONS_4.3.10_93012/
sudo apt-get install gcc
sudo apt-get install make
sudo ./VBoxLinuxAdditions.run
sudo reboot now

Accessing a shared drive

sudo adduser user vboxsf

(in general for each user do: sudo adduser <username> vboxsf)

    Written on March 11, 2015


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Substring.Web {

    public partial class Default {

        /// <summary>
        /// formSubstringModuleConsumer control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.HtmlControls.HtmlForm formSubstringModuleConsumer;

        /// <summary>
        /// TextBox control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox TextBox;

        /// <summary>
        /// SubStringTextBox control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox SubStringTextBox;

        /// <summary>
        /// ButtonSubmit control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button ButtonSubmit;

        /// <summary>
        /// ResultLabel control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label ResultLabel;
    }
}


text:
package org.scalatest.matchers

import org.scalatest._
import org.scalatest.exceptions.TestFailedException

/*
This has a bit of redundancy with several other specs, but was the
original file I used to develop the matchers syntax, and it has a few
tests that don't exist elsewhere, so I'm keeping it alive for now.
*/
class ShouldMatcherSpec extends Spec with ShouldMatchers {

  object `The be matcher` {

    object `(for booleans)` {

      def `should do nothing when false is compared to false` {
        false should be (false)
      }

      def `should do nothing when true is compared to true` {
        true should be (true)
      }

      def `should throw an assertion error when not equal` {
        val caught = intercept[TestFailedException] {
          false should be (true)
        }
        assert(caught.getMessage === "false was not true")
      }
    }

    object `(for null)` {

      def `should do nothing when null is compared to null` {
        val o: String = null
        o should be (null)
        o should equal (null)
      }

      def `should throw an assertion error when non-null compared to null` {
        val caught = intercept[TestFailedException] {
          val o = "Helloooooo"
          o should be (null)
        }
        assert(caught.getMessage === "\"Helloooooo\" was not null")
      }

      def `should do nothing when non-null is compared to not null` {
        val o = "Helloooooo"
        o should not { be (null) }
      }

      def `should throw an assertion error when null compared to not null` {
        val caught1 = intercept[TestFailedException] {
          val o: String = null
          o should not { be (null) }
        }
        assert(caught1.getMessage === "The reference was null")
      }

      def `should work when used in a logical expression` {
        val o: String = null
        o should { be (null) and equal (null) }
        o should { equal (null) and be (null) }
      }
    }

    object `(for Nil)` {

      def `should do nothing when an empty list is compared to Nil` {
        val emptyList = List[String]()
        emptyList should be (Nil)
        emptyList should equal (Nil)
      }

      def `should throw an assertion error when a non-empty list is compared to Nil` {
        val nonEmptyList = List("Helloooooo")
        val caught1 = intercept[TestFailedException] {
          nonEmptyList should be (Nil)
        }
        assert(caught1.getMessage === "List(Helloooooo) was not equal to List()")
        val caught2 = intercept[TestFailedException] {
          nonEmptyList should equal (Nil)
        }
        assert(caught2.getMessage === "List(Helloooooo) did not equal List()")
      }

      def `should do nothing when non-null is compared to not null` {
        val nonEmptyList = List("Helloooooo")
        nonEmptyList should not { be (Nil) }
        nonEmptyList should not { equal (Nil) }
      }

      def `should throw an assertion error when null compared to not null` {
        val emptyList = List[String]()
        val caught1 = intercept[TestFailedException] {
          emptyList should not { be (Nil) }
        }
        assert(caught1.getMessage === "List() was equal to List()")

        val caught3 = intercept[TestFailedException] {
          emptyList should not { equal (Nil) }
        }
        assert(caught3.getMessage === "List() equaled List()")
      }

      def `should work when used in a logical expression` {
        val emptyList = List[Int]()
        emptyList should { be (Nil) and equal (Nil) }
        emptyList should { equal (Nil) and be (Nil) } // Nada, and nada is nada
      }
    }

    object `(for None)` {

        /* I think I should have tests for options somewhere
        val option = Some(1)
        option should equal (Some(1))
      val option = Some(1)
      option should not { equal (Some(2)) }

         */
      def `should do nothing when a None option is compared to None` {
        val option: Option[String] = None
        option should be (None)
        option should equal (None)
      }

      def `should throw an assertion error when a Some is compared to None` {
        val someString = Some("Helloooooo")
        val caught1 = intercept[TestFailedException] {
          someString should be (None)
        }
        assert(caught1.getMessage === "Some(Helloooooo) was not equal to None")
        val caught2 = intercept[TestFailedException] {
          someString should equal (None)
        }
        assert(caught2.getMessage === "Some(Helloooooo) did not equal None")
      }

      def `should do nothing when Some is compared to not None` {
        val someString = Some("Helloooooo")
        someString should not { be (None) }
        someString should not { equal (None) }
      }

      def `should throw an assertion error when None compared to not None` {
        val none = None
        val caught1 = intercept[TestFailedException] {
          none should not { be (None) }
        }
        assert(caught1.getMessage === "None was equal to None")

        val caught3 = intercept[TestFailedException] {
          none should not { equal (None) }
        }
        assert(caught3.getMessage === "None equaled None")

        val noString: Option[String] = None
        val caught5 = intercept[TestFailedException] {
          noString should not { be (None) }
        }
        assert(caught5.getMessage === "None was equal to None")

        val caught7 = intercept[TestFailedException] {
          noString should not { equal (None) }
        }
        assert(caught7.getMessage === "None equaled None")
      }

      def `should work when used in a logical expression` {
        val none = None
        none should { be (None) and equal (None) }
        none should { equal (None) and be (None) }
        val noString: Option[String] = None
        noString should { be (None) and equal (None) }
        noString should { equal (None) and be (None) }
      }
    }

    object `(for Any)` {
      def `should do nothing when equal` {
        1 should be (1)
        val option = Some(1)
        option should be (Some(1))
      }

      def `should throw an assertion error when not equal` {
        val caught = intercept[TestFailedException] {
          1 should be (2)
        }
        assert(caught.getMessage === "1 was not equal to 2")
      }

      def `should do nothing when not equal and used with should not` {
        1 should not { be (2) }
        val option = Some(1)
        option should not { be (Some(2)) }
      }

      def `should throw an assertion error when equal but used with should not` {
        val caught = intercept[TestFailedException] {
          1 should not { be (1) }
        }
        assert(caught.getMessage === "1 was equal to 1")
      }
    }
  }

  object `The have word` {

    def `should work with map and key, right after a 'should'` {
      val map = Map(1 -> "Howdy")
      map should contain key (1)
      map should contain key (1)
      map should equal { Map(1 -> "Howdy") }
      val otherMap = Map("Howdy" -> 1)
      otherMap should contain key ("Howdy")
      otherMap should equal { Map("Howdy" -> 1) }
      import scala.collection.immutable.TreeMap
      val treeMap = TreeMap(1 -> "hi", 2 -> "howdy")
      treeMap should contain key (1)
    }

    def `should work with map and key, in a logical expression` {
      val map = Map(1 -> "Howdy")
      // The compiler infer the type of the value to be Nothing if I say: map should { contain key 1 and equal (Map(1 -> "Howdy")) }
      // map should { have.key[Int, String](1) and equal (Map(1 -> "Howdy")) }
      map should { contain key (1) and equal (Map(1 -> "Howdy")) }
      val otherMap = Map("Howdy" -> 1)
      // otherMap should { have.key[String, Int]("Howdy") and equal (Map("Howdy" -> 1)) }
      otherMap should { contain key ("Howdy") and equal (Map("Howdy" -> 1)) }
    }

    def `should work with map and key, right after a 'should not'` {
      val map = Map(1 -> "Howdy")
      map should not { contain key (2) }
    }

    def `should work with map and value, right after a 'should'` {
      val map = Map(1 -> "Howdy")
      map should contain value ("Howdy")
      map should contain value ("Howdy")
      map should equal { Map(1 -> "Howdy") }
      val otherMap = Map("Howdy" -> 1)
      otherMap should contain value (1)
      otherMap should equal { Map("Howdy" -> 1) }
    }

    def `should work with map and value, in a logical expression` {
      val map = Map(1 -> "Howdy")
      map should { equal (Map(1 -> "Howdy")) and (contain value "Howdy") }
      val otherMap = Map("Howdy" -> 1)
      otherMap should { contain value (1) and equal (Map("Howdy" -> 1)) }
    }

    def `should work with map and value, right after a 'should not'` {
      val map = Map(1 -> "Howdy")
      map should not { contain value ("Doody") }
    }

    def `should work with collection and size, in an and expression.` {
      val list = List(1, 2, 3)
      list should { have size (3) and equal (List(1, 2, 3)) }
    }

    def `should work with collection and size, right after a 'should'` {

      val map = Map(1 -> "Howdy")
      map should have size (1)
      val caught1 = intercept[TestFailedException] {
        map should have size (5)
      }
      assert(caught1.getMessage.indexOf("did not have size") != -1)

      val list = List(1, 2, 3, 4, 5)
      list should have size (5)
      val caught2 = intercept[TestFailedException] {
        list should have size (6)
      }
      assert(caught2.getMessage.indexOf("did not have size") != -1)

      val set = Set(1.0, 2.0, 3.0)
      set should have size (3)
      val caught3 = intercept[TestFailedException] {
        set should have size (0)
      }
      assert(caught3.getMessage.indexOf("did not have size") != -1)

      val array = Array[String]()
      array should have size 0
      val caught4 = intercept[TestFailedException] {
        array should have size 2
      }
      assert(caught4.getMessage.indexOf("did not have size") != -1)
    }

    def `should work with collection and size, right after a 'should not'` {

      val map = Map(1 -> "Howdy")
      map should not { have size (2) }
      val caught1 = intercept[TestFailedException] {
        map should not { have size (1) }
      }
      assert(caught1.getMessage.indexOf("had size") != -1, caught1.getMessage)

      val list = List(1, 2, 3, 4, 5)
      list should not { have size (6) }
      val caught2 = intercept[TestFailedException] {
        list should not { have size (5) }
      }
      assert(caught2.getMessage.indexOf("had size") != -1)

      val set = Set(1.0, 2.0, 3.0)
      set should not { have size (0) }
      val caught3 = intercept[TestFailedException] {
        set should not { have size (3) }
      }
      assert(caught3.getMessage.indexOf("had size") != -1)

      val array = Array[String]()
      array should not { have size (2) }
      val caught4 = intercept[TestFailedException] {
        array should not { have size (0) }
      }
      assert(caught4.getMessage.indexOf("had size") != -1)
    }
  }

  object `The contain word` {

    def `should work with a set, list, array, and map right after a 'should'` {

      val set = Set(1, 2, 3)
      set should contain (2)
      val caught1 = intercept[TestFailedException] {
        set should contain (5)
      }
      assert(caught1.getMessage.indexOf("did not contain element") != -1)

      set should { contain (2) and equal (Set(1, 2, 3)) }
      val caught1b = intercept[TestFailedException] {
        set should { contain (5) and equal(Set(1, 2, 3)) }
      }
      assert(caught1b.getMessage.indexOf("did not contain element") != -1)

      val list = List("one", "two", "three")
      list should contain ("two")
      val caught2 = intercept[TestFailedException] {
        list should contain ("five")
      }
      assert(caught2.getMessage.indexOf("did not contain element") != -1)

      val array = Array("one", "two", "three")
      array should contain ("one")
      val caught3 = intercept[TestFailedException] {
        array should contain ("five")
      }
      assert(caught3.getMessage.indexOf("did not contain element") != -1)

      val map = Map(1 -> "one", 2 -> "two", 3 -> "three")
      val tuple2: Tuple2[Int, String] = 1 -> "one"
      map should contain (tuple2)
      val caught4 = intercept[TestFailedException] {
        map should contain (1 -> "won")
      }
      assert(caught4.getMessage.indexOf("did not contain element") != -1)
    }

    def `should work with a set, list, array, and map right after a 'should not'` {

      val set = Set(1, 2, 3)
      set should not { contain (5) }
      val caught1 = intercept[TestFailedException] {
        set should not { contain (2) }
      }
      assert(caught1.getMessage.indexOf("contained element") != -1)

      val list = List("one", "two", "three")
      list should not { contain ("five") }
      val caught2 = intercept[TestFailedException] {
        list should not { contain ("two") }
      }
      assert(caught2.getMessage.indexOf("contained element") != -1)

      val array = Array("one", "two", "three")
      array should not { contain ("five") }
      val caught3 = intercept[TestFailedException] {
        array should not { contain ("one") }
      }
      assert(caught3.getMessage.indexOf("contained element") != -1)

      val map = Map(1 -> "one", 2 -> "two", 3 -> "three")
      val tuple2: Tuple2[Int, String] = 1 -> "won"
      map should not { contain (tuple2) }
      val caught4 = intercept[TestFailedException] {
        map should not { contain (1 -> "one") }
      }
      assert(caught4.getMessage.indexOf("contained element") != -1)
    }
  }

  object `The be theSameInstanceAs syntax` {

    val string = "Hi"
    val obj: AnyRef = string
    val otherString = new String("Hi")

    def `should do nothing if the two objects are the same` {
      string should be theSameInstanceAs (string)
      obj should be theSameInstanceAs (string)
      string should be theSameInstanceAs (obj)
      otherString should not { be theSameInstanceAs (string) }
    }

    def `should throw TestFailedException if the two objects are not the same` {
      val caught1 = intercept[TestFailedException] {
        string should not { be theSameInstanceAs (string) }
      }
      val caught2 = intercept[TestFailedException] {
        obj should not { be theSameInstanceAs (string) }
      }
      val caught3 = intercept[TestFailedException] {
        string should not { be theSameInstanceAs (obj) }
      }
      val caught4 = intercept[TestFailedException] {
        otherString should be theSameInstanceAs (string)
      }
      assert(true) // TODO: test the failure message
    }
  }

  object `The floating point numbers when compared with equals` {
    def `should do nothing if the floating point number is exactly equal to the specified value` {
      val sevenDotOh = 7.0
      sevenDotOh should be (7.0)
      sevenDotOh should equal (7.0)
      sevenDotOh should not { be (7.0001) }

      val sixDotOh: Float = 6.0f
      sixDotOh should be (6.0)
      sixDotOh should equal (6.0)
      sixDotOh should not { be (6.0001) }
    }

    def `should throw TestFailedException if the floating point number is not exactly equal to the specified value` {
      val sevenDotOh = 7.0001
      val caught1 = intercept[TestFailedException] {
        sevenDotOh should be (7.0)
        // sevenDotOh should be (7.0 exactly)
      }
      assert(caught1.getMessage === "7.0001 was not equal to 7.0")

      val caught2 = intercept[TestFailedException] {
        sevenDotOh should equal (7.0)
      }
      assert(caught2.getMessage === "7.0001 did not equal 7.0")

      val caught3 = intercept[TestFailedException] {
        sevenDotOh should not { be (7.0001) }
      }
      assert(caught3.getMessage === "7.0001 was equal to 7.0001")

      val sixDotOh: Float = 6.0001f
      val caught4 = intercept[TestFailedException] {
        // sixDotOh should be (6.0f exactly)
        sixDotOh should be (6.0f)
      }
      assert(caught4.getMessage === "6.0001 was not equal to 6.0")

      val caught5 = intercept[TestFailedException] {
        sixDotOh should equal (6.0f)
      }
      assert(caught5.getMessage === "6.0001 did not equal 6.0")

      val caught6 = intercept[TestFailedException] {
        sixDotOh should not { be (6.0001f) }
      }
      assert(caught6.getMessage === "6.0001 was equal to 6.0001")
    }
  }

  object `The floating point 'plusOrMinus' operator` {
    def `should do nothing if the floating point number is within the specified range` {
      val sevenDotOh = 7.0
      sevenDotOh should be (7.1 plusOrMinus 0.2)
      sevenDotOh should be (6.9 plusOrMinus 0.2)
      sevenDotOh should not { be (7.5 plusOrMinus 0.2) }
      sevenDotOh should not { be (6.5 plusOrMinus 0.2) }
      val minusSevenDotOh = -7.0
      minusSevenDotOh should be (-7.1 plusOrMinus 0.2)
      minusSevenDotOh should be (-6.9 plusOrMinus 0.2)
      minusSevenDotOh should not { be (-7.5 plusOrMinus 0.2) }
      minusSevenDotOh should not { be (-6.5 plusOrMinus 0.2) }
    }

    def `should throw TestFailedException if the floating point number is not within the specified range` {
      val sevenDotOh = 7.0
      val caught1 = intercept[TestFailedException] {
        sevenDotOh should not { be (7.1 plusOrMinus 0.2) }
      }
      assert(caught1.getMessage === "7.0 was 7.1 plus or minus 0.2")

      val caught2 = intercept[TestFailedException] {
        sevenDotOh should not { be (6.9 plusOrMinus 0.2) }
      }
      assert(caught2.getMessage === "7.0 was 6.9 plus or minus 0.2")

      val caught3 = intercept[TestFailedException] {
        sevenDotOh should be (7.5 plusOrMinus 0.2)
      }
      assert(caught3.getMessage === "7.0 was not 7.5 plus or minus 0.2")

      val caught4 = intercept[TestFailedException] {
        sevenDotOh should be (6.5 plusOrMinus 0.2)
      }
      assert(caught4.getMessage === "7.0 was not 6.5 plus or minus 0.2")

      val minusSevenDotOh = -7.0
      val caught5 = intercept[TestFailedException] {
        minusSevenDotOh should not { be (-7.1 plusOrMinus 0.2) }
      }
      assert(caught5.getMessage === "-7.0 was -7.1 plus or minus 0.2")

      val caught6 = intercept[TestFailedException] {
        minusSevenDotOh should not { be (-6.9 plusOrMinus 0.2) }
      }
      assert(caught6.getMessage === "-7.0 was -6.9 plus or minus 0.2")

      val caught7 = intercept[TestFailedException] {
        minusSevenDotOh should be (-7.5 plusOrMinus 0.2)
      }
      assert(caught7.getMessage === "-7.0 was not -7.5 plus or minus 0.2")

      val caught8 = intercept[TestFailedException] {
        minusSevenDotOh should be (-6.5 plusOrMinus 0.2)
      }
      assert(caught8.getMessage === "-7.0 was not -6.5 plus or minus 0.2")
    }
  }
}


text:
package stroom.test.common.util.test;

import stroom.content.ContentPack;
import stroom.util.logging.LogUtil;
import stroom.util.zip.ZipUtil;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public abstract class FileSystemTestUtil {

    // These zips are downloaded by the gradle task downloadStroomContent
    // Ought to be the same as in ContentPackDownloader
    private static final Path CONTENT_PACK_DOWNLOADS_DIR = Paths.get(
            System.getProperty("user.home"),
            "/.stroom/contentPackDownload");
    private static final Path EXPLODED_DIR = CONTENT_PACK_DOWNLOADS_DIR.resolve("exploded");

    private static final long TEST_PREFIX = System.currentTimeMillis();
    private static long testSuffix = 0;

    private FileSystemTestUtil() {
        // Utility
    }

    /**
     * @return a unique string for testing
     */
    public static synchronized String getUniqueTestString() {
        testSuffix++;
        return TEST_PREFIX + "_" + testSuffix;
    }

    /**
     * @return The directory where content pack zips are downloaded to.
     * It will ensure it exists.
     */
    public static Path getContentPackDownloadsDir() {
        try {
            Files.createDirectories(CONTENT_PACK_DOWNLOADS_DIR);
        } catch (IOException e) {
            throw new RuntimeException(LogUtil.message(
                    "Error ensuring directory {}",
                    CONTENT_PACK_DOWNLOADS_DIR.toAbsolutePath()), e);
        }
        return CONTENT_PACK_DOWNLOADS_DIR;
    }

    /**
     * @return The directory where content pack zips are unzipped to.
     * It will ensure it exists.
     */
    public static Path getExplodedContentPacksDir() {
        try {
            Files.createDirectories(EXPLODED_DIR);
        } catch (IOException e) {
            throw new RuntimeException(LogUtil.message(
                    "Error ensuring directory {}",
                    EXPLODED_DIR.toAbsolutePath()), e);
        }
        return EXPLODED_DIR;
    }

    /**
     * @return The directory of the unziped content pack. If it has not already
     * been unziped then it will unzip the pack first, which is assumed to exist.
     */
    public static Path getExplodedContentPackDir(final ContentPack contentPack) {

        final Path explodedPackDir = getExplodedContentPacksDir()
                .resolve(contentPack.toString());

        if (!Files.exists(explodedPackDir)) {
            final Path downloadsDir = getContentPackDownloadsDir();
            final Path packZip = downloadsDir.resolve(contentPack.toFileName());

            if (!Files.exists(packZip)) {
                ContentPackDownloader.downloadContentPack(contentPack, downloadsDir);
            }

            // Unzip the zip file.
            try {
                ZipUtil.unzip(packZip, explodedPackDir);
            } catch (IOException e) {
                throw new RuntimeException(LogUtil.message("Error unzipping {} into {}",
                        packZip.toAbsolutePath().normalize(),
                        explodedPackDir.toAbsolutePath().normalize()));
            }
        }
        return explodedPackDir;
    }
}


text:
package com.sourcegraph.toolchain.cpp;

import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.apache.commons.lang3.StringUtils;

import java.util.LinkedList;
import java.util.List;

import static com.sourcegraph.toolchain.cpp.antlr4.CPP14Parser.Identifier;

/**
 * Namespace-aware path
 */
class NSPath {

    /**
     * Individual path components (foo, bar, baz) for ::foo::bar::baz
     */
    LinkedList<String> components = new LinkedList<>();

    /**
     * Individual terminal nodes (foo, bar, baz) for ::foo::bar::baz
     */
    LinkedList<TerminalNode> nodes = new LinkedList<>();
    /**
     * Indicates if path is absolute (starts with ::)
     */
    boolean absolute;
    /**
     * Normalized path foo.bar.baz for (foo::bar::baz)
     */
    String path;

    /**
     * Local name (last component)
     */
    String local;

    /**
     * Local name (last component)
     */
    TerminalNode localCtx;

    NSPath(ParserRuleContext ctx) {

        if (ctx == null) {
            absolute = false;
            path = StringUtils.EMPTY;
            return;
        }

        List<TerminalNode> nodes = getNestedComponents(ctx);
        absolute = "::".equals(ctx.getStart().getText());
        StringBuilder pathBuilder = new StringBuilder();
        for (TerminalNode node : nodes) {
            String ident = node.getText();
            components.add(ident);
            this.nodes.add(node);
            if (pathBuilder.length() > 0) {
                pathBuilder.append(CPPParseTreeListener.PATH_SEPARATOR);
            }
            pathBuilder.append(ident);
            local = ident;
            localCtx = node;
        }
        path = pathBuilder.toString();
    }

    /**
     * Extracts nested components (identifiers) (foo, bar, baz from foo::bar::baz)
     */
    private static List<TerminalNode> getNestedComponents(ParserRuleContext ctx) {
        List<TerminalNode> ret = new LinkedList<>();
        collectNestedComponents(ctx, ret);
        return ret;
    }

    /**
     * Extracts nested components (identiiers) (foo, bar, baz from foo::bar::baz)
     */
    private static void collectNestedComponents(ParseTree ctx, List<TerminalNode> ret) {
        int count = ctx.getChildCount();
        for (int i = 0; i < count; i++) {
            ParseTree child = ctx.getChild(i);
            if (child instanceof TerminalNode) {
                TerminalNode terminalNode = (TerminalNode) child;
                int type = terminalNode.getSymbol().getType();
                if (type == Identifier) {
                    ret.add(terminalNode);
                }
            } else {
                collectNestedComponents(child, ret);
            }
        }
    }

    NSPath parent() {
        NSPath ret = new NSPath(null);
        ret.absolute = absolute;
        if (!components.isEmpty()) {
            ret.components = new LinkedList<>(components.subList(0, components.size() - 1));
            if (!ret.components.isEmpty()) {
                ret.local = ret.components.getLast();
            }
        }
        if (!nodes.isEmpty()) {
            ret.nodes = new LinkedList<>(nodes.subList(0, nodes.size() - 1));
            if (!ret.nodes.isEmpty()) {
                ret.localCtx = ret.nodes.getLast();
            }
        }
        ret.path = StringUtils.join(ret.components, CPPParseTreeListener.PATH_SEPARATOR);
        return ret;
    }
}


text:
import logging
from math import acos, cos, sin, radians
import traceback

from geopy import geocoders, exc as geopy_exc

from famille import errors
from famille.utils.http import use_proxy

EARTH_RADIUS =  6371.0  # in km

def geolocate(address):
    """
    Geolocate an address, i.e. return its
    GPS coordinates.

    :param address:         the address to geolocalize
    """
    try:
        with use_proxy():
            geocoder = geocoders.GoogleV3(scheme="http")
            _, (lat, lon) = geocoder.geocode(address)
        return lat, lon
    except geopy_exc.GeopyError:
        logging.critical("Cannot geolocate address due to API error: %s", traceback.format_exc())
        raise errors.GeolocationError("Address '%s' cannot be geolocated" % address)

def geodistance(origin, to):
    """
    Calculate the distance from a GPS point to another,
    using the spherical law of cosines.
    See http://www.movable-type.co.uk/scripts/latlong.html

    :param origin:    a Geolocation model
    :param to:        a Geolocation model
    """
    lat1, lon1 = origin.lat, origin.lon
    lat2, lon2 = to.lat, to.lon
    delta_lon = lon2 - lon1

    lat1, lat2, delta_lon = map(radians, (lat1, lat2, delta_lon))
    return acos(sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(delta_lon)) * EARTH_RADIUS

def is_close_enough(origin, to, distance):
    """
    A utility function that computes if a point is close
    enough to another point.

    :param origin:         a Geolocation model
    :param to:             a Geolocation model
    :param distance:       the distance to test
    """
    if not origin or not to:
        raise ValueError("One of the two points is missing")

    return geodistance(origin, to) <= distance


text:
var searchData=
[
  ['getting_20started',['Getting Started',['../page_getting_started.html',1,'']]]
];


text:
package org.jsfr.json;

import java.util.Collection;

public class DispatchUtil {

    public static void dispatchValueToListeners(Object value, Collection<JsonPathListener> listeners, ParsingContext context, ErrorHandlingStrategy errorHandlingStrategy) {
        for (JsonPathListener listener : listeners) {
            if (context.isStopped()) {
                break;
            }
            try {
                listener.onValue(value, context);
            } catch (Exception e) {
                errorHandlingStrategy.handleExceptionFromListener(e, context);
            }
        }
    }

    public static void dispatchValueToListeners(Object value, JsonPathListener[] listeners, ParsingContext context, ErrorHandlingStrategy errorHandlingStrategy) {
        for (JsonPathListener listener : listeners) {
            if (context.isStopped()) {
                break;
            }
            try {
                listener.onValue(value, context);
            } catch (Exception e) {
                errorHandlingStrategy.handleExceptionFromListener(e, context);
            }
        }
    }

}


text:
package com.cloud.storage.download;

import org.apache.log4j.Level;

import com.cloud.agent.api.storage.DownloadAnswer;
import com.cloud.agent.api.storage.DownloadProgressCommand.RequestType;
import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;

public abstract class DownloadActiveState extends DownloadState {

	public DownloadActiveState(DownloadListener dl) {
		super(dl);
	}

	@Override
	public String handleAnswer(DownloadAnswer answer) {
		if (s_logger.isTraceEnabled()) {
			s_logger.trace("handleAnswer, answer status=" + answer.getDownloadStatus() + ", curr state=" + getName());
		}
		switch (answer.getDownloadStatus()) {
		case DOWNLOAD_IN_PROGRESS:
			getDownloadListener().scheduleStatusCheck(RequestType.GET_STATUS);
			return Status.DOWNLOAD_IN_PROGRESS.toString();
		case DOWNLOADED:
			getDownloadListener().cancelTimeoutTask();
			return Status.DOWNLOADED.toString();
		case NOT_DOWNLOADED:
			getDownloadListener().scheduleStatusCheck(RequestType.GET_STATUS);
			return Status.NOT_DOWNLOADED.toString();
		case DOWNLOAD_ERROR:
			getDownloadListener().cancelStatusTask();
			getDownloadListener().cancelTimeoutTask();
			return Status.DOWNLOAD_ERROR.toString();
		case UNKNOWN:
			getDownloadListener().cancelStatusTask();
			getDownloadListener().cancelTimeoutTask();
			return Status.DOWNLOAD_ERROR.toString();
		default:
			return null;
		}
	}

	@Override
	public  void onEntry(String prevState, DownloadEvent event, Object evtObj) {
		if (s_logger.isTraceEnabled()) {
			getDownloadListener().log("onEntry, prev state= " + prevState + ", curr state=" + getName() + ", event=" + event, Level.TRACE);
		}

		if (event==DownloadEvent.DOWNLOAD_ANSWER) {
			getDownloadListener().updateDatabase((DownloadAnswer)evtObj);
			getDownloadListener().setLastUpdated();
		}

	}

	@Override
	public  void onExit() {
	}

	@Override
	public  String handleTimeout(long updateMs) {
		if (s_logger.isTraceEnabled()) {
			getDownloadListener().log("handleTimeout, updateMs=" + updateMs + ", curr state= " + getName(), Level.TRACE);
		}
		String newState = this.getName();
		if (updateMs > 5*DownloadListener.STATUS_POLL_INTERVAL){
			newState=Status.DOWNLOAD_ERROR.toString();
			getDownloadListener().log("timeout: transitioning to download error state, currstate=" + getName(), Level.DEBUG );
		} else if (updateMs > 3*DownloadListener.STATUS_POLL_INTERVAL) {
			getDownloadListener().cancelStatusTask();
			getDownloadListener().scheduleImmediateStatusCheck(RequestType.GET_STATUS);
			getDownloadListener().scheduleTimeoutTask(3*DownloadListener.STATUS_POLL_INTERVAL);
			getDownloadListener().log(getName() + " first timeout: checking again ", Level.DEBUG );
		} else {
			getDownloadListener().scheduleTimeoutTask(3*DownloadListener.STATUS_POLL_INTERVAL);
		}
		return newState;
	}

	@Override
	public  String handleAbort(){
		return Status.ABANDONED.toString();
	}

	@Override
	public  String handleDisconnect(){

		return Status.DOWNLOAD_ERROR.toString();
	}

}


text:
package io.dropwizard.jetty;

import com.codahale.metrics.Timer;
import org.eclipse.jetty.io.Connection;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.server.ConnectionFactory;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.util.component.ContainerLifeCycle;

import javax.annotation.Nullable;
import java.util.List;

import static java.util.Objects.requireNonNull;

/**
 * A version {@link com.codahale.metrics.jetty9.InstrumentedConnectionFactory}, which supports Jetty 9.3 API.
 * NOTE: This class could be replaced, when dropwizard-metrics-jetty9 will support Jetty 9.3.
 */
public class Jetty93InstrumentedConnectionFactory extends ContainerLifeCycle implements ConnectionFactory {

    private final ConnectionFactory connectionFactory;
    private final Timer timer;

    public Jetty93InstrumentedConnectionFactory(ConnectionFactory connectionFactory, Timer timer) {
        this.connectionFactory = connectionFactory;
        this.timer = timer;
        addBean(connectionFactory);
    }

    public ConnectionFactory getConnectionFactory() {
        return connectionFactory;
    }

    public Timer getTimer() {
        return timer;
    }

    @Override
    public String getProtocol() {
        return connectionFactory.getProtocol();
    }

    @Override
    public List<String> getProtocols() {
        return connectionFactory.getProtocols();
    }

    @Override
    public Connection newConnection(Connector connector, EndPoint endPoint) {
        final Connection connection = connectionFactory.newConnection(connector, endPoint);
        connection.addListener(new Connection.Listener() {

            @Nullable
            private Timer.Context context;

            @Override
            public void onOpened(Connection connection) {
                this.context = timer.time();
            }

            @Override
            public void onClosed(Connection connection) {
                requireNonNull(context).stop();
            }
        });
        return connection;
    }
}


text: ps aux | grep 'unicorn' | awk '{print $2}' | xargs kill -9


text:
class PrefService;

namespace extensions {

class ExtensionsAPIClient;

// An ExtensionsBrowserClient that supports a single content::BrowserContext
// with no related incognito context.
// Must be initialized via InitWithBrowserContext() once the BrowserContext is
// created.
class ShellExtensionsBrowserClient : public ExtensionsBrowserClient {
 public:
  ShellExtensionsBrowserClient();
  ShellExtensionsBrowserClient(const ShellExtensionsBrowserClient&) = delete;
  ShellExtensionsBrowserClient& operator=(const ShellExtensionsBrowserClient&) =
      delete;
  ~ShellExtensionsBrowserClient() override;

  // ExtensionsBrowserClient overrides:
  bool IsShuttingDown() override;
  bool AreExtensionsDisabled(const base::CommandLine& command_line,
                             content::BrowserContext* context) override;
  bool IsValidContext(content::BrowserContext* context) override;
  bool IsSameContext(content::BrowserContext* first,
                     content::BrowserContext* second) override;
  bool HasOffTheRecordContext(content::BrowserContext* context) override;
  content::BrowserContext* GetOffTheRecordContext(
      content::BrowserContext* context) override;
  content::BrowserContext* GetOriginalContext(
      content::BrowserContext* context) override;

  content::BrowserContext* GetRedirectedContextInIncognito(
      content::BrowserContext* context,
      bool force_guest_profile,
      bool force_system_profile) override;
  content::BrowserContext* GetContextForRegularAndIncognito(
      content::BrowserContext* context,
      bool force_guest_profile,
      bool force_system_profile) override;
  content::BrowserContext* GetRegularProfile(
      content::BrowserContext* context,
      bool force_guest_profile,
      bool force_system_profile) override;

#if BUILDFLAG(IS_CHROMEOS_ASH)
  std::string GetUserIdHashFromContext(
      content::BrowserContext* context) override;
#endif
#if BUILDFLAG(IS_CHROMEOS_LACROS)
  bool IsFromMainProfile(content::BrowserContext* context) override;
#endif
  bool IsGuestSession(content::BrowserContext* context) const override;
  bool IsExtensionIncognitoEnabled(
      const std::string& extension_id,
      content::BrowserContext* context) const override;
  bool CanExtensionCrossIncognito(
      const Extension* extension,
      content::BrowserContext* context) const override;
  base::FilePath GetBundleResourcePath(
      const network::ResourceRequest& request,
      const base::FilePath& extension_resources_path,
      int* resource_id) const override;
  void LoadResourceFromResourceBundle(
      const network::ResourceRequest& request,
      mojo::PendingReceiver<network::mojom::URLLoader> loader,
      const base::FilePath& resource_relative_path,
      int resource_id,
      scoped_refptr<net::HttpResponseHeaders> headers,
      mojo::PendingRemote<network::mojom::URLLoaderClient> client) override;
  bool AllowCrossRendererResourceLoad(
      const network::ResourceRequest& request,
      network::mojom::RequestDestination destination,
      ui::PageTransition page_transition,
      int child_id,
      bool is_incognito,
      const Extension* extension,
      const ExtensionSet& extensions,
      const ProcessMap& process_map) override;
  PrefService* GetPrefServiceForContext(
      content::BrowserContext* context) override;
  void GetEarlyExtensionPrefsObservers(
      content::BrowserContext* context,
      std::vector<EarlyExtensionPrefsObserver*>* observers) const override;
  ProcessManagerDelegate* GetProcessManagerDelegate() const override;
  std::unique_ptr<ExtensionHostDelegate> CreateExtensionHostDelegate() override;
  bool DidVersionUpdate(content::BrowserContext* context) override;
  void PermitExternalProtocolHandler() override;
  bool IsInDemoMode() override;
  bool IsScreensaverInDemoMode(const std::string& app_id) override;
  bool IsRunningInForcedAppMode() override;
  bool IsAppModeForcedForApp(const ExtensionId& extension_id) override;
  bool IsLoggedInAsPublicAccount() override;
  ExtensionSystemProvider* GetExtensionSystemFactory() override;
  void RegisterBrowserInterfaceBindersForFrame(
      mojo::BinderMapWithContext<content::RenderFrameHost*>* binder_map,
      content::RenderFrameHost* render_frame_host,
      const Extension* extension) const override;
  std::unique_ptr<RuntimeAPIDelegate> CreateRuntimeAPIDelegate(
      content::BrowserContext* context) const override;
  const ComponentExtensionResourceManager*
  GetComponentExtensionResourceManager() override;
  void BroadcastEventToRenderers(
      events::HistogramValue histogram_value,
      const std::string& event_name,
      base::Value::List args,
      bool dispatch_to_off_the_record_profiles) override;
  ExtensionCache* GetExtensionCache() override;
  bool IsBackgroundUpdateAllowed() override;
  bool IsMinBrowserVersionSupported(const std::string& min_version) override;
  ExtensionWebContentsObserver* GetExtensionWebContentsObserver(
      content::WebContents* web_contents) override;
  KioskDelegate* GetKioskDelegate() override;
  bool IsLockScreenContext(content::BrowserContext* context) override;
  std::string GetApplicationLocale() override;
  std::string GetUserAgent() const override;

  // |context| is the single BrowserContext used for IsValidContext().
  // |pref_service| is used for GetPrefServiceForContext().
  void InitWithBrowserContext(content::BrowserContext* context,
                              PrefService* pref_service);

  // Sets the API client.
  void SetAPIClientForTest(ExtensionsAPIClient* api_client);

 private:
  // The single BrowserContext for app_shell. Not owned. Must be initialized
  // when ready by calling InitWithBrowserContext().
  raw_ptr<content::BrowserContext, DanglingUntriaged> browser_context_ =
      nullptr;

  // The PrefService for |browser_context_|. Not owned. Must be initialized when
  // ready by calling InitWithBrowserContext().
  raw_ptr<PrefService, DanglingUntriaged> pref_service_ = nullptr;

  // Support for extension APIs.
  std::unique_ptr<ExtensionsAPIClient> api_client_;

  // The extension cache used for download and installation.
  std::unique_ptr<ExtensionCache> extension_cache_;

  std::unique_ptr<KioskDelegate> kiosk_delegate_;
};

}  // namespace extensions

#endif  // EXTENSIONS_SHELL_BROWSER_SHELL_EXTENSIONS_BROWSER_CLIENT_H_


text:
'''
Output to STDOUT stuffs.

@author: Michael Eddington
@version: $Id: stdout.py 2020 2010-04-14 23:13:14Z meddingt $
'''

#
# Copyright (c) Michael Eddington
#
# 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.
#

# Authors:
#   Michael Eddington (mike@phed.org)

# $Id: stdout.py 2020 2010-04-14 23:13:14Z meddingt $

from Peach.publisher import Publisher
import sys

class Stdout(Publisher):
	'''
	Basic stdout publisher.  All data is written to stdout.  No input
	is available from this publisher.  Excelent for testing.
	'''

	def accept(self):
		pass

	def connect(self):
		pass

	def close(self):
		pass

	def send(self, data):
		print data

	def receive(self, size = None):
		return ''

	def call(self, method, args):
		str = ""
		for a in args:
			str += "%s, " % repr(a)

		print "%s(%s)" % (method, str[:-2])

		return ''

class StdoutHex(Publisher):
	'''
	Basic stdout publisher that emits a hex dump.  All data is written to stdout.  No input
	is available from this publisher.  Excellent for testing (without the BEEPS).

	'''

	def dump2(src, length=16):

		return result

	def accept(self):
		pass

	def connect(self):
		pass

	def close(self):
		pass

	def send(self, src):
		# yoinked from http://code.activestate.com/recipes/142812/

		FILTER=''.join([(len(repr(chr(x)))==3) and chr(x) or '.' for x in range(256)])
		N=0; result=''
		length=16
		while src:
			s,src = src[:length],src[length:]
			hexa = ' '.join(["%02X"%ord(x) for x in s])
			s = s.translate(FILTER)
			result += "%04X   %-*s   %s\n" % (N, length*3, hexa, s)
			N+=length
		print result

	def receive(self, size = None):
		return ''

	def call(self, method, args):
		str = ""
		for a in args:
			str += "%s, " % repr(a)

		print "%s(%s)" % (method, str[:-2])

		return ''

class Null(Publisher):
	'''
	Basic stdout publisher.  All data is written to stdout.  No input
	is available from this publisher.  Excelent for testing.
	'''

	def accept(self):
		pass

	def connect(self):
		pass

	def close(self):
		pass

	def send(self, data):
		pass

	def receive(self):
		return ''

	def call(self, method, args):
		return ''

class StdoutCtypes(Publisher):
	'''

	'''

	#: Indicates which method should be called.
	withNode = True

	def connect(self):
		pass

	def sendWithNode(self, data, dataNode):
		'''
		Publish some data

		@type	data: string
		@param	data: Data to publish
		@type   dataNode: DataElement
		@param  dataNode: Root of data model that produced data
		'''
		value = dataNode.asCType()
		print value
		print dir(value)

	def close(self):
		'''
		Close current stream/connection.
		'''
		pass

# end