text:
<?php

namespace Adldap\Query;

class Grammar
{
    /**
     * Wraps a query string in brackets.
     *
     * @param string $query
     * @param string $prefix
     * @param string $suffix
     *
     * @return string
     */
    public function wrap($query, $prefix = '(', $suffix = ')')
    {
        return $prefix.$query.$suffix;
    }

    /**
     * Compiles the Builder instance into an LDAP query string.
     *
     * @param \Adldap\Query\Builder $builder
     *
     * @return string
     */
    public function compileQuery(Builder $builder)
    {
        $query = implode(null, $builder->filters);

        $query = $this->compileWheres($builder, $query);

        $query = $this->compileOrWheres($builder, $query);

        // Count the total amount of filters.
        $total = count($builder->wheres)
            + count($builder->filters);

        // Make sure we wrap the query in an 'and' if using
        // multiple filters. We also need to check if only
        // one where is used with multiple orWheres, that
        // we wrap it in an 'and' query.
        if ($total > 1 || (count($builder->wheres) === 1 && count($builder->orWheres) > 0)) {
            $query = $this->compileAnd($query);
        }

        return $query;
    }

    /**
     * Returns a query string for equals.
     *
     * Produces: (field=value)
     *
     * @param string $field
     * @param string $value
     *
     * @return string
     */
    public function compileEquals($field, $value)
    {
        return $this->wrap($field.Operator::$equals.$value);
    }

    /**
     * Returns a query string for does not equal.
     *
     * Produces: (!(field=value))
     *
     * @param string $field
     * @param string $value
     *
     * @return string
     */
    public function compileDoesNotEqual($field, $value)
    {
        return $this->wrap(Operator::$doesNotEqual.$this->compileEquals($field, $value));
    }

    /**
     * Returns a query string for greater than or equals.
     *
     * Produces: (field>=value)
     *
     * @param string $field
     * @param string $value
     *
     * @return string
     */
    public function compileGreaterThanOrEquals($field, $value)
    {
        return $this->wrap($field.Operator::$greaterThanOrEquals.$value);
    }

    /**
     * Returns a query string for less than or equals.
     *
     * Produces: (field<=value)
     *
     * @param string $field
     * @param string $value
     *
     * @return string
     */
    public function compileLessThanOrEquals($field, $value)
    {
        return $this->wrap($field.Operator::$lessThanOrEquals.$value);
    }

    /**
     * Returns a query string for approximately equals.
     *
     * Produces: (field~=value)
     *
     * @param string $field
     * @param string $value
     *
     * @return string
     */
    public function compileApproximatelyEquals($field, $value)
    {
        return $this->wrap($field.Operator::$approximatelyEquals.$value);
    }

    /**
     * Returns a query string for starts with.
     *
     * Produces: (field=value*)
     *
     * @param string $field
     * @param string $value
     *
     * @return string
     */
    public function compileStartsWith($field, $value)
    {
        return $this->wrap($field.Operator::$equals.$value.Operator::$has);
    }

    /**
     * Returns a query string for does not start with.
     *
     * Produces: (!(field=*value))
     *
     * @param string $field
     * @param string $value
     *
     * @return string
     */
    public function compileNotStartsWith($field, $value)
    {
        return $this->wrap(Operator::$doesNotEqual.$this->compileStartsWith($field, $value));
    }

    /**
     * Returns a query string for ends with.
     *
     * Produces: (field=*value)
     *
     * @param string $field
     * @param string $value
     *
     * @return string
     */
    public function compileEndsWith($field, $value)
    {
        return $this->wrap($field.Operator::$equals.Operator::$has.$value);
    }

    /**
     * Returns a query string for does not end with.
     *
     * Produces: (!(field=value*))
     *
     * @param string $field
     * @param string $value
     *
     * @return string
     */
    public function compileNotEndsWith($field, $value)
    {
        return $this->wrap(Operator::$doesNotEqual.$this->compileEndsWith($field, $value));
    }

    /**
     * Returns a query string for contains.
     *
     * Produces: (field=*value*)
     *
     * @param string $field
     * @param string $value
     *
     * @return string
     */
    public function compileContains($field, $value)
    {
        return $this->wrap($field.Operator::$equals.Operator::$has.$value.Operator::$has);
    }

    /**
     * Returns a query string for does not contain.
     *
     * Produces: (!(field=*value*))
     *
     * @param string $field
     * @param string $value
     *
     * @return string
     */
    public function compileNotContains($field, $value)
    {
        return $this->wrap(Operator::$doesNotEqual.$this->compileContains($field, $value));
    }

    /**
     * Returns a query string for a where has.
     *
     * Produces: (field=*)
     *
     * @param string $field
     *
     * @return string
     */
    public function compileHas($field)
    {
        return $this->wrap($field.Operator::$equals.Operator::$has);
    }

    /**
     * Returns a query string for a where does not have.
     *
     * Produces: (!(field=*))
     *
     * @param string $field
     *
     * @return string
     */
    public function compileNotHas($field)
    {
        return $this->wrap(Operator::$doesNotEqual.$this->compileHas($field));
    }

    /**
     * Wraps the inserted query inside an AND operator.
     *
     * Produces: (&query)
     *
     * @param string $query
     *
     * @return string
     */
    public function compileAnd($query)
    {
        return $this->wrap($query, '(&');
    }

    /**
     * Wraps the inserted query inside an OR operator.
     *
     * Produces: (|query)
     *
     * @param string $query
     *
     * @return string
     */
    public function compileOr($query)
    {
        return $this->wrap($query, '(|');
    }

    /**
     * Assembles all where clauses in the current wheres property.
     *
     * @param Builder $builder
     * @param string  $query
     *
     * @return string
     */
    protected function compileWheres(Builder $builder, $query = '')
    {
        foreach ($builder->wheres as $where) {
            $query .= $this->compileWhere($where);
        }

        return $query;
    }

    /**
     * Assembles all or where clauses in the current orWheres property.
     *
     * @param Builder $builder
     * @param string  $query
     *
     * @return string
     */
    protected function compileOrWheres(Builder $builder, $query = '')
    {
        $ors = '';

        foreach ($builder->orWheres as $where) {
            $ors .= $this->compileWhere($where);
        }

        // Make sure we wrap the query in an 'or' if using
        // multiple orWheres. For example (|(QUERY)(ORWHEREQUERY)).
        if ((!empty($query) && count($builder->getOrWheres()) > 0) || count($builder->getOrWheres()) > 1) {
            $query .= $this->compileOr($ors);
        } else {
            $query .= $ors;
        }

        return $query;
    }

    /**
     * Assembles a single where query based
     * on its operator and returns it.
     *
     * @param array $where
     *
     * @return string|null
     */
    protected function compileWhere(array $where = [])
    {
        // The compile function prefix.
        $prefix = 'compile';

        // Make sure the operator key exists inside the where clause.
        if (array_key_exists(Builder::$whereOperatorKey, $where)) {
            // Get the operator from the where.
            $operator = $where[Builder::$whereOperatorKey];

            // Get the name of the operator.
            $name = array_search($operator, Operator::all());

            if ($name !== false) {
                // If the name was found we'll camel case it
                // to run it through the compile method.
                $method = $prefix.ucfirst($name);

                // Make sure the compile method exists for the operator.
                if (method_exists($this, $method)) {
                    return $this->{$method}($where[Builder::$whereFieldKey], $where[Builder::$whereValueKey]);
                }
            }
        }
    }
}


text:
package fr.diabhelp.diabhelp.BDD.Ressource;

/**
 * Created by naqued on 28/09/15.
 */
public class User {
    // Notez que l'identifiant est un long
    private long id;
    private String user;
    private String pwd;

    public User(long id, String user, String pwd) {
        super();
        this.id = id;
        this.user = user;
        this.pwd = pwd;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }
    public String getPwd() {
        return this.pwd;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
}

redpajama_set_name: RedPajamaGithub


text:
using Aspose.Email.Outlook;
using Aspose.Email.Outlook.Pst;

/*
This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Email for .NET API reference
when the project is build. Please check https://Docs.nuget.org/consume/nuget-faq for more information.
If you do not wish to use NuGet, you can manually download Aspose.Email for .NET API from http://www.aspose.com/downloads,
install it and then add its reference to this project. For any issues, questions or suggestions
please feel free to contact us using http://www.aspose.com/community/forums/default.aspx
*/

namespace Aspose.Email.Examples.CSharp.Email.Outlook
{
    class ExtractAttachmentsFromPSTMessages
    {
        public static void Run()
        {
            // The path to the File directory.
            // ExStart:ExtractAttachmentsFromPSTMessages
            string dataDir = RunExamples.GetDataDir_Outlook();

            using (PersonalStorage personalstorage = PersonalStorage.FromFile(dataDir + "Outlook.pst"))
            {
                FolderInfo folder = personalstorage.RootFolder.GetSubFolder("Inbox");

                foreach (var messageInfo in folder.EnumerateMessagesEntryId())
                {
                    MapiAttachmentCollection attachments = personalstorage.ExtractAttachments(messageInfo);

                    if (attachments.Count != 0)
                    {
                        foreach (var attachment in attachments)
                        {
                            if (!string.IsNullOrEmpty(attachment.LongFileName))
                            {
                                if (attachment.LongFileName.Contains(".msg"))
                                {
                                    continue;
                                }
                                else
                                {
                                    attachment.Save(dataDir + @"\Attachments\" + attachment.LongFileName);
                                }
                            }
                        }
                    }
                }
            }
            // ExEnd:ExtractAttachmentsFromPSTMessages
        }
    }
}


text:
import { Emitter } from "@ckeditor/ckeditor5-utils/src/emittermixin";

export default function clickOutsideHandler(options?: {
    emitter: Emitter;
    activator: () => boolean;
    contextElements: HTMLElement[];
    callback: () => void;
}): void;


text:
/*

FILE DESCRIPTION

Defines the data structure for the engine.

*/

#pragma once

#include <GL\glew.h>
#include <glm\glm.hpp>

enum VERTEX_TYPES
{
	VERTEX, VERTEX_2D, VERTEX_3D, NUM_TYPES
};

struct Position3D // the position struct
{
	float x, y, z;
};

struct Position2D
{
	float x, y;
};

struct Color8 // the color struct
{
	GLubyte r, g, b;

	Color8() : r(0), g(0), b(0) { /*Empty*/ } // the 0 constructor for color

	Color8(GLubyte R, GLubyte G, GLubyte B) : // the contructor for color to set to a specific color
		r(R), g(G), b(B) { /*Empty*/ }
};

struct TexCoord // the tex coordinations struct
{
	float x, y;
};
/*
The basic Vertex class that other Vertex classes derive from
*/
class Vertex
{
public:

	Vertex()
	{
		/* default empty constructor */
	};
	~Vertex()
	{
		/* default empty destructor */
	};
	virtual void setColor(Color8 col) // set the color to a specific color
	{
		color = col;
	}
	virtual void setTexCoord(glm::vec2 tex) // set the tex coord to glm::vec2
	{
		texCoord.x = tex.x;
		texCoord.y = tex.y;
	}
	virtual void setTexCoord(float x, float y)
	{
		texCoord.x = x;
		texCoord.y = y;
	}

	virtual void setPosition() {};
	virtual void setPosition(glm::vec2) {};
	virtual void setPosition(glm::vec3) {};
	virtual void setPosition(float x, float y) {};
	virtual void setPosition(float x, float y, float z) {};

	virtual Position2D getPosition2D() { return Position2D(); };
	virtual Position3D getPosition3D() { return Position3D(); };

	virtual Color8 getColor() { return color; }
	virtual TexCoord getTexCoord() { return texCoord; }

	Color8 color;
	TexCoord texCoord;
protected:
private:
};

/*
The 3D Vertex class
*/
class Vertex3D  : public Vertex
{
public:
	Vertex3D()
	{

	};
	void setPosition(glm::vec3 pos)  // set the position to a glm::vec3
	{
		position.x = pos.x;
		position.y = pos.y;
		position.z = pos.z;
	}
	void setPosition(float x, float y, float z)
	{
		position.x = x;
		position.y = y;
		position.z = z;

	}

	Position3D getPosition3D() { return this->position; }

	Position3D position;
protected:
private:
};
/*
The 2D Vertex class
*/
class Vertex2D : public Vertex // the vertex2D class, combines all the previus structs.
{
public:
	Vertex2D()
	{

	};

	void setPosition(glm::vec2 pos) // set the position to a glm::vec2
	{
		position.x = pos.x;
		position.y = pos.y;
	}
	void setPosition(float x, float y)
	{
		position.x = x;
		position.y = y;
	}

	Position2D getPosition2D() { return this->position; }
	Position2D position;
protected:
private:
};


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Test 1 - audio.js</title>

audiojs.createAll()

Load from remote URL

<audio preload="auto">
    <source src="https://raw.githubusercontent.com/kolber/audiojs/master/mp3/bensound-dubstep.mp3">
</audio>

Load local file

<audio preload="auto">
    <source src="../mp3/bensound-dubstep.mp3">
</audio>

Load failure (from source)

<audio preload="auto">
    <source src="./mp3/invalid.mp3">
</audio>

Royalty Free Music from Bensound


text:
/*****************************************************************************

  rsa.cpp -- An implementation of the RSA public-key cipher. The
             following implementation is based on the one given in Cormen et
             al., Inroduction to Algorithms, 1991. I'll refer to this book as
             CLR because of its authors. This implementation shows the usage of
             arbitrary precision types of SystemC. That is, these types in
             SystemC can be used to implement algorithmic examples regarding
             arbitrary precision integers. The algorithms used are not the most
             efficient ones; however, they are intended for explanatory
             purposes, so they are simple and perform their job correctly.
             Below, NBITS shows the maximum number of bits in n, the variable
             that is a part of both the public and secret keys, P and S,
             respectively. NBITS can be made larger at the expense of longer
             running time. For example, CLR mentions that the RSA cipher uses
             large primes that contain approximately 100 decimal digits. This
             means that NBITS should be set to approximately 560.

             Some background knowledge: A prime number p > 1 is an integer that
             has only two divisiors, 1 and p itself. For example, 2, 3, 5, 7,
             and 11 are all primes. If p is not a prime number, it is called a
             composite number. If we are given two primes p and q, it is easy
             to find their product p * q; however, if we are given a number m
             which happens to be the product of two primes p and q that we do
             not know, it is very difficult to find p and q if m is very large,
             i.e., it is very difficult to factor m. The RSA public-key
             cryptosystem is based on this fact. Internally, we use the
             Miller-Rabin randomized primality test to deal with primes. More
             information can be obtained from pp. 831-836 in CLR, the first
             edition.

  Original Author: Ali Dasdan, Synopsys, Inc.

 *****************************************************************************/

/*****************************************************************************

  MODIFICATION LOG - modifiers, enter your name, affiliation, date and
  changes you are making here.

      Name, Affiliation, Date:
  Description of Modification:

 *****************************************************************************/

#include <stdlib.h>
#include <sys/types.h>
#include <time.h>
#include <stdlib.h>    // drand48, srand48
#include "systemc.h"

#define DEBUG_SYSTEMC // #undef this to disable assertions.

// NBITS is the number of bits in n of public and secret keys P and
// S. HALF_NBITS is the number of bits in p and q, which are the prime
// factors of n.
#define NBITS         250
#define HALF_NBITS    ( NBITS / 2 )

// +2 is for the format specifier '0b' to make the string binary.
#define STR_SIZE      ( NBITS + 2 )
#define HALF_STR_SIZE ( HALF_NBITS + 2 )

typedef sc_bigint<NBITS>  bigint;

// Return the absolute value of x.
inline
bigint
abs_val( const sc_signed& x )
{
  return ( x < 0 ? -x : x );
}

// Initialize the random number generator. If seed == -1, the
// generator will be initialized with the system time. If not, it will
// be initialized with the given seed. This way, an experiment with
// random numbers becomes reproducible.
inline
long
randomize( int seed  )
{
  long in_seed;  // time_t is long.

  in_seed = ( seed <= 0 ? time( 0 ) : seed );

#ifndef WIN32
  srand48( in_seed );
#else
  srand( ( unsigned ) in_seed );
#endif

  return in_seed;
}

// Flip a coin with probability p.

#ifndef WIN32

inline
bool
flip( double p )
{
  return ( drand48() < p );
}

#else

inline
bool
flip( double p )
{
  const int MAX_VAL = ( 1 << 15 );

  // rand() produces an integer between 0 and 2^15-1, so rand() /
  // MAX_VAL is a number between 0 and 1, which is required to compare
  // with p.
  return ( rand() < ( int ) ( p * MAX_VAL ) );
}

#endif

// Randomly generate a bit string with nbits bits.  str has a length
// of nbits + 1. This function is used to generate random messages to
// process.
inline
void
rand_bitstr( char *str, int nbits )
{
  assert( nbits >= 4 );

  str[ 0 ] = '0';
  str[ 1 ] = 'b';
  str[ 2 ] = '0';  // Sign for positive numbers.

  for ( int i = 3; i < nbits; ++i )
    str[ i ] = ( flip( 0.5 ) == true ? '1' : '0' );

  str[ nbits ] = '\0';
}

// Generate "111..111" with nbits bits for masking.
// str has a length of nbits + 1.
inline
void
max_bitstr( char *str, int nbits )
{
  assert( nbits >= 4 );

  str[ 0 ] = '0';
  str[ 1 ] = 'b';
  str[ 2 ] = '0';  // Sign for positive numbers.

  for ( int i = 3; i < nbits; ++i )
    str[ i ] = '1';

  str[ nbits ] = '\0';
}

// Return a positive remainder.
inline
bigint
ret_pos( const bigint& x, const bigint& n )
{
  if ( x < 0 )
    return x + n;
  return x;
}

// Compute the greatest common divisor ( gcd ) of a and b. This is
// Euclid's algorithm. This algorithm is at least 2,300 years old! The
// non-recursive version of this algorithm is not as elegant.
bigint
gcd( const bigint& a, const bigint& b )
{
  if ( b == 0 )
    return a;
  return gcd( b, a % b );
}

// Compute d, x, and y such that d = gcd( a, b ) = ax + by. x and y can
// be zero or negative. This algorithm is also Euclid's algorithm but
// it is extended to also find x and y. Recall that the existence of x
// and y is guaranteed by Euclid's algorithm.
void
euclid( const bigint& a, const bigint& b, bigint& d, bigint& x, bigint& y )
{
  if ( b != 0 ) {
    euclid( b, a % b, d, x, y );

    bigint tmp = x;
    x = y;
    y = tmp - ( a / b ) * y;
  }
  else {
    d = a;
    x = 1;
    y = 0;
  }
}

// Return d = a^b % n, where ^ represents exponentiation.
inline
bigint
modular_exp( const bigint& a, const bigint& b, const bigint& n )
{
  bigint d = 1;

  for ( int i = b.length() - 1; i >= 0; --i )
  {
    d = ( d * d ) % n;
    if ( b[ i ] )
      d = ( d * a ) % n;
  }

  return ret_pos( d, n );
}

// Return the multiplicative inverse of a, modulo n, when a and n are
// relatively prime. Recall that x is a multiplicative inverse of a,
// modulo n, if a * x = 1 ( mod n ).
inline
bigint
inverse( const bigint& a, const bigint& n )
{
  bigint d, x, y;

  euclid( a, n, d, x, y );
  assert( d == 1 );
  x %= n;

  return ret_pos( x, n );
}

// Find a small odd integer a that is relatively prime to n. I do not
// know an efficient algorithm to do that but the loop below seems to
// work; it usually iterates a few times. Recall that a is relatively
// prime to n if their only common divisor is 1, i.e., gcd( a, n ) ==
// 1.
inline
bigint
find_rel_prime( const bigint& n )
{
  bigint a = 3;
  while ( true ) {
    if ( gcd( a, n ) == 1 )
      break;
    a += 2;
#ifdef DEBUG_SYSTEMC
    assert( a < n );
#endif
  }

  return a;
}

// Return true if and only if a is a witness to the compositeness of
// n, i.e., a can be used to prove that n is composite.
inline
bool
witness( const bigint& a, const bigint& n )
{
  bigint n_minus1 = n - 1;
  bigint x;
  bigint d = 1;

  // Compute d = a^( n-1 ) % n.
  for ( int i = n.length() - 1; i >= 0; --i )
  {
    // Sun's SC5 bug when compiling optimized version
    // makes the wrong assignment if abs_val() is inlined
    //x = (sc_signed)d<0?-(sc_signed)d:(sc_signed)d;//abs_val( d );
    if(d<0)
      {
      x = -d;
      assert(x==-d);
      }
    else
      {
      x = d;
      assert(x==d);
      }
    d = ( d * d ) % n;

    // x is a nontrivial square root of 1 modulo n ==> n is composite.
    if ( ( abs_val( d ) == 1 ) && ( x != 1 ) && ( x != n_minus1 ) )
      return true;

    if ( n_minus1[ i ] )
      d = ( d * a ) % n;
  }

  // d = a^( n-1 ) % n != 1 ==> n is composite.
  if ( abs_val( d ) != 1 )
    return true;

  return false;
}

// Check to see if n has any small divisors. For small numbers, we do
// not have to run the Miller-Rabin primality test. We define "small"
// to be less than 1023. You can change it if necessary.
inline
bool
div_test( const bigint& n )
{
  int limit;

  if ( n < 1023 )
    limit = n.to_int() - 2;
  else
    limit = 1023;

  for ( int i = 3; i <= limit; i += 2 ) {
    if ( n % i == 0 )
      return false;   // n is composite.
  }

  return true;  // n may be prime.
}

// Return true if n is almost surely prime, return false if n is
// definitely composite.  This test, called the Miller-Rabin primality
// test, errs with probaility at most 2^(-s). CLR suggests s = 50 for
// any imaginable application, and s = 3 if we are trying to find
// large primes by applying miller_rabin to randomly chosen large
// integers. Even though we are doing the latter here, we will still
// choose s = 50. The probability of failure is at most
// 0.00000000000000088817, a pretty small number.
inline
bool
miller_rabin( const bigint& n )
{
  if ( n <= 2 )
    return false;

  if ( ! div_test( n ) )
    return false;

  char str[ STR_SIZE + 1 ];

  int s = 50;
  for ( int j = 1; j <= s; ++j ) {

    // Choose a random number.
    rand_bitstr( str, STR_SIZE );

    // Set a to the chosen number.
    bigint a = str;

    // Make sure that a is in [ 1, n - 1 ].
    a = ( a % ( n - 1 ) ) + 1;

    // Check to see if a is a witness.
    if ( witness( a, n ) )
      return false;  // n is definitely composite.
  }

  return true;   // n is almost surely prime.
}

// Return a randomly generated, large prime number using the
// Miller-Rabin primality test.
inline
bigint
find_prime( const bigint& r )
{
  char p_str[ HALF_STR_SIZE + 1 ];

  rand_bitstr( p_str, HALF_STR_SIZE );
  p_str[ HALF_STR_SIZE - 1 ] = '1';  // Force p to be an odd number.

  bigint p = p_str;

#ifdef DEBUG_SYSTEMC
  assert( ( p > 0 ) && ( p % 2 == 1 ) );
#endif

  // p is randomly determined. Now, we'll look for a prime in the
  // vicinity of p. By the prime number theorem, executing the
  // following loop approximately ln ( 2^NBITS ) iterations should
  // find a prime.

#ifdef DEBUG_SYSTEMC
  // A very large counter to check against infinite loops.
  sc_bigint<NBITS> niter = 0;
#endif

  while ( ! miller_rabin( p ) ) {
    p = ( p + 2 ) % r;

#ifdef DEBUG_SYSTEMC
    assert( ++niter > 0 );
#endif
  }

  return p;
}

// Encode or cipher the message in msg using the RSA public key P=( e, n ).
inline
bigint
cipher( const bigint& msg, const bigint& e, const bigint& n )
{
  return modular_exp( msg, e, n );
}

// Dencode or decipher the message in msg using the RSA secret key S=( d, n ).
inline
bigint
decipher( const bigint& msg, const bigint& d, const bigint& n )
{
  return modular_exp( msg, d, n );
}

// The RSA cipher.
inline
void
rsa( int seed )
{
  // Generate all 1's in r.
  char r_str[ HALF_STR_SIZE + 1 ];

  max_bitstr( r_str, HALF_STR_SIZE );
  bigint r = r_str;

#ifdef DEBUG_SYSTEMC
  assert( r > 0 );
#endif

  // Initialize the random number generator.
  cout << "\nRandom number generator seed = " << randomize( seed ) << endl;

  cout << endl;

  // Find two large primes p and q.
  bigint p = find_prime( r );
  bigint q = find_prime( r );

#ifdef DEBUG_SYSTEMC
  assert( ( p > 0 ) && ( q > 0 ) );
#endif

  // Compute n and ( p - 1 ) * ( q - 1 ) = m.
  bigint n = p * q;
  bigint m = ( p - 1 ) * ( q - 1 );

#ifdef DEBUG_SYSTEMC
  assert( ( n > 0 ) && ( m > 0 ) );
#endif
  // Find a small odd integer e that is relatively prime to m.
  bigint e = find_rel_prime( m );

#ifdef DEBUG_SYSTEMC
  assert( e > 0 );
#endif

  // Find the multiplicative inverse d of e, modulo m.
  bigint d = inverse( e, m );

#ifdef DEBUG_SYSTEMC
  assert( d > 0 );
#endif

  // Output public and secret keys.
  cout << "RSA public key P: P=( e, n )" << endl;
  cout << "e = " << e << endl;
  cout << "n = " << n << endl;
  cout << endl;

  cout << "RSA secret key S: S=( d, n )" << endl;
  cout << "d = " << d << endl;
  cout << "n = " << n << endl;
  cout << endl;

  // Cipher and decipher a randomly generated message msg.
  char msg_str[ STR_SIZE + 1 ];
  rand_bitstr( msg_str, STR_SIZE );
  bigint msg = msg_str;

  msg %= n; // Make sure msg is smaller than n. If larger, this part
            // will be a block of the input message.

#ifdef DEBUG_SYSTEMC
  assert( msg > 0 );
#endif

  cout << "Message to be ciphered = " << endl;
  cout << msg << endl;

  bigint msg2 = cipher( msg, e, n );
  cout << "\nCiphered message = " << endl;
  cout << msg2 << endl;

  msg2 = decipher( msg2, d, n );
  cout << "\nDeciphered message = " << endl;
  cout << msg2 << endl;

  // Make sure that the original message is recovered.
  if ( msg == msg2 ) {
    cout << "\nNote that the original message == the deciphered message, " << endl;
    cout << "showing that this algorithm and implementation work correctly.\n" << endl;
  }
  else {
    // This case is unlikely.
    cout << "\nNote that the original message != the deciphered message, " << endl;
    cout << "showing that this implementation works incorrectly.\n" << endl;
  }

  return;
}

int sc_main( int argc, char *argv[] )
{
  if ( argc <= 1 )
    rsa( -1 );
  else
    rsa( atoi( argv[ 1 ] ) );

  return 0;
}

// End of file


text:
package com.salesforce.keystone.coyote.rpc.server.protobuf;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.protobuf.Descriptors;
import com.google.protobuf.Message;
import com.salesforce.keystone.coyote.netty.ProtocolExceptions;
import com.salesforce.keystone.coyote.netty.handler.stream.NettyTrailerAccessor;
import com.salesforce.keystone.coyote.netty.roadrunner.NettyInboundRoadRunnerMessage;
import com.salesforce.keystone.coyote.protobuf.generated.RpcMessages;
import com.salesforce.keystone.coyote.rpc.exception.IncorrectServiceNameException;
import com.salesforce.keystone.coyote.rpc.protobuf.service.BlockingServiceAndTranslator;
import com.salesforce.keystone.coyote.rpc.protobuf.service.ProtobufServiceInitializer;
import com.salesforce.keystone.coyote.rpc.protobuf.service.ProtobufServiceTranslator;
import com.salesforce.keystone.coyote.rpc.protobuf.RoadRunnerMessageUtil;
import com.salesforce.keystone.coyote.rpc.protobuf.RpcRequestResponse;
import com.salesforce.keystone.coyote.rpc.protobuf.StreamCarryingRpcController;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;

/**
 * Handles delegating calls from a RPC request to an actual service implementation
 */
public class ProtobufServiceHandler extends
    SimpleChannelInboundHandler<NettyInboundRoadRunnerMessage> {

  private static final Log LOG = LogFactory.getLog(ProtobufServiceHandler.class);

  private final List<BlockingServiceAndTranslator> services;
  private final ListeningExecutorService pool;

  public ProtobufServiceHandler(ProtobufServiceInitializer initializer, ExecutorService pool) {
    this.pool = MoreExecutors.listeningDecorator(pool);
    this.services = initializer.getServices();
  }

  protected void channelRead0(final ChannelHandlerContext ctx,
      NettyInboundRoadRunnerMessage receivedMessage) throws Exception {
    final RpcMessages.Rpc rpc = RoadRunnerMessageUtil.unwrap(receivedMessage);

    // find the blocking service for the call
    String serviceName = rpc.getService();
    final BlockingServiceAndTranslator service = ProtobufServiceTranslator
        .getBlockingServiceAndTranslator(services, serviceName);
    if (service == null) {
      throw new IncorrectServiceNameException(serviceName);
    }

    // ensure that we can serve this method request
    if (!rpc.hasMethod()) {
      // Remote caller didn't send a method
      throw new ProtocolExceptions.MissingMethodException();
    }
    final Descriptors.MethodDescriptor md =
        service.getBlockingService().getDescriptorForType().findMethodByName(rpc.getMethod());
    if (md == null) {
      throw new ProtocolExceptions.NoHandlerForMethodException(rpc.getMethod());
    }

    // set the current request context. this only works because we assume the rpcs are
    // synchronous. once we have a client that will send multiple updates over the same channel
    // we need to be smarter when binding requests and responses
    RpcRequestResponse
        .setContextAttributes(rpc.getSequenceNumber(), rpc.getMessageId(), ctx);

    final StreamCarryingRpcController controller = new StreamCarryingRpcController(receivedMessage
        .getTrailerLen() == 0 ? null : new NettyTrailerAccessor(receivedMessage,
        receivedMessage.getChunkSize()));

    // get the request prototype from the service
    final Message request =
        service.getTranslator().translateRequest(rpc, service.getBlockingService(), md);

    // submit the request to the service and listen for the response
    ListenableFuture<RpcRequestResponse> response = pool.submit(
        new Callable<RpcRequestResponse>() {
          @Override
          public RpcRequestResponse call() throws Exception {
            // get the simple response
            Message response = service.getBlockingService().callBlockingMethod(
                md, controller, request);
            // wrap it into an rpc response that we can send
            return service.getTranslator().translate(md, response,
                controller);
          }
        });

    // listen for the result so we can handle it
    Futures.addCallback(response, new FutureCallback<RpcRequestResponse>() {

      public void onSuccess(RpcRequestResponse response) {
        response.setAttributesFromContext(ctx);
        // pass it along the channel
        ctx.write(response, ctx.voidPromise());
      }

      public void onFailure(Throwable thrown) {
        LOG.debug("Got an error while handling rpc response, passing onto channel handlers!",
            thrown);
        ctx.fireExceptionCaught(thrown);
      }

    });
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false"
android:zAdjustment="top">

<translate
    android:duration="200"
    android:fromXDelta="100.0%p"
    android:toXDelta="0.0" />
</set>


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Diagnostics.EngineV1;
using Microsoft.CodeAnalysis.Editor.Shared.Tagging;
using Microsoft.CodeAnalysis.Editor.Shared.Threading;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Tagging;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics
{
    internal abstract partial class AbstractAggregatedDiagnosticsTagSource<TTag> : TagSource<TTag> where TTag : ITag
    {
        private class DiagnosticsTagSource
        {
            private readonly AbstractAggregatedDiagnosticsTagSource<TTag> _owner;
            private readonly object _id;

            private readonly AsynchronousSerialWorkQueue _workQueue;

            private IntervalTree<Data> _lastDiagnostics;

            public DiagnosticsTagSource(AbstractAggregatedDiagnosticsTagSource<TTag> owner, object id)
            {
                _owner = owner;
                _id = id;

                _workQueue = new AsynchronousSerialWorkQueue(_owner.Listener);
                _lastDiagnostics = IntervalTree<Data>.Empty;
            }

            public void Shutdown()
            {
                _workQueue.CancelCurrentWork();

                ClearExistingTags();
            }

            public void OnDiagnosticsUpdated(DiagnosticsUpdatedArgs e, SourceText text, ITextSnapshot snapshot, int delay)
            {
                // cancel pending work
                _workQueue.CancelCurrentWork();

                // enqueue new work
                var cancellationToken = _workQueue.CancellationToken;
                _workQueue.EnqueueBackgroundWork(() => RecomputeTagsBackground(e, text, snapshot, cancellationToken), "RecomputeTagsBackground", delay, cancellationToken);
            }

            private void RecomputeTagsBackground(DiagnosticsUpdatedArgs e, SourceText text, ITextSnapshot snapshot, CancellationToken cancellationToken)
            {
                Contract.ThrowIfNull(e.Solution);

                cancellationToken.ThrowIfCancellationRequested();

                // no diagnostics
                if (e.Diagnostics.IsEmpty)
                {
                    ClearExistingTags(snapshot);
                    return;
                }

                // e.Diagnostics is unordered list and the list could contains overlapping elements
                var diagnostics = GetAugmentedDiagnostics(e.Diagnostics, text, snapshot);

                var introspector = new IntervalIntrospector(snapshot);
                var newTree = IntervalTree.Create(introspector, diagnostics);

                // new diagnostics
                if (_lastDiagnostics.IsEmpty())
                {
                    _lastDiagnostics = newTree;
                    RaiseTagsChanged(newTree, snapshot);
                    return;
                }

                // diagnostics changed
                var oldTree = _lastDiagnostics;
                _lastDiagnostics = newTree;

                var spans = new NormalizedSnapshotSpanCollection(Difference(newTree, oldTree, new DiffSpanComparer(snapshot, _owner.MinimumLength)));
                if (spans.Count == 0)
                {
                    // no changes
                    return;
                }

                _owner.RaiseTagsChanged(snapshot.TextBuffer, spans);
            }

            public void AppendIntersectingSpans(int start, int length, IntervalIntrospector introspector, List<ITagSpan<TTag>> list)
            {
                if (_owner.SubjectBuffer != introspector.Snapshot.TextBuffer)
                {
                    // in venus case, buffer comes and goes and tag source might hold onto diagnostics that belong to
                    // old/new buffers which are different than current subject buffer.
                    return;
                }

                var result = _lastDiagnostics.GetIntersectingInOrderIntervals(start, length, introspector);
                if (result.Count == 0)
                {
                    return;
                }

                // only follow minimum length for live diagnostic. otherwise, let it be zero length.
                var minimumLength = _id is ISupportLiveUpdate ? _owner.MinimumLength : 0;

                foreach (var data in result)
                {
                    var span = data.GetSnapshotSpan(introspector.Snapshot, minimumLength);
                    if (span.Length == 0)
                    {
                        continue;
                    }

                    list.Add(_owner.CreateTagSpan(span, data.Diagnostic));
                }
            }

            private void ClearExistingTags(ITextSnapshot snapshot = null)
            {
                var local = _lastDiagnostics;
                _lastDiagnostics = IntervalTree<Data>.Empty;

                if (local.IsEmpty())
                {
                    return;
                }

                snapshot = snapshot ?? local.First().TrackingSpan.TextBuffer.CurrentSnapshot;
                RaiseTagsChanged(local, snapshot);
            }

            private void RaiseTagsChanged(IntervalTree<Data> tree, ITextSnapshot snapshot)
            {
                if (_owner.SubjectBuffer != snapshot.TextBuffer)
                {
                    return;
                }

                var spans = new NormalizedSnapshotSpanCollection(tree.Select(d => d.GetSnapshotSpan(snapshot, _owner.MinimumLength)));
                if (spans.Count == 0)
                {
                    return;
                }

                _owner.RaiseTagsChanged(snapshot.TextBuffer, spans);
            }

            private IEnumerable<Data> GetAugmentedDiagnostics(ImmutableArray<DiagnosticData> diagnostics, SourceText text, ITextSnapshot snapshot)
            {
                return diagnostics.Where(_owner.ShouldInclude)
                                  .Select(d => new Data(d, snapshot.CreateTrackingSpan(AdjustSpanRange(text, d.GetExistingOrCalculatedTextSpan(text)), SpanTrackingMode.EdgeExclusive)));
            }

            private static Span AdjustSpanRange(SourceText text, TextSpan span)
            {
                // make sure given span is within the range of given text. diagnostic from other source than live analyzer can have
                // range outside of the given text since those doesn't have a way to track versions properly
                return Span.FromBounds(Math.Min(Math.Max(span.Start, 0), text.Length), Math.Min(Math.Max(span.End, 0), text.Length));
            }

            public class DiffSpanComparer : IDiffSpanComparer<Data>
            {
                private readonly int _minimumLength;
                private readonly ITextSnapshot _snapshot;

                public DiffSpanComparer(ITextSnapshot snapshot, int minimumLength)
                {
                    _snapshot = snapshot;
                    _minimumLength = minimumLength;
                }

                public bool IsDefault(Data data)
                {
                    return data.IsDefault;
                }

                public bool Equals(Data data1, Data data2)
                {
                    return data1.Diagnostic.Id == data2.Diagnostic.Id && data1.Diagnostic.Severity == data2.Diagnostic.Severity;
                }

                public SnapshotSpan GetSpan(Data data)
                {
                    if (data.TrackingSpan.TextBuffer != _snapshot.TextBuffer)
                    {
                        // when two different buffers are compared, we make whole buffer as changed.
                        return new SnapshotSpan(_snapshot, 0, _snapshot.Length);
                    }

                    return data.GetSnapshotSpan(_snapshot, _minimumLength);
                }
            }
        }
    }
}


text:
'use strict';
var gutil = require('gulp-util');
var through = require('through2');
var revHash = require('rev-hash');
var imageinfo = require('imageinfo');
var modifyFilename = require('modify-filename');

function transformFilename(file, opts) {
  var hash = revHash(file.contents);
  var ret_path = "";
  file.path = modifyFilename(file.path, function(filename, ext) {
    if (opts.showName == true) {
      ret_path += filename;
    }
    if (opts.showSize == true) {
      var info = imageinfo(file.contents);
      var size = parseInt(file.contents.length / 1024, 10);
      ret_path += "_" + info.width + "x" + info.height + "_" + size;
    }
    if (opts.showHash == true) {
      ret_path += "_" + hash;
    }
    if (ret_path.length === 0) {
      ret_path = filename;
    }
    return ret_path + ext;
  });
}
;

var plugin = function(opts) {
  opts = opts || {};
  return through.obj(function(file, enc, cb) {
    if (file.isNull()) {
      cb(null, file);
      return;
    }
    if (file.isStream()) {
      cb(new gutil.PluginError('gulp-rev', 'Streaming not supported'));
      return;
    }
    transformFilename(file, opts);
    cb(null, file);
  }, function(cb) {
    cb();
  });
};

module.exports = plugin;


text:
/* jslint node: true */
'use strict';

var marked = require('marked');

function markdownParser(md) {

  if (md instanceof Array) {
    for (var i = 0; i < md.length; i++) {
      md[i].abstract = marked(md[i].abstract);
    }
  } else if (md instanceof Object) {
    md.content = marked(md.content);
  }

  return md;
}

module.exports = markdownParser;


text:
var CapabilitiesShowCapabilitiesRoute = Ember.Route.extend({
    model:function(params) {
        return this.modelFor('project').get('capabilities');
    },

    serialize: function(model, params) {
        console.log("params: " + params);
        return { component_id: model.get('component_id'), attribute_id: model.get('attribute_id') };
    }
});

export default CapabilitiesShowCapabilitiesRoute;


text:
var interval = 1000;
window.setInterval(function(){
	$("[class^=endProduct]").each(function(){
		var dom = $(this);
		var endDate=new Date(dom.val());
		var now = new Date();
		var leftTime = endDate.getTime()-now.getTime();
		if(leftTime < 0){
			$(dom).parent().addClass("open_mask");
			$(dom).parent().find(".round_spread").attr("href","javascript://");
			if(!$(dom).parent().find(".mask_jjks_ex").length){
				$(dom).parent().append('

');
			}
			return;
		}
	});
}, interval);

window.setInterval(function(){
	$("[class^=startProduct]").each(function(){
		var dom = $(this);
		var startDate=new Date(dom.val());
		var now = new Date();
		var leftTime = startDate.getTime()-now.getTime();
		var leftsecond = parseInt(leftTime/1000);
		var day = Math.floor(leftsecond/(60*60*24));
		var hour = Math.floor((leftsecond-day*24*60*60)/3600);
		var minute = Math.floor((leftsecond-day*24*60*60-hour*3600)/60);
		var second = Math.floor(leftsecond-day*24*60*60-hour*3600-minute*60);
		hour = day > 0 ? hour + day * 24 : hour;
		hour = hour < 10 ? "0" + hour : hour;
		minute = minute < 10 ? "0" + minute : minute;
		second = second < 10 ? "0" + second : second;
		if(hour == "00" && minute == "00" && second == "00"){
			$(dom).parent().removeClass("open_mask");
			$(dom).parent().find(".round_spread").attr("href","/experienceProduct/fqueryExperienceProduct.htm?productId="+ dom.attr("class").split("_")[1]);
		}
	});
}, interval);


text:
package com.interview.linklist;

/**
 * Find if there is loop in linklist
 * Test cases
 * 0, 1 or more elements in linklist
 * even or odd size loops
 * @author tusroy
 */
public class LoopInLinkList {

    public boolean loopExists(Node head){
        if(head == null){
            return false;
        }
        Node slow = head;
        Node fast = head.next;
        while(slow != fast && fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }

        if(slow == fast){
            return true;
        }
        else{
            return false;
        }
    }

    public static void main(String args[]){
        LinkList ll = new LinkList();
        Node head = null;
        head = ll.addNode(1, head);
        head = ll.addNode(2, head);
        head = ll.addNode(3, head);
        head = ll.addNode(4, head);
        head = ll.addNode(5, head);
        head = ll.addNode(6, head);
        head = ll.addNode(7, head);
        head = ll.addNode(8, head);
        Node node1 = ll.find(head, 8);
        Node node2 = ll.find(head, 4);
        node1.next = node2;
        LoopInLinkList lll = new LoopInLinkList();
        System.out.println(lll.loopExists(head));

        node2.next = null;
        System.out.println(lll.loopExists(head));

        node1 = ll.find(head, 3);
        node2.next = node1;
        System.out.println(lll.loopExists(head));
    }
}


text:
As a user, I can have my spare time automatically managed
           I can add activities to be scheduled
           I can reschedule things and let the system figure out the rest

Models:

User
  has_many activities
  can register/login
  links with google

Activity
  A user created activity, to have occurrences scheduled
  belongs_to user
  has_many occurences

Occurence
  A scheduled activity, to be managed by the system

Services:
  ScheduleActivities
  FetchCalendar
  PushCalendar

Workflow for scheduling:
  Fetch the user's google calendar
  For a given week
    Create a number of timeblocks from the user's activities
    Fit them into the calendar (?)
    Schedule the occurences in the user's calendar
    Persist the occurences


text:
package org.pentaho.di.www;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.CopyOnWriteArrayList;

import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.vfs2.FileObject;
import org.pentaho.di.cluster.SlaveServer;
import org.pentaho.di.core.KettleClientEnvironment;
import org.pentaho.di.core.KettleEnvironment;
import org.pentaho.di.core.logging.KettleLogStore;
import org.pentaho.di.core.logging.LogChannel;
import org.pentaho.di.core.logging.LogChannelInterface;
import org.pentaho.di.core.util.EnvUtil;
import org.pentaho.di.core.util.Utils;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.i18n.BaseMessages;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
import com.sun.jersey.api.json.JSONConfiguration;

public class Carte {
  private static Class<?> PKG = Carte.class; // for i18n purposes, needed by Translator2!!

  private WebServer webServer;
  private SlaveServerConfig config;
  private boolean allOK;
  private static Options options;

  public Carte( final SlaveServerConfig config ) throws Exception {
    this( config, null );
  }

  public Carte( final SlaveServerConfig config, Boolean joinOverride ) throws Exception {
    this.config = config;

    allOK = true;

    CarteSingleton.setSlaveServerConfig( config );
    LogChannelInterface log = CarteSingleton.getInstance().getLog();

    final TransformationMap transformationMap = CarteSingleton.getInstance().getTransformationMap();
    transformationMap.setSlaveServerConfig( config );
    final JobMap jobMap = CarteSingleton.getInstance().getJobMap();
    jobMap.setSlaveServerConfig( config );
    List<SlaveServerDetection> detections = new CopyOnWriteArrayList<SlaveServerDetection>();
    SocketRepository socketRepository = CarteSingleton.getInstance().getSocketRepository();

    SlaveServer slaveServer = config.getSlaveServer();

    String hostname = slaveServer.getHostname();
    int port = WebServer.PORT;
    if ( !Utils.isEmpty( slaveServer.getPort() ) ) {
      try {
        port = Integer.parseInt( slaveServer.getPort() );
      } catch ( Exception e ) {
        log.logError( BaseMessages.getString( PKG, "Carte.Error.CanNotPartPort", slaveServer.getHostname(), "" + port ),
            e );
        allOK = false;
      }
    }

    // TODO: see if we need to keep doing this on a periodic basis.
    // The master might be dead or not alive yet at the time we send this message.
    // Repeating the registration over and over every few minutes might harden this sort of problems.
    //
    Properties masterProperties = null;
    if ( config.isReportingToMasters() ) {
      String propertiesMaster = slaveServer.getPropertiesMasterName();
      for ( final SlaveServer master : config.getMasters() ) {
        // Here we use the username/password specified in the slave server section of the configuration.
        // This doesn't have to be the same pair as the one used on the master!
        //
        try {
          SlaveServerDetection slaveServerDetection = new SlaveServerDetection( slaveServer.getClient() );
          master.sendXML( slaveServerDetection.getXML(), RegisterSlaveServlet.CONTEXT_PATH + "/" );
          log.logBasic( "Registered this slave server to master slave server [" + master.toString() + "] on address ["
              + master.getServerAndPort() + "]" );
        } catch ( Exception e ) {
          log.logError( "Unable to register to master slave server [" + master.toString() + "] on address [" + master
              .getServerAndPort() + "]" );
          allOK = false;
        }
        try {
          if ( !StringUtils.isBlank( propertiesMaster ) && propertiesMaster.equalsIgnoreCase( master.getName() ) ) {
            if ( masterProperties != null ) {
              log.logError( "More than one primary master server. Master name is " + propertiesMaster );
            } else {
              masterProperties = master.getKettleProperties();
              log.logBasic( "Got properties from master server [" + master.toString() + "], address [" + master
                  .getServerAndPort() + "]" );
            }
          }
        } catch ( Exception e ) {
          log.logError( "Unable to get properties from master server [" + master.toString() + "], address [" + master
              .getServerAndPort() + "]" );
          allOK = false;
        }
      }
    }
    if ( masterProperties != null ) {
      EnvUtil.applyKettleProperties( masterProperties, slaveServer.isOverrideExistingProperties() );
    }

    // If we need to time out finished or idle objects, we should create a timer in the background to clean
    // this is done automatically now
    // CarteSingleton.installPurgeTimer(config, log, transformationMap, jobMap);

    if ( allOK ) {
      boolean shouldJoin = config.isJoining();
      if ( joinOverride != null ) {
        shouldJoin = joinOverride;
      }

      this.webServer =
          new WebServer( log, transformationMap, jobMap, socketRepository, detections, hostname, port, shouldJoin,
              config.getPasswordFile(), slaveServer.getSslConfig() );
    }
  }

  public static void main( String[] args ) {
    try {
      parseAndRunCommand( args );
    } catch ( Exception e ) {
      e.printStackTrace();
    }
  }

  @SuppressWarnings( "static-access" )
  private static void parseAndRunCommand( String[] args ) throws Exception {
    options = new Options();
    options.addOption( OptionBuilder.withLongOpt( "stop" ).withDescription( BaseMessages.getString( PKG,
        "Carte.ParamDescription.stop" ) ).hasArg( false ).isRequired( false ).create( 's' ) );
    options.addOption( OptionBuilder.withLongOpt( "userName" ).withDescription( BaseMessages.getString( PKG,
        "Carte.ParamDescription.userName" ) ).hasArg( true ).isRequired( false ).create( 'u' ) );
    options.addOption( OptionBuilder.withLongOpt( "password" ).withDescription( BaseMessages.getString( PKG,
        "Carte.ParamDescription.password" ) ).hasArg( true ).isRequired( false ).create( 'p' ) );
    options.addOption( OptionBuilder.withLongOpt( "help" ).withDescription( BaseMessages.getString( PKG,
        "Carte.ParamDescription.help" ) ).create( 'h' ) );

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse( options, args );

    if ( cmd.hasOption( 'h' ) ) {
      displayHelpAndAbort();
    }

    String[] arguments = cmd.getArgs();
    boolean usingConfigFile = false;

    // Load from an xml file that describes the complete configuration...
    //
    SlaveServerConfig config = null;
    if ( arguments.length == 1 && !Utils.isEmpty( arguments[0] ) ) {
      if ( cmd.hasOption( 's' ) ) {
        throw new Carte.CarteCommandException( BaseMessages.getString( PKG, "Carte.Error.illegalStop" ) );
      }
      usingConfigFile = true;
      FileObject file = KettleVFS.getFileObject( arguments[0] );
      Document document = XMLHandler.loadXMLFile( file );
      setKettleEnvironment(); // Must stand up server now to allow decryption of password
      Node configNode = XMLHandler.getSubNode( document, SlaveServerConfig.XML_TAG );
      config = new SlaveServerConfig( new LogChannel( "Slave server config" ), configNode );
      if ( config.getAutoSequence() != null ) {
        config.readAutoSequences();
      }
      config.setFilename( arguments[0] );
    }
    if ( arguments.length == 2 && !Utils.isEmpty( arguments[0] ) && !Utils.isEmpty( arguments[1] ) ) {
      String hostname = arguments[0];
      String port = arguments[1];

      if ( cmd.hasOption( 's' ) ) {
        String user = cmd.getOptionValue( 'u' );
        String password = cmd.getOptionValue( 'p' );
        shutdown( hostname, port, user, password );
        System.exit( 0 );
      }

      SlaveServer slaveServer = new SlaveServer( hostname + ":" + port, hostname, port, null, null );

      config = new SlaveServerConfig();
      config.setSlaveServer( slaveServer );
    }

    // Nothing configured: show the usage
    //
    if ( config == null ) {
      displayHelpAndAbort();
    }

    if ( !usingConfigFile ) {
      setKettleEnvironment();
    }
    runCarte( config );
  }

  private static void setKettleEnvironment() throws Exception {
    KettleClientEnvironment.getInstance().setClient( KettleClientEnvironment.ClientType.CARTE );
    KettleEnvironment.init();
  }

  public static void runCarte( SlaveServerConfig config ) throws Exception {
    KettleLogStore.init( config.getMaxLogLines(), config.getMaxLogTimeoutMinutes() );

    config.setJoining( true );

    Carte carte = new Carte( config, false );
    CarteSingleton.setCarte( carte );

    carte.getWebServer().join();
  }

  /**
   * @return the webServer
   */
  public WebServer getWebServer() {
    return webServer;
  }

  /**
   * @param webServer
   *          the webServer to set
   */
  public void setWebServer( WebServer webServer ) {
    this.webServer = webServer;
  }

  /**
   * @return the slave server (Carte) configuration
   */
  public SlaveServerConfig getConfig() {
    return config;
  }

  /**
   * @param config
   *          the slave server (Carte) configuration
   */
  public void setConfig( SlaveServerConfig config ) {
    this.config = config;
  }

  private static void displayHelpAndAbort() {
    HelpFormatter formatter = new HelpFormatter();
    String optionsHelp = getOptionsHelpForUsage();
    String header =
        BaseMessages.getString( PKG, "Carte.Usage.Text" ) + optionsHelp + "\nor\n" + BaseMessages.getString( PKG,
            "Carte.Usage.Text2" ) + "\n\n" + BaseMessages.getString( PKG, "Carte.MainDescription" );

    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter( stringWriter );
    formatter.printHelp( printWriter, 80, "CarteDummy", header, options, 5, 5, "", false );
    System.err.println( stripOff( stringWriter.toString(), "usage: CarteDummy" ) );

    System.err.println( BaseMessages.getString( PKG, "Carte.Usage.Example" ) + ": Carte 127.0.0.1 8080" );
    System.err.println( BaseMessages.getString( PKG, "Carte.Usage.Example" ) + ": Carte 192.168.1.221 8081" );
    System.err.println();
    System.err.println( BaseMessages.getString( PKG, "Carte.Usage.Example" ) + ": Carte /foo/bar/carte-config.xml" );
    System.err.println( BaseMessages.getString( PKG, "Carte.Usage.Example" )
        + ": Carte http://www.example.com/carte-config.xml" );
    System.err.println( BaseMessages.getString( PKG, "Carte.Usage.Example" )
        + ": Carte 127.0.0.1 8080 -s -u cluster -p cluster" );

    System.exit( 1 );
  }

  private static String getOptionsHelpForUsage() {
    HelpFormatter formatter = new HelpFormatter();
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter( stringWriter );
    formatter.printUsage( printWriter, 999, "", options );
    return stripOff( stringWriter.toString(), "usage: " ); // Strip off the "usage:" so it can be localized
  }

  private static String stripOff( String target, String strip ) {
    return target.substring( target.indexOf( strip ) + strip.length() );
  }

  private static void shutdown( String hostname, String port, String username, String password ) {
    try {
      callStopCarteRestService( hostname, port, username, password );
    } catch ( Exception e ) {
      e.printStackTrace();
    }
  }

  /**
   * Checks that Carte is running and if so, shuts down the Carte server
   *
   * @param hostname
   * @param port
   * @param username
   * @param password
   * @throws ParseException
   * @throws CarteCommandException
   */
  private static void callStopCarteRestService( String hostname, String port, String username, String password )
    throws ParseException, CarteCommandException {
    // get information about the remote connection
    try {
      ClientConfig clientConfig = new DefaultClientConfig();
      clientConfig.getFeatures().put( JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE );
      Client client = Client.create( clientConfig );
      client.addFilter( new HTTPBasicAuthFilter( username, password ) );

      // check if the user can access the carte server. Don't really need this call but may want to check it's output at
      // some point
      String contextURL = "http://" + hostname + ":" + port + "/kettle";
      WebResource resource = client.resource( contextURL + "/status/?xml=Y" );
      String response = resource.get( String.class );
      if ( response == null || !response.contains( "<serverstatus>" ) ) {
        throw new Carte.CarteCommandException( BaseMessages.getString( PKG, "Carte.Error.NoServerFound", hostname, ""
            + port ) );
      }

      // This is the call that matters
      resource = client.resource( contextURL + "/stopCarte" );
      response = resource.get( String.class );
      if ( response == null || !response.contains( "Shutting Down" ) ) {
        throw new Carte.CarteCommandException( BaseMessages.getString( PKG, "Carte.Error.NoShutdown", hostname, ""
            + port ) );
      }
    } catch ( Exception e ) {
      throw new Carte.CarteCommandException( BaseMessages.getString( PKG, "Carte.Error.NoServerFound", hostname, ""
          + port ), e );
    }
  }

  /**
   * Exception generated when command line fails
   */
  public static class CarteCommandException extends Exception {
    private static final long serialVersionUID = 1L;

    public CarteCommandException() {
    }

    public CarteCommandException( final String message ) {
      super( message );
    }

    public CarteCommandException( final String message, final Throwable cause ) {
      super( message, cause );
    }

    public CarteCommandException( final Throwable cause ) {
      super( cause );
    }
  }
}


text:
(function () {
    'use strict';

    angular
        .module('predictionsApp')
        .controller('MenuController', MenuController);

    MenuController.$inject = ['$location'];

    function MenuController($location) {
        var vm = this;
        vm.is_active = function (path_root) {
            return path_root === $location.path().substr(1, path_root.length);
        };
    }

}());


text:
// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0.
// See LICENSE.txt in the project root for complete license information.

// Allows for executing a program with command-line arguments and reading the result
interface IExec {
    exec: (filename: string, cmdLineArgs: string[], handleResult: (ExecResult) => void) => void;
}

declare var require;

class ExecResult {
    public stdout = "";
    public stderr = "";
    public exitCode: number;
}

class WindowsScriptHostExec implements IExec {
    public exec(filename: string, cmdLineArgs: string[], handleResult: (ExecResult) => void) : void {
        var result = new ExecResult();
        var shell = new ActiveXObject('WScript.Shell');
        try {
            var process = shell.Exec(filename + ' ' + cmdLineArgs.join(' '));
        } catch(e) {
            result.stderr = e.message;
            result.exitCode = 1
            handleResult(result);
            return;
        }
        // Wait for it to finish running
        while (process.Status != 0) { /* todo: sleep? */ }

        result.exitCode = process.ExitCode;
        if(!process.StdOut.AtEndOfStream) result.stdout = process.StdOut.ReadAll();
        if(!process.StdErr.AtEndOfStream) result.stderr = process.StdErr.ReadAll();

        handleResult(result);
    }
}

class NodeExec implements IExec {
    public exec(filename: string, cmdLineArgs: string[], handleResult: (ExecResult) => void) : void {
        var nodeExec = require('child_process').exec;

        var result = new ExecResult();
        result.exitCode = null;
        var cmdLine = filename + ' ' + cmdLineArgs.join(' ');
        var process = nodeExec(cmdLine, function(error, stdout, stderr) {
            result.stdout = stdout;
            result.stderr = stderr;
            result.exitCode = error ? error.code : 0;
            handleResult(result);
        });
    }
}

var Exec: IExec = function() : IExec {
    var global = <any>Function("return this;").call(null);
    if(typeof global.ActiveXObject !== "undefined") {
        return new WindowsScriptHostExec();
    } else {
        return new NodeExec();
    }
}();


text:
using namespace arangodb;
using namespace arangodb::traverser;
using namespace arangodb::graph;

bool Traverser::VertexGetter::getVertex(VPackSlice edge, std::vector<StringRef>& result) {
  VPackSlice res = edge;
  if (!res.isString()) {
    res = transaction::helpers::extractFromFromDocument(edge);
    if (result.back() == StringRef(res)) {
      res = transaction::helpers::extractToFromDocument(edge);
    }
    TRI_ASSERT(res.isString());
  }

  if (!_traverser->vertexMatchesConditions(res, result.size())) {
    return false;
  }
  result.emplace_back(_traverser->traverserCache()->persistString(StringRef(res)));
  return true;
}

bool Traverser::VertexGetter::getSingleVertex(arangodb::velocypack::Slice edge, StringRef cmp,
                                              uint64_t depth, StringRef& result) {
  VPackSlice resSlice = edge;
  if (!resSlice.isString()) {
    VPackSlice from = transaction::helpers::extractFromFromDocument(edge);
    if (from.compareString(cmp.data(), cmp.length()) != 0) {
      resSlice = from;
    } else {
      resSlice = transaction::helpers::extractToFromDocument(edge);
    }
    TRI_ASSERT(resSlice.isString());
  }
  result = _traverser->traverserCache()->persistString(StringRef(resSlice));
  return _traverser->vertexMatchesConditions(resSlice, depth);
}

void Traverser::VertexGetter::reset(StringRef const&) {
}

bool Traverser::UniqueVertexGetter::getVertex(VPackSlice edge, std::vector<StringRef>& result) {
  VPackSlice toAdd = edge;
  if (!toAdd.isString()) {
    toAdd = transaction::helpers::extractFromFromDocument(edge);
    StringRef const& cmp = result.back();
    TRI_ASSERT(toAdd.isString());
    if (cmp == StringRef(toAdd)) {
      toAdd = transaction::helpers::extractToFromDocument(edge);
    }
    TRI_ASSERT(toAdd.isString());
  }

  StringRef toAddStr = _traverser->traverserCache()->persistString(StringRef(toAdd));
  // First check if we visited it. If not, then mark
  if (_returnedVertices.find(toAddStr) != _returnedVertices.end()) {
    // This vertex is not unique.
    _traverser->traverserCache()->increaseFilterCounter();
    return false;
  } else {
    _returnedVertices.emplace(toAddStr);
  }

  if (!_traverser->vertexMatchesConditions(toAdd, result.size())) {
    return false;
  }

  result.emplace_back(toAddStr);
  return true;
}

bool Traverser::UniqueVertexGetter::getSingleVertex(arangodb::velocypack::Slice edge, StringRef cmp,
                                              uint64_t depth, StringRef& result) {
  VPackSlice resSlice = edge;
  if (!resSlice.isString()) {
    resSlice = transaction::helpers::extractFromFromDocument(edge);
    if (resSlice.compareString(cmp.data(), cmp.length()) == 0) {
      resSlice = transaction::helpers::extractToFromDocument(edge);
    }
    TRI_ASSERT(resSlice.isString());
  }

  result = _traverser->traverserCache()->persistString(StringRef(resSlice));
  // First check if we visited it. If not, then mark
  if (_returnedVertices.find(result) != _returnedVertices.end()) {
    // This vertex is not unique.
    _traverser->traverserCache()->increaseFilterCounter();
    return false;
  } else {
    _returnedVertices.emplace(result);
  }
  return _traverser->vertexMatchesConditions(resSlice, depth);
}

void Traverser::UniqueVertexGetter::reset(arangodb::StringRef const& startVertex) {
  _returnedVertices.clear();
  // The startVertex always counts as visited!
  _returnedVertices.emplace(startVertex);
}

Traverser::Traverser(arangodb::traverser::TraverserOptions* opts,
                     transaction::Methods* trx,
                     arangodb::ManagedDocumentResult* mmdr)
    : _trx(trx),
      _mmdr(mmdr),
      _startIdBuilder(trx),
      _pruneNext(false),
      _done(true),
      _opts(opts),
      _canUseOptimizedNeighbors(false) {
  if (opts->uniqueVertices == TraverserOptions::UniquenessLevel::GLOBAL) {
    _vertexGetter = std::make_unique<UniqueVertexGetter>(this);
  } else {
    _vertexGetter = std::make_unique<VertexGetter>(this);
  }
}

Traverser::~Traverser() {}

bool arangodb::traverser::Traverser::edgeMatchesConditions(VPackSlice e,
                                                           StringRef vid,
                                                           uint64_t depth,
                                                           size_t cursorId) {
  if (!_opts->evaluateEdgeExpression(e, vid, depth, cursorId)) {
    return false;
  }
  return true;
}

bool arangodb::traverser::Traverser::vertexMatchesConditions(VPackSlice v, uint64_t depth) {
  TRI_ASSERT(v.isString());
  if (_opts->vertexHasFilter(depth)) {
    // We always need to destroy this vertex
    aql::AqlValue vertex = fetchVertexData(StringRef(v));
    if (!_opts->evaluateVertexExpression(vertex.slice(), depth)) {
      vertex.destroy();
      return false;
    }
    vertex.destroy();
  }
  return true;
}

bool arangodb::traverser::Traverser::next() {
  TRI_ASSERT(!_done);
  bool res = _enumerator->next();
  if (!res) {
    _done = true;
  }
  return res;
}

TraverserCache* arangodb::traverser::Traverser::traverserCache() {
  return _opts->cache();
}

arangodb::aql::AqlValue arangodb::traverser::Traverser::lastVertexToAqlValue() {
  return _enumerator->lastVertexToAqlValue();
}

arangodb::aql::AqlValue arangodb::traverser::Traverser::lastEdgeToAqlValue() {
  return _enumerator->lastEdgeToAqlValue();
}

arangodb::aql::AqlValue arangodb::traverser::Traverser::pathToAqlValue(
    VPackBuilder& builder) {
  return _enumerator->pathToAqlValue(builder);
}

size_t arangodb::traverser::Traverser::getAndResetReadDocuments() {
  return traverserCache()->getAndResetInsertedDocuments();
}

size_t arangodb::traverser::Traverser::getAndResetFilteredPaths() {
  return traverserCache()->getAndResetFilteredDocuments();
}

void arangodb::traverser::Traverser::allowOptimizedNeighbors() {
  _canUseOptimizedNeighbors = true;
}