text:
'use strict';

let express = require('express');
let app = express();
let server = require('http').Server(app);
let io = require('socket.io')(server);
let Client = require('./models/Client');

let port = process.env.PORT || 3000;
let loginWord = "woord1";
let loginWord2 = "woord2";

let clients = [];
let socketid;
let arrayMetKeys = [];

let mobileSocketIdInServer;
let desktopSocketIdInServer;

app.use(express.static(__dirname + '/public'));

io.on('connection', socket => {
  socketid = socket.id;
  socket.emit("socketid",socket.id);

  ////////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////
  //////////////////////////UPDATES PLAYERS///////////////////////////
  ////////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////

  socket.on('particles', (playerX, playerY, playerID, desktopID) => {
    // console.log('player ' + playerID);
    // console.log('player sends particles x ' + playerX);
    // console.log('player sends particles x ' + playerY);
    socket.broadcast.emit('sendParticlesToEveryone', playerX, playerY, playerID, desktopID);
  });

  socket.on('yPosDown', (playerposY, playerId) => {
    //console.log('dooooown' + playerposY + ' player id: ' + playerId);
    socket.broadcast.emit('yPosDownAllPlayers', playerposY, playerId);
    socket.broadcast.to(playerId).emit('youPos', playerposY);
  });

  socket.on('yPosUp', (playerposY, playerId) => {
    //console.log('uuuup' + playerposY + ' player id: ' + playerId);
    socket.broadcast.emit('yPosUpAllPlayers', playerposY, playerId);
  });

  socket.on('gameover', playerId => {
    console.log('Game Over' + playerId);
    //socket.broadcast.emit('gameoverplayer', playerId);
    socket.broadcast.to(playerId).emit('gameoverplayer', playerId);
  });

  ////////////////////////////////////////////////////////////////////
  //////////////////////////////BUTTONS///////////////////////////////
  ////////////////////////////////////////////////////////////////////

  socket.on('downhillFast', (socketidDownhill, socketIdDesktopDownHill) => {
    socket.broadcast.emit('downHill', socketidDownhill, socketIdDesktopDownHill);
  });

  socket.on('disturb', (sockIdDisturb, socketDesktopID) => {
    socket.broadcast.emit('disturbToAll', sockIdDisturb, socketDesktopID);
  });

  socket.on('flipview', (sockIdChangeView, socketDesktopID) => {
    //console.log(socketidDownhill);
    io.sockets.emit('changeCameraViewToAll', sockIdChangeView, socketDesktopID);
  });

  socket.on('blackout', (sockIdBlackout, socketDesktopID) => {
    //console.log(socketidDownhill);
    socket.broadcast.emit('blackoutToAll', sockIdBlackout, socketDesktopID);
  });

  ////////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////
  ////////////////////////DESKTOP OF MOBILE///////////////////////////
  ////////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////

  socket.on('ditIsDesktopSocket', (key, socketidDesktop) => {
    loginWord = key;
    desktopSocketIdInServer = socketidDesktop;

    //arrayMetKeys.push(key);
    arrayMetKeys.push({id: desktopSocketIdInServer, key: loginWord});
  });

  socket.on('ditIsMobileSocket', (key, socketidMobile, color) => {
    mobileSocketIdInServer = socketidMobile;

    if (arrayMetKeys !== []) {
      arrayMetKeys.forEach(function(code) {
        if (code.key === key){

          console.log("dit is mobile met id " + mobileSocketIdInServer + " and connected to desktop id " + code.id);
          socket.emit("schermwegdoen", code.id);
          let client  = new Client(mobileSocketIdInServer, code.id, color);

          socket.broadcast.to(code.id).emit('thisIsANewSpeler', client);
          //console.log("client to yourself " + client.socketidMobile);

          arrayMetKeys.splice(arrayMetKeys.indexOf(code), 1);

          //console.log("client to everyone " + client.socketidMobile);
          //console.log("desktop to everyone " + client.socketidDesktop);

          io.sockets.emit('newplayer', client);

        }else{
          socket.emit('errorInformsubmit', mobileSocketIdInServer);
          console.log(key + " je zit verkeerd");
        }
      });
    }

  });

  ////////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////
  ///////////////////////////Disconnect///////////////////////////////
  ////////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////

  socket.on('disconnect', () => {
    clients = clients.filter(c => c.socketid !== socket.id);
    socket.broadcast.emit('removePlayer', socket.id);

  });

});

const randomColor = () => {

  let letters = '0123456789ABCDEF'.split('');
  let color = '#';
  for (let i = 0; i < 6; i++ ) {
      color += letters[Math.floor(Math.random() * 16)];
  }
  return color;

};

server.listen(port, () => {
  console.log('Server listening at port %d', port);
});


text:
package cloud.orbit.actors.extensions;

import cloud.orbit.actors.runtime.AbstractActor;
import cloud.orbit.concurrent.Task;
import cloud.orbit.exception.UncheckedException;

/**
 * Listener the actor activation/deactivation process.
 */
public interface LifetimeExtension extends ActorExtension
{
    /**
     * Called to construct actor.
     *
     * @param concreteClass concrete class of actor instance to construct
     * @return instance of concreteClass
     */
    default <T> T newInstance(Class<T> concreteClass)
    {
        try
        {
            return concreteClass.newInstance();
        }
        catch (Exception ex)
        {
            throw new UncheckedException(ex);
        }
    }

    /**
     * Called immediately before invoking the actors activation.
     *
     * @param actor the actor object being activated
     * @return a completion promise, the framework will wait if necessary.
     */
    default Task<?> preActivation(AbstractActor<?> actor)
    {
        return Task.done();
    }

    /**
     * Called immediately after invoking the actors activation.
     *
     * @param actor the actor object being activated
     * @return a completion promise, the framework will wait if necessary.
     */
    default Task<?> postActivation(AbstractActor<?> actor)
    {
        return Task.done();
    }

    /**
     * Called immediately before invoking the actors deactivation code.
     *
     * @param actor the actor object being deactivated
     * @return a completion promise, the framework will wait if necessary.
     */
    default Task<?> preDeactivation(AbstractActor<?> actor)
    {
        return Task.done();
    }

    /**
     * Called immediately after invoking the actors deactivation code.
     *
     * @param actor the actor object being deactivated
     * @return a completion promise, the framework will wait if necessary.
     */
    default Task<?> postDeactivation(AbstractActor<?> actor)
    {
        return Task.done();
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.dubbo.rpc.cluster.router.tag;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.cluster.Router;
import org.apache.dubbo.rpc.cluster.RouterFactory;

public class TagRouterFactory implements RouterFactory {

    public static final String NAME = "tag";

    @Override
    public Router getRouter(URL url) {
        return new TagRouter(url);
    }
}


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

namespace Cruder.Helper
{
    public static class StringHelper
    {
        public static readonly Regex SlugRegex = new Regex(@"(^[a-z0-9])([a-z0-9_-]+)*([a-z0-9])$", RegexOptions.Compiled);

        public static string Split(this string text, int length, string suffix)
        {
            if (text.Length > length)
            {
                int num = length - suffix.Length;
                if (num > 0)
                {
                    text = text.Substring(0, num) + suffix;
                    return text;
                }
                text = text.Substring(0, length);
            }

            return text;
        }

        public static string GenerateRandom(int length)
        {
            StringBuilder generated = new StringBuilder();

            Random randomizer = new Random();
            List<int> possibleChars = new List<int>();
            possibleChars.AddRange(Enumerable.Range(48, 10)); //0-9
            possibleChars.AddRange(Enumerable.Range(65, 26)); //A-Z
            possibleChars.AddRange(Enumerable.Range(97, 26)); //a-z

            for (int i = 1; i <= length; i++)
            {
                generated.Append((char)possibleChars[randomizer.Next(possibleChars.Count)]);
            }

            return generated.ToString();
        }

        public static string GenerateSlug(string value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            if (SlugRegex.IsMatch(value))
            {
                return value;
            }

            string result = RemoveAccent(value).ToLowerInvariant();
            result = result.Trim('-', '.');
            result = result.Replace('.', '-');
            result = result.Replace("#", "-sharp");
            result = Regex.Replace(result, @"[^a-z0-9\s-]", string.Empty); // remove invalid characters
            result = Regex.Replace(result, @"\s+", " ").Trim(); // convert multiple spaces into one space

            return Regex.Replace(result, @"\s", "-"); // replace all spaces with hyphens
        }

        public static string Serialize(this IEnumerable<string> enumerable, string separator = ",")
        {
            string retVal = null;
            StringBuilder sb = new StringBuilder();

            foreach (string item in enumerable)
            {
                sb.AppendFormat("{0}{1}", item, separator);
            }

            if (!string.IsNullOrEmpty(sb.ToString()))
            {
                retVal = sb.Remove(sb.Length - separator.Length, separator.Length).ToString();
            }

            return retVal;
        }

        private static string RemoveAccent(string txt)
        {
            byte[] bytes = Encoding.GetEncoding("Cyrillic").GetBytes(txt);
            return Encoding.ASCII.GetString(bytes);
        }
    }
}


text:
/*
 * Angular Imports
 */
import {Routes, RouterModule} from '@angular/router';

/*
 * Components
 */
import {WelcomeComponent} from './welcome/welcome.component';
import {ProductListComponent} from './product/product-list.component';
import {ProductViewComponent} from './product/product-view.component';
import {CartViewComponent} from './cart/cart-view.component';
import {CheckoutViewComponent} from './checkout/checkout-view.component';

/*
 * Routes
 */
export const routes: Routes = [
  { path: '', redirectTo: 'welcome', pathMatch: 'full' },
  { path: 'welcome', component: WelcomeComponent },
  { path: 'products', component: ProductListComponent },
  { path: 'products/:id', component: ProductViewComponent },
  { path: 'cart', component: CartViewComponent },
  { path: 'checkout', component: CheckoutViewComponent },
];


text:
/*
 * Tests the floating point context save and restore mechanism.
 *
 * Two tasks are created - each of which is allocated a buffer of
 * portNO_FLOP_REGISTERS_TO_SAVE 32bit variables into which the flop context
 * of the task is saved when the task is switched out, and from which the
 * flop context of the task is restored when the task is switch in.  Prior to
 * the tasks being created each position in the two buffers is filled with a
 * unique value - this way the flop context of each task is different.
 *
 * The two test tasks never block so are always in either the Running or
 * Ready state.  They execute at the lowest priority so will get pre-empted
 * regularly, although the yield frequently so will not get much execution
 * time.  The lack of execution time is not a problem as its only the
 * switching in and out that is being tested.
 *
 * Whenever a task is moved from the Ready to the Running state its flop
 * context will be loaded from the buffer, but while the task is in the
 * Running state the buffer is not used and can contain any value - in this
 * case and for test purposes the task itself clears the buffer to zero.
 * The next time the task is moved out of the Running state into the
 * Ready state the flop context will once more get saved to the buffer -
 * overwriting the zeros.
 *
 * Therefore whenever the task is not in the Running state its buffer contains
 * the most recent values of its floating point registers - the zeroing out
 * of the buffer while the task was executing being used to ensure the values
 * the buffer contains are not stale.
 *
 * When neither test task is in the Running state the buffers should contain
 * the unique values allocated before the tasks were created.  If so then
 * the floating point context has been maintained.  This check is performed
 * by the 'check' task (defined in main.c) by calling
 * xAreFlopRegisterTestsStillRunning().
 *
 * The test tasks also increment a value each time they execute.
 * xAreFlopRegisterTestsStillRunning() also checks that this value has changed
 * since it last ran to ensure the test tasks are still getting processing time.
 */

/* Standard includes files. */
#include <string.h>

/* Scheduler include files. */
#include "FreeRTOS.h"
#include "task.h"

/*-----------------------------------------------------------*/

#define flopNUMBER_OF_TASKS		2
#define flopSTART_VALUE ( 0x0000000100000001LL )

/*-----------------------------------------------------------*/

/* The two test tasks as described at the top of this file. */
static void vFlopTest1( void *pvParameters );
static void vFlopTest2( void *pvParameters );

/*-----------------------------------------------------------*/

/* Buffers into which the flop registers will be saved.  There is a buffer for
both tasks. */
static volatile portDOUBLE dFlopRegisters[ flopNUMBER_OF_TASKS ][ portNO_FLOP_REGISTERS_TO_SAVE ];

/* Variables that are incremented by the tasks to indicate that they are still
running. */
static volatile unsigned long ulFlop1CycleCount = 0, ulFlop2CycleCount = 0;

/*-----------------------------------------------------------*/

void vStartFlopRegTests( void )
{
xTaskHandle xTaskJustCreated;
unsigned portBASE_TYPE x, y;
portDOUBLE z = flopSTART_VALUE;

	/* Fill the arrays into which the flop registers are to be saved with
	known values.  These are the values that will be written to the flop
	registers when the tasks start, and as the tasks do not perform any
	flop operations the values should never change.  Each position in the
	buffer contains a different value so the flop context of each task
	will be different. */
	for( x = 0; x < flopNUMBER_OF_TASKS; x++ )
	{
		for( y = 0; y < ( portNO_FLOP_REGISTERS_TO_SAVE - 1); y++ )
		{
			dFlopRegisters[ x ][ y ] = z;
			z+=flopSTART_VALUE;
		}
	}

	/* Create the first task. */
	xTaskCreate( vFlopTest1, ( signed char * ) "flop1", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, &xTaskJustCreated );

	/* The task	tag value is a value that can be associated with a task, but
	is not used by the scheduler itself.  Its use is down to the application so
	it makes a convenient place in this case to store the pointer to the buffer
	into which the flop context of the task will be stored.  The first created
	task uses dFlopRegisters[ 0 ], the second dFlopRegisters[ 1 ]. */
	vTaskSetApplicationTaskTag( xTaskJustCreated, ( void * ) &( dFlopRegisters[ 0 ][ 0 ] ) );

	/* Do the same for the second task. */
	xTaskCreate( vFlopTest2, ( signed char * ) "flop2", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, &xTaskJustCreated );
	vTaskSetApplicationTaskTag( xTaskJustCreated, ( void * ) &( dFlopRegisters[ 1 ][ 0 ] ) );
}
/*-----------------------------------------------------------*/

static void vFlopTest1( void *pvParameters )
{
	/* Just to remove compiler warning. */
	( void ) pvParameters;

	for( ;; )
	{
		/* The values from the buffer should have now been written to the flop
		registers.  Clear the buffer to ensure the same values then get written
		back the next time the task runs.  Being preempted during this memset
		could cause the test to fail, hence the critical section. */
		portENTER_CRITICAL();
			memset( ( void * ) dFlopRegisters[ 0 ], 0x00, ( portNO_FLOP_REGISTERS_TO_SAVE * sizeof( portDOUBLE ) ) );
		portEXIT_CRITICAL();

		/* We don't have to do anything other than indicate that we are
		still running. */
		ulFlop1CycleCount++;
		taskYIELD();
	}
}
/*-----------------------------------------------------------*/

static void vFlopTest2( void *pvParameters )
{
	/* Just to remove compiler warning. */
	( void ) pvParameters;

	for( ;; )
	{
		/* The values from the buffer should have now been written to the flop
		registers.  Clear the buffer to ensure the same values then get written
		back the next time the task runs. */
		portENTER_CRITICAL();
			memset( ( void * ) dFlopRegisters[ 1 ], 0x00, ( portNO_FLOP_REGISTERS_TO_SAVE * sizeof( portDOUBLE ) ) );
		portEXIT_CRITICAL();

		/* We don't have to do anything other than indicate that we are
		still running. */
		ulFlop2CycleCount++;
		taskYIELD();
	}
}
/*-----------------------------------------------------------*/

portBASE_TYPE xAreFlopRegisterTestsStillRunning( void )
{
portBASE_TYPE xReturn = pdPASS;
unsigned portBASE_TYPE x, y;
portDOUBLE z = flopSTART_VALUE;
static unsigned long ulLastFlop1CycleCount = 0, ulLastFlop2CycleCount = 0;

	/* Called from the 'check' task.

	The flop tasks cannot be currently running, check their saved registers
	are as expected.  The tests tasks do not perform any flop operations so
	their registers should be as per their initial setting. */
	for( x = 0; x < flopNUMBER_OF_TASKS; x++ )
	{
		for( y = 0; y < ( portNO_FLOP_REGISTERS_TO_SAVE - 1 ); y++ )
		{
			if( dFlopRegisters[ x ][ y ] != z )
			{
				xReturn = pdFAIL;
				break;
			}

			z+=flopSTART_VALUE;
		}
	}

	/* Check both tasks have actually been swapped in and out since this function
	last executed. */
	if( ulFlop1CycleCount == ulLastFlop1CycleCount )
	{
		xReturn = pdFAIL;
	}

	if( ulFlop2CycleCount == ulLastFlop2CycleCount )
	{
		xReturn = pdFAIL;
	}

	ulLastFlop1CycleCount = ulFlop1CycleCount;
	ulLastFlop2CycleCount = ulFlop2CycleCount;

	return xReturn;
}


text:
package org.kylin.service.xcode.filters.impl;

import javafx.util.Pair;
import org.apache.commons.collections4.CollectionUtils;
import org.kylin.bean.p5.WCode;
import org.kylin.service.xcode.filters.SimpleFilter;
import org.kylin.util.TransferUtil;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class GossipSimpleFilterr implements SimpleFilter{

    @Override
    public List<WCode> filter(List<WCode> target, String filterStr) {

        if(CollectionUtils.isEmpty(target)){
            return Collections.emptyList();
        }

        List<Pair<Integer,Integer>> gossips = TransferUtil.parsePairCodeList(filterStr);
        if(CollectionUtils.isEmpty(gossips)){
            return target;
        }

        List<WCode> ret = target.stream().filter(wCode -> isContain(wCode, gossips)).collect(Collectors.toList());

        return ret;
    }

    private boolean isContain(WCode wCode, List<Pair<Integer,Integer>> gossips){
        for(Pair<Integer,Integer> pair : gossips){

            if((wCode.getCodes().get(0) == pair.getKey()
                    || wCode.getCodes().get(1) == pair.getKey())
                    && (wCode.getCodes().get(0) == pair.getValue()
                    || wCode.getCodes().get(1) == pair.getValue())){
                return true;
            }
        }

        return false;
    }
}


text:
=head1 NAME

Mail::SpamAssassin::SQLBasedAddrList - SpamAssassin SQL Based Auto Welcomelist

=head1 SYNOPSIS

    my $factory = Mail::SpamAssassin::SQLBasedAddrList->new()
    $spamtest->set_persistent_addr_list_factory ($factory);
  ... call into SpamAssassin classes...

SpamAssassin will call:

    my $addrlist = $factory->new_checker($spamtest);
    $entry = $addrlist->get_addr_entry ($addr, $origip);
  ...

=head1 DESCRIPTION

A SQL based persistent address list implementation.

See C<Mail::SpamAssassin::PersistentAddrList> for more information.

Uses DBI::DBD module access to your favorite database (tested with
MySQL, SQLite and PostgreSQL) to store user auto-welcomelists.

The default table structure looks like this:
CREATE TABLE awl (
  username varchar(100) NOT NULL default '',
  email varchar(255) NOT NULL default '',
  ip varchar(40) NOT NULL default '',
  msgcount int(11) NOT NULL default '0',
  totscore float NOT NULL default '0',
  signedby varchar(255) NOT NULL default '',
  last_hit timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (username,email,signedby,ip)
) TYPE=MyISAM;

Your table definition may change depending on which database driver
you choose.  There is a config option to override the table name.

This module introduces several new config variables:

user_awl_dsn

user_awl_sql_username

user_awl_sql_password

user_awl_sql_table

user_awl_sql_override_username

see C<Mail::SpamAssassin::Conf> for more information.

=cut

package Mail::SpamAssassin::SQLBasedAddrList;

use strict;
use warnings;
# use bytes;
use re 'taint';

# Do this silliness to stop RPM from finding DBI as required
BEGIN { require DBI;  DBI->import; }

use Mail::SpamAssassin::PersistentAddrList;
use Mail::SpamAssassin::Logger;

our @ISA = qw(Mail::SpamAssassin::PersistentAddrList);

=head2 new

public class (Mail::SpamAssassin::SQLBasedAddrList) new ()

Description:
This method creates a new instance of the SQLBasedAddrList factory and calls
the parent's (PersistentAddrList) new method.

=cut

sub new {
  my ($proto) = @_;
  my $class = ref($proto) || $proto;
  my $self = $class->SUPER::new(@_);
  $self->{class} = $class;
  bless ($self, $class);
  $self;
}

=head2 new_checker

public instance (Mail::SpamAssassin::SQLBasedAddrList) new_checker (\% $main)

Description:
This method is called to setup a new checker interface and return a blessed
copy of itself.  Here is where we setup the SQL database connection based
on the config values.

=cut

sub new_checker {
  my ($self, $main) = @_;

  my $class = $self->{class};

  if (!$main->{conf}->{user_awl_dsn} ||
      !$main->{conf}->{user_awl_sql_table}) {
    dbg("auto-welcomelist: sql-based invalid config");
    return;
  }

  my $dsn    = $main->{conf}->{user_awl_dsn};
  my $dbuser = $main->{conf}->{user_awl_sql_username};
  my $dbpass = $main->{conf}->{user_awl_sql_password};

  my $dbh = DBI->connect($dsn, $dbuser, $dbpass, {'PrintError' => 0});

  if(!$dbh) {
    info("auto-welcomelist: sql-based unable to connect to database (%s) : %s",
         $dsn, DBI::errstr);
    return;
  }

  dbg("auto-welcomelist: sql-based connected to $dsn");

  $self = { 'main'      => $main,
            'dsn'       => $dsn,
            'dbh'       => $dbh,
            'tablename' => $main->{conf}->{user_awl_sql_table},
          };

  my $override_username = $main->{conf}->{user_awl_sql_override_username};
  if (defined $override_username && $override_username ne '') {
    $self->{_username} = $override_username;
  }
  else {
    $self->{_username} = $main->{username};

    # Need to make sure that a username is set, so just in case there is
    # no username set in main, set one here.
    if (!defined $self->{_username} || $self->{_username} eq '') {
      $self->{_username} = "GLOBAL";
    }
  }
  $self->{_with_awl_signer} =
    $main->{conf}->{auto_welcomelist_distinguish_signed};

  dbg("auto-welcomelist: sql-based using username: ".$self->{_username});

  return bless ($self, $class);
}

=head2 get_addr_entry

public instance (\%) get_addr_entry (String $addr, String $signedby)

Description:
This method takes a given C<$addr> and splits it between the email address
component and the ip component and performs a lookup in the database. If
nothing is found in the database then a blank entry hash is created and
returned, otherwise an entry containing the found information is returned.
If a with_awl_signer configuration option is enabled only addresses signed
by the given signing identity are taken into account, or, if $signedby is
undefined (or empty) only unsigned entries are considered.

A key, C<exists_p>, is set to 1 if an entry already exists in the database,
otherwise it is set to 0.

=cut

sub get_addr_entry {
  my ($self, $addr, $signedby) = @_;

  my $entry = { addr     => $addr,
                exists_p => 0,
                msgcount    => 0,
                totscore => 0,
                signedby => $signedby,
              };

  my ($email, $ip) = $self->_unpack_addr($addr);

  return $entry  unless $email ne '' && (defined $ip || defined $signedby);

  my $sql = "SELECT msgcount, totscore FROM $self->{tablename} " .
            "WHERE username = ? AND email = ?";
  my @args = ( $email );
  if (!$self->{_with_awl_signer}) {
    $sql .= " AND ip = ?";
    push(@args, $ip);
  } else {
    my @signedby = !defined $signedby ? () : split(' ', lc $signedby);
    if (!@signedby) {
      $sql .= " AND signedby = '' AND ip = ?";
      push(@args, $ip);
    } elsif (@signedby == 1) {
      $sql .= " AND signedby = ?";
    } elsif (@signedby > 1) {
      $sql .= " AND signedby IN (" . join(',', ('?') x @signedby) . ")";
    }
    push(@args, @signedby);
  }
  $sql .= " ORDER BY last_hit";

  my $sth = $self->{dbh}->prepare($sql);

  unless (defined($sth)) {
    info("auto-welcomelist: sql-based get_addr_entry %s: SQL prepare error: %s",
         join('|',@args), $self->{dbh}->errstr);
    return $entry;
  }

  my $rc = $sth->execute($self->{_username}, @args);

  if (!$rc) { # there was an error, but try to go on
    info("auto-welcomelist: sql-based get_addr_entry %s: SQL error: %s",
         join('|',@args), $sth->errstr);
    $entry->{msgcount} = 0;
    $entry->{totscore} = 0;
  }
  else {
    my $cnt = 0;
    my $aryref;
    # how to combine data if there are several entries (like signed by
    # an author domain and by a remailer)?  for now just take an average
    while ( defined($aryref = $sth->fetchrow_arrayref()) ) {
      if (defined $entry->{msgcount} && defined $aryref->[1]) {
        $entry->{msgcount} = $aryref->[0];
        $entry->{totscore} = $aryref->[1];
      }
      $entry->{exists_p} = 1;
      $cnt++;
    }
    dbg("auto-welcomelist: sql-based get_addr_entry: %s for %s",
        $cnt ? "found $cnt entries" : 'no entries found',
        join('|',@args) );
  }
  $sth->finish();

  # tests t/sql_based_w*.t look for this dbg line in this format
  dbg("auto-welcomelist: sql-based %s scores %.1f, msgcount %s",
      join('|',@args), $entry->{totscore}, $entry->{msgcount});

  return $entry;
}

=head2 add_score

public instance (\%) add_score (\% $entry, Integer $score)

Description:
This method adds a given C<$score> to a given C<$entry>.  If the entry was
marked as not existing in the database then an entry will be inserted,
otherwise a simple update will be performed.

NOTE: This code uses a self referential SQL call (ie set foo = foo + 1) which
is supported by most modern database backends, but not everything calling
itself a SQL database.

=cut

sub add_score {
  my($self, $entry, $score) = @_;

  return if (!$entry->{addr});

  my ($email, $ip) = $self->_unpack_addr($entry->{addr});

  $entry->{msgcount} += 1;
  $entry->{totscore} += $score;
  my $signedby = $entry->{signedby};

  return $entry  unless $email ne '' && (defined $ip || defined $signedby);

  # try inserting first, and if that fails we'll do the update; this way
  # we avoid to large extent a race condition between multiple processes

  my $inserted = 0;

  { my @fields = qw(username email ip msgcount totscore);
    my @signedby;
    if ($self->{_with_awl_signer}) {
      push(@fields, 'signedby');
      @signedby = !defined $signedby ? () : split(' ', lc $signedby);
      @signedby = ( '' )  if !@signedby;
    }
    my @args = ($self->{_username}, $email, $ip, 1, $score);
    my $sql = sprintf("INSERT INTO %s (%s) VALUES (%s)", $self->{tablename},
                      join(',', @fields),  join(',', ('?') x @fields));
    if ($self->{dsn} =~ /^DBI:(?:pg|SQLite)/i) {
       $sql .= " ON CONFLICT (username, email, signedby, ip) DO UPDATE set msgcount = ?, totscore = totscore + ?";
    } elsif ($self->{dsn} =~ /^DBI:(?:mysql|MariaDB)/i) {
       $sql .= " ON DUPLICATE KEY UPDATE msgcount = ?, totscore = totscore + ?";
    }

    my $sth = $self->{dbh}->prepare($sql);

    unless (defined($sth)) {
      info("auto-welcomelist: sql-based add_score/insert %s: SQL prepare error: %s",
           join('|',@args), $self->{dbh}->errstr);
      return $entry;
    }

    if (!$self->{_with_awl_signer}) {
      my $rc;
      if ($self->{dsn} =~ /^DBI:(?:pg|SQLite|mysql|MariaDB)/i) {
          $rc = $sth->execute(@args, $entry->{msgcount}, $score);
      } else {
          $rc = $sth->execute(@args);
      }
      if (!$rc) {
        dbg("auto-welcomelist: sql-based add_score/insert %s: SQL error: %s",
             join('|',@args), $sth->errstr);
      } else {
        dbg("auto-welcomelist: sql-based add_score/insert ".
            "score %s: %s", $score, join('|',@args));
        $inserted = 1; $entry->{exists_p} = 1;
      }
    } else {
      for my $s (@signedby) {
        my $rc;
	if ($self->{dsn} =~ /^DBI:(?:pg|SQLite|mysql|MariaDB)/i) {
          $rc = $sth->execute(@args, $s, $entry->{msgcount}, $score);
	} else {
	  $rc = $sth->execute(@args, $s);
	}
        if (!$rc) {
          dbg("auto-welcomelist: sql-based add_score/insert %s: SQL error: %s",
              join('|',@args,$s), $sth->errstr);
        } else {
          dbg("auto-welcomelist: sql-based add_score/insert ".
              "score %s: %s", $score, join('|',@args,$s));
          $inserted = 1; $entry->{exists_p} = 1;
        }
      }
    }
  }

  if (!$inserted && $self->{dsn} !~ /^DBI:(?:pg|SQLite|mysql|MariaDB)/i) {
    # insert failed, assume primary key constraint, so try the update

    my $sql = "UPDATE $self->{tablename} ".
              "SET msgcount = ?, totscore = totscore + ? ".
              "WHERE username = ? AND email = ?";
    my(@args) = ($entry->{msgcount}, $score, $self->{_username}, $email);
    if ($self->{_with_awl_signer}) {
      my @signedby = !defined $signedby ? () : split(' ', lc $signedby);
      if (!@signedby) {
        $sql .= " AND signedby = ''";
      } elsif (@signedby == 1) {
        $sql .= " AND signedby = ?";
      } elsif (@signedby > 1) {
        $sql .= " AND signedby IN (" . join(',', ('?') x @signedby) . ")";
      }
      push(@args, @signedby);
    }
    $sql .= " AND ip = ?";
    push(@args, $ip);

    my $sth = $self->{dbh}->prepare($sql);

    unless (defined($sth)) {
      info("auto-welcomelist: sql-based add_score/update %s: SQL prepare error: %s",
           join('|',@args), $self->{dbh}->errstr);
      return $entry;
    }

    my $rc = $sth->execute(@args);

    if (!$rc) {
      info("auto-welcomelist: sql-based add_score/update %s: SQL error: %s",
           join('|',@args), $sth->errstr);
    } else {
      dbg("auto-welcomelist: sql-based add_score/update ".
          "new msgcount: %s, new totscore: %s for %s",
          $entry->{msgcount}, $entry->{totscore}, join('|',@args));
      $entry->{exists_p} = 1;
    }
  }

  return $entry;
}

=head2 remove_entry

public instance () remove_entry (\% $entry)

Description:
This method removes a given C<$entry> from the database.  If the
ip portion of the entry address is equal to "none" then remove any
perl-IP entries for this address as well.

=cut

sub remove_entry {
  my ($self, $entry) = @_;

  my ($email, $ip) = $self->_unpack_addr($entry->{addr});

  return unless ($email && $ip);

  my $sql = "DELETE FROM $self->{tablename} WHERE username = ? AND email = ?";
  my @args = ($self->{_username}, $email);

  # when $ip is equal to none then attempt to delete all entries
  # associated with address
  if ($ip eq 'none') {
    dbg("auto-welcomelist: sql-based remove_entry: removing all entries matching $email");
  }
  else {
    $sql .= " AND ip = ?";
    push(@args, $ip);
    dbg("auto-welcomelist: sql-based remove_entry: removing single entry matching ".$entry->{addr});
  }
  # if a key 'signedby' exists in the $entry, be selective on its value too
  my $signedby = $entry->{signedby};
  if ($self->{_with_awl_signer} && defined $signedby) {
    my @signedby = split(' ', lc $signedby);
    if (@signedby == 1) {
      $sql .= " AND signedby = ?";
    } elsif (@signedby > 1) {
      $sql .= " AND signedby IN (" . join(',', ('?') x @signedby) . ")";
    }
    push(@args, @signedby);
  }

  my $sth = $self->{dbh}->prepare($sql);

  unless (defined($sth)) {
    info("auto-welcomelist: sql-based remove_entry %s: SQL prepare error: %s",
         join('|',@args), $self->{dbh}->errstr);
    return;
  }

  my $rc = $sth->execute(@args);

  if (!$rc) {
    info("auto-welcomelist: sql-based remove_entry %s: SQL error: %s",
         join('|',@args), $sth->errstr);
  }
  else {
    # We might normally have a dbg saying we removed the address
    # but the common codepath already provides this in SpamAssassin.pm
  }
  $entry = undef; # slight cleanup since it is now gone
}

=head2 finish

public instance () finish ()

Description:
This method provides the necessary cleanup for the address list.

=cut

sub finish {
  my ($self) = @_;
  dbg("auto-welcomelist: sql-based finish: disconnected from " . $self->{dsn});
  $self->{dbh}->disconnect();
}

=head2 _unpack_addr

private instance (String, String) _unpack_addr(string $addr)

Description:
This method splits an autowelcomelist address into it's two components,
email and ip address.

=cut

sub _unpack_addr {
  my ($self, $addr) = @_;

  my ($email, $ip) = split(/\|ip=/, $addr);

  unless ($email && $ip) {
    dbg("auto-welcomelist: sql-based _unpack_addr: unable to decode $addr");
  }

  return ($email, $ip);
}

1;


text:
<?php
/**
 * Created by PhpStorm.
 * User: NickTaporuk
 * Date: 22.12.13
 * Time: 19:34
 */
require(LIBS.'Smarty/libs/Smarty.class.php');
require(LIBS.'ActiveRecord/ActiveRecord.php');
/*
 *
 * */
function _loader_controller($class)
{
    require(LIBS.$class.".class.php");
}
/*
 *
 * */
//function _loader_geoIp($class)
//{
    require(LIBS.'getIp/SxGeo.php');
//}
spl_autoload_extensions('.php');
spl_autoload_register('_loader_controller','_loader_geoIp');
//print_r(spl_autoload_functions());


text:
using AppXLibrary.CustomXmlConfig;
using Juhta.Net.LibraryManagement;
using System;

namespace AppXLibrary.Closable
{
    public class ClosableLibrary : LibraryHandleBase, IClosableLibrary
    {
        #region Public Constructors

        public ClosableLibrary() : base("AppXLibrary.dll")
        {}

        #endregion

        #region Public Methods

        public bool CloseLibrary()
        {
            LibraryConfig.IntSetting = Int32.MaxValue;

            LibraryConfig.StringSetting = "<null>";

            return(true);
        }

        #endregion
    }
}


text:
<?php

class Google_Service_Dataflow_ContainerSpec extends Google_Model
{
  public $image;
  protected $metadataType = 'Google_Service_Dataflow_TemplateMetadata';
  protected $metadataDataType = '';
  protected $sdkInfoType = 'Google_Service_Dataflow_SDKInfo';
  protected $sdkInfoDataType = '';

  public function setImage($image)
  {
    $this->image = $image;
  }
  public function getImage()
  {
    return $this->image;
  }
  /**
   * @param Google_Service_Dataflow_TemplateMetadata
   */
  public function setMetadata(Google_Service_Dataflow_TemplateMetadata $metadata)
  {
    $this->metadata = $metadata;
  }
  /**
   * @return Google_Service_Dataflow_TemplateMetadata
   */
  public function getMetadata()
  {
    return $this->metadata;
  }
  /**
   * @param Google_Service_Dataflow_SDKInfo
   */
  public function setSdkInfo(Google_Service_Dataflow_SDKInfo $sdkInfo)
  {
    $this->sdkInfo = $sdkInfo;
  }
  /**
   * @return Google_Service_Dataflow_SDKInfo
   */
  public function getSdkInfo()
  {
    return $this->sdkInfo;
  }
}


text:
/**
  * Testing NeighbourAwareNode
  */

package uk.ac.cdrc.mintsearch.graph

import org.neo4j.driver.v1._
import org.neo4j.graphdb.GraphDatabaseService
import org.neo4j.harness.{ServerControls, TestServerBuilder, TestServerBuilders}
import org.scalatest._
import uk.ac.cdrc.mintsearch.index.PropertyLabelMaker
import uk.ac.cdrc.mintsearch.neo4j.{GraphDBContext, WithResource}

class NeighbourAwareNodeSpec extends fixture.WordSpec with Matchers {

  case class FixtureParam(neo4jServer: ServerControls) extends AutoCloseable {

    lazy val driver: Driver = GraphDatabase.driver(
      neo4jServer.boltURI(),
      Config.build().withEncryptionLevel(Config.EncryptionLevel.NONE).toConfig
    )

    val context = new GraphDBContext
        with ExponentialPropagation
        with PropertyLabelMaker
        with NeighbourhoodByRadius
        with NeighbourAwareContext {

      override val radius: Int = 2
      override val propagationFactor: Double = 0.5

      override val labelStorePropKey: String = s"__nagg_$radius"
      override val db: GraphDatabaseService = neo4jServer.graph()
    }

    override def close(): Unit = {
      neo4jServer.close()
    }
  }

  override def withFixture(test: OneArgTest): Outcome = {
    val builder: TestServerBuilder = TestServerBuilders.newInProcessBuilder()
    WithResource(FixtureParam(builder.newServer())) { f =>
      withFixture(test.toNoArgTest(f))
    }
  }

  "A neighbour aware node" should {

    "return paths to neighbours" in { f =>
      import f._
      WithResource(neo4jServer) { _ =>
        WithResource(driver.session()) { session =>
          import context.nodeWrapper
          // create a simple graph with two order of relationship friend
          val nodeId: Long = session.run(
            """CREATE
              | (a: Person {name:'Alice'}),
              | (b: Person {name: 'Bob'}),
              | (c: Person {name: 'Carl'}),
              | (a)-[:Friend]->(b)-[:Friend]->(c)
              | RETURN id(a)""".stripMargin
          )
            .single()
            .get(0).asLong()

          // create a wrapper function
          WithResource(context.db.beginTx()) { _ =>
            // query the neighbours
            val result = (for {
              p <- context.db.getNodeById(nodeId).neighbours
              n = p.endNode()
            } yield n.getProperty("name").toString).toSet
            result should not contain "Alice"
            result should contain("Bob")
            result should contain("Carl")
          }
          WithResource(context.db.beginTx()) { _ =>
            // query the neighbours
            val result = (for {
              p <- context.db.getNodeById(nodeId).neighbourhood
              n = p.endNode()
            } yield n.getProperty("name").toString).toSet
            result should contain("Alice")
            result should contain("Bob")
            result should contain("Carl")
          }
        }
      }
    }

    "return many neighbours" in { f =>
      import f._
      WithResource(neo4jServer) { _ =>
        WithResource(driver.session()) { session =>
          import context.nodeWrapper
          // create a simple graph with two order of relationship friend
          val nodeId: Long = session.run(
            """CREATE
              | (a: Person {name: 'Alice'}),
              | (b: Person {name: 'Bob'}),
              | (c: Person {name: 'Carl'}),
              | (d: Person {name: 'David'}),
              | (e: Person {name: 'Elizabeth'}),
              | (a)-[:Friend]->(b)-[:Friend]->(c),
              | (a)-[:Friend]->(d)-[:Friend]->(e)
              | RETURN id(a)""".stripMargin
          ).single().get(0).asLong()

          // create a wrapper function
          WithResource(context.db.beginTx()) { _ =>
            // query the neighbours
            val result = (for {
              p <- context.db.getNodeById(nodeId).neighbours
              n = p.endNode
            } yield n.getProperty("name").toString).toSet
            result should not contain "Alice"
            result should contain("Bob")
            result should contain("Carl")
            result should contain("David")
          }
        }
      }
    }

    "return all neighbours within 2 hops" in { f =>
      import f._
      WithResource(neo4jServer) { _ =>
        WithResource(driver.session()) { session =>
          import context.nodeWrapper
          // create a simple graph with two order of relationship friend
          val nodeId: Long = session.run(
            """CREATE
              | (a: Person {name: 'Alice'}),
              | (b: Person {name: 'Bob'}),
              | (c: Person {name: 'Carl'}),
              | (d: Person {name: 'David'}),
              | (a)-[:Friend]->(b)-[:Friend]->(c),
              | (a)-[:Friend]->(d)-[:Friend]->(c)
              | RETURN id(a)""".stripMargin
          ).single().get(0).asLong()

          // create a wrapper function
          WithResource(context.db.beginTx()) { _ =>
            // query the neighbours
            val result = (for {
              p <- context.db.getNodeById(nodeId).neighbours
              n = p.endNode()
            } yield n.getProperty("name").toString).toSet
            result should not contain "Alice"
            result should contain("Bob")
            result should contain("Carl")
            result should contain("David")
          }
          // create a wrapper function
          WithResource(context.db.beginTx()) { _ =>
            // query the neighbours
            val result = (for {
              p <- context.db.getNodeById(nodeId).neighbourhood
              n = p.endNode()
            } yield n.getProperty("name").toString).toSet
            result should contain("Alice")
            result should contain("Bob")
            result should contain("Carl")
            result should contain("David")
          }
        }
      }
    }
  }

}


text:
package tree.love.draglayout.drag;

import android.content.Context;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.widget.ViewDragHelper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

/** Created by wuyexiong on 13-8-31. */
public class DragLayout extends LinearLayout{

    private static final String TAG = "DragLayout";

    private ViewDragHelper mDragHelper;
    private View mDragView;

    public DragLayout(Context context) {
        super(context);
        init();
    }

    public DragLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public DragLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    private void init() {
        mDragHelper = ViewDragHelper.create(this, 1.0f, new DragHelperCallback());
        mDragHelper.setEdgeTrackingEnabled(ViewDragHelper.EDGE_LEFT);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        mDragView = getChildAt(0);
    }

    private class DragHelperCallback extends ViewDragHelper.Callback
    {
        @Override
        public boolean tryCaptureView(View child, int pointerId) {//返回true则表示启动拖拽
            return child == mDragView;
        }

        @Override
        public int clampViewPositionHorizontal(View child, int left, int dx) {//重新计算当前子View的X坐标
            Log.d(TAG, "clampViewPositionHorizontal " + left + "," + dx);
            final int leftBound  = getPaddingLeft();
            final int rightBound = getWidth() - mDragView.getWidth() - leftBound;
            final int newLeft = Math.min(Math.max(left, leftBound), rightBound);

            return newLeft;
        }

        @Override
        public int clampViewPositionVertical(View child, int top, int dy) {//重新计算当前子View的Y坐标
            Log.d(TAG, "clampViewPositionVertical " + top + "," + dy);
            final int topBound = getPaddingTop();
            final int bottomBound = getHeight() - mDragView.getHeight() - topBound;
            final int newTop = Math.min(Math.max(top, topBound), bottomBound);

            return newTop;
        }

        @Override
        public void onEdgeTouched(int edgeFlags, int pointerId) {//触发角接收到了触摸事件
            super.onEdgeTouched(edgeFlags, pointerId);
            Toast.makeText(getContext(), "edgeTouched:" + edgeFlags, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onEdgeDragStarted(int edgeFlags, int pointerId) {
            mDragHelper.captureChildView(mDragView,pointerId);
        }
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        final int action = MotionEventCompat.getActionMasked(ev);
        if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
            mDragHelper.cancel();
            return false;
        }
        return mDragHelper.shouldInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        boolean mINeedTouch = true;
        mDragHelper.processTouchEvent(event);
        return mINeedTouch;
    }
}


text:
class AddUniqueIndexOnPendingReports < ActiveRecord::Migration
  def change
    add_index :rp_pending_reports, :report_id, unique: true
  end
end


text:
Webpack offers multiple deployment targets for both server and browser. To set the target property, you simple set the target value in your webpack config:

```javascript
module.exports = {
    target: 'node'
}
```

## Multiple Targets

Webpack does not support multiple strings being passed into the target property, you can create an isomorphic library by building two separate configurations:

```javascript
var path = require('path');
var serverConfig = {
  target: 'node',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'lib.node.js'
  }
  //…
};

var clientConfig = {
  target: 'web', // <=== can be omitted as default is 'web'
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'lib.js'
  }
  //…
};

module.exports = [ serverConfig, clientConfig ];

```


text:
<?xml version="1.0" encoding="utf-8"?>
<openerp>
    <data>
        <record model="ir.module.category" id="module_category_networking">
            <field name="name">Hardware Administration</field>
            <field name="description">Helps you handle all the hardware in your network.</field>
            <field name="sequence">100</field>
        </record>
    </data>
</openerp>


text:
<?php

namespace Drupal\key\Exception;

/**
 * Defines a generic exception for Key.
 */
class KeyException extends \Exception { }


text:
SYNONYM

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

#### Published in
Z. PflKrankh. PflPath. PflSchutz 9: 152 (1899)

#### Original name
Puccinia urticae-hirtae Kleb., 1899

### Remarks
null


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="100"
    android:background="#000000" >

	<ImageView
	    android:id="@+id/player_album_art_view"
	    android:paddingTop="10dp"
	    android:layout_width="match_parent"
	    android:layout_height="0dp"
	    android:layout_weight="45"
	    android:src="@drawable/ic_launcher"
	    android:contentDescription="@string/access_album_art"
	     />

	<SeekBar
		    android:id="@+id/player_progress_bar"
		    android:layout_width="match_parent"
		    android:layout_height="0dp"
		    android:minHeight="5dip"
		    android:maxHeight="5dip"
		    style="@android:style/Widget.ProgressBar.Horizontal"
		    android:layout_weight="10"
		    android:progressDrawable="@drawable/seek_bar_custom"
		    android:thumb="@drawable/thumb"
		    />

	<RelativeLayout
	    android:id="@+id/player_time_section"
	    android:layout_width="match_parent"
	    android:layout_height="0dp"
	    android:layout_weight="5">

	    <TextView
	        android:id="@+id/player_current_time_display"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:layout_alignParentLeft="true"
	        android:text="@string/zero_time"
	        android:textColor="#FFFFFF"
	        android:layout_marginLeft="10dp"
	         />

		<TextView
	        android:id="@+id/player_total_time_display"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:layout_alignParentRight="true"
	        android:text="@string/zero_time"
	        android:textColor="#FFFFFF"
	        android:layout_marginLeft="10dp"
	         />

	</RelativeLayout>

	<TextView
	    android:id="@+id/player_track_name_view"
	    android:layout_width="match_parent"
	    android:layout_height="0dp"
	    android:layout_weight="10"
	    android:layout_marginLeft="10dp"
	    android:layout_marginRight="10dp"
	    android:textColor="#FFFFFF"
	    android:textSize="20sp"
	    />

	<TextView
	    android:id="@+id/player_artist_name_view"
	    android:layout_width="match_parent"
	    android:layout_height="0dp"
	    android:layout_weight="5"
	   	android:layout_marginLeft="10dp"
	    android:layout_marginRight="10dp"
	    android:textColor="#FFFFFF"
	    android:textSize="18sp"
	    />

	<TextView
	    android:id="@+id/player_album_name_view"
	    android:layout_width="match_parent"
	    android:layout_height="0dp"
	    android:layout_weight="5"
	   	android:layout_marginLeft="10dp"
	    android:layout_marginRight="10dp"
	    android:textColor="#FFFFFF"
	    android:textSize="15sp"
	    />

	<LinearLayout
	    android:id="@+id/player_control_section"
	    android:layout_width="match_parent"
	    android:layout_height="0dp"
	    android:orientation="horizontal"
	    android:gravity="center"
	    android:layout_weight="20">

	    <ImageButton
	        android:id="@+id/player_back_button"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:contentDescription="@string/access_back_button"
	        android:background="@drawable/list_item_background_selector"
	        android:src="@drawable/ic_back"
	        />

	    <ImageButton
	        android:id="@+id/player_play_pause_button"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:contentDescription="@string/access_play_pause_button"
	        android:background="@drawable/list_item_background_selector"
	        android:src="@drawable/ic_play"
	        />

	    <ImageButton
	        android:id="@+id/player_forward_button"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:contentDescription="@string/access_forward_button"
	        android:background="@drawable/list_item_background_selector"
	        android:src="@drawable/ic_forward"
	        />
	</LinearLayout>

</LinearLayout>


text:
package org.formula.swing.binding;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JCheckBox;

import org.formula.binding.FormBinder;
import org.formula.binding.PropertyMap;
import org.formula.converter.Converter;

public class JCheckBoxBinding extends SwingFormFieldBinding<JCheckBox> implements ActionListener {

	private String pattern = null;

	public JCheckBoxBinding(JCheckBox jCheckBox, FormBinder formBinder, PropertyMap propertyMap, String property, String[] labelProperties, String optionsProperty, boolean required, boolean errorIndicator, Converter converter) {
		super(jCheckBox, formBinder, propertyMap, property, labelProperties, optionsProperty, required, errorIndicator, converter);
		jCheckBox.addActionListener(this);
		this.pattern = jCheckBox.getText();
	}

	@Override
	protected void doRead() {
		if (getPropertyValue() != null) {
			getView().setSelected((Boolean) getPropertyValue());
		}
	}

	@Override
	protected void doReadLabel() {
		if (this.pattern != null) {
			String[] labelProperties = getLabelProperties();
			if (labelProperties != null && labelProperties.length > 0) {
				Object[] labelPropertyValues = new Object[getLabelProperties().length];
				for (int i = 0; i < labelProperties.length; ++i) {
					labelPropertyValues[i] = getPropertyValue(labelProperties[i]);
					if (labelPropertyValues[i] == null) {
						labelPropertyValues[i] = "";
					}
				}
				getView().setText(String.format(this.pattern, labelPropertyValues));
			} else {
				getView().setText(this.pattern);
			}
		}
	}

	@Override
	protected void doReadOptions() {

	}

	@Override
	public void actionPerformed(ActionEvent e) {
		write(getView().isSelected());
	}

	@Override
	public void enable(boolean enable) {
		getView().setEnabled(enable);
	}

	@Override
	public void focus() {
		getView().requestFocusInWindow();
	}

}


text:
using Microsoft.MixedReality.Toolkit.Utilities;
using System;
using UnityEngine;
using UnityEngine.XR;

#if MSFT_OPENXR && (UNITY_STANDALONE_WIN || UNITY_WSA)
using Microsoft.MixedReality.OpenXR;
#else
using System.Collections.Generic;
#endif

namespace Microsoft.MixedReality.Toolkit.XRSDK.OpenXR
{
    internal class OpenXRHandJointProvider
    {
        public OpenXRHandJointProvider(Utilities.Handedness handedness)
        {
#if MSFT_OPENXR && (UNITY_STANDALONE_WIN || UNITY_WSA)
            handTracker = handedness == Utilities.Handedness.Left ? HandTracker.Left : HandTracker.Right;
#endif // MSFT_OPENXR && (UNITY_STANDALONE_WIN || UNITY_WSA)
        }

#if MSFT_OPENXR && (UNITY_STANDALONE_WIN || UNITY_WSA)
        private static readonly HandJoint[] HandJoints = Enum.GetValues(typeof(HandJoint)) as HandJoint[];
        private readonly HandTracker handTracker = null;
        private readonly HandJointLocation[] locations = new HandJointLocation[HandTracker.JointCount];
#else
        private static readonly HandFinger[] HandFingers = Enum.GetValues(typeof(HandFinger)) as HandFinger[];
        private readonly List<Bone> fingerBones = new List<Bone>();
#endif // MSFT_OPENXR && (UNITY_STANDALONE_WIN || UNITY_WSA)

        public void UpdateHandJoints(Hand hand, ref MixedRealityPose[] jointPoses)
        {
#if MSFT_OPENXR && (UNITY_STANDALONE_WIN || UNITY_WSA)
            if (handTracker != null && handTracker.TryLocateHandJoints(FrameTime.OnUpdate, locations))
            {
                if (jointPoses == null)
                {
                    jointPoses = new MixedRealityPose[ArticulatedHandPose.JointCount];
                }

                foreach (HandJoint handJoint in HandJoints)
                {
                    HandJointLocation handJointLocation = locations[(int)handJoint];

                    // We want input sources to follow the playspace, so fold in the playspace transform here to
                    // put the pose into world space.
                    Vector3 position = MixedRealityPlayspace.TransformPoint(handJointLocation.Pose.position);
                    Quaternion rotation = MixedRealityPlayspace.Rotation * handJointLocation.Pose.rotation;

                    jointPoses[ConvertToArrayIndex(handJoint)] = new MixedRealityPose(position, rotation);
                }
#else
            if (jointPoses == null)
            {
                jointPoses = new MixedRealityPose[ArticulatedHandPose.JointCount];
            }

            foreach (HandFinger finger in HandFingers)
            {
                if (hand.TryGetRootBone(out Bone rootBone) && TryReadHandJoint(rootBone, out MixedRealityPose rootPose))
                {
                    jointPoses[(int)TrackedHandJoint.Palm] = rootPose;
                }

                if (hand.TryGetFingerBones(finger, fingerBones))
                {
                    for (int i = 0; i < fingerBones.Count; i++)
                    {
                        if (TryReadHandJoint(fingerBones[i], out MixedRealityPose pose))
                        {
                            jointPoses[ConvertToArrayIndex(finger, i)] = pose;
                        }
                    }
                }
#endif // MSFT_OPENXR && (UNITY_STANDALONE_WIN || UNITY_WSA)
            }
        }

#if MSFT_OPENXR && (UNITY_STANDALONE_WIN || UNITY_WSA)
        private int ConvertToArrayIndex(HandJoint handJoint)
        {
            TrackedHandJoint trackedHandJoint;

            switch (handJoint)
            {
                case HandJoint.Palm: trackedHandJoint = TrackedHandJoint.Palm; break;
                case HandJoint.Wrist: trackedHandJoint = TrackedHandJoint.Wrist; break;

                case HandJoint.ThumbMetacarpal: trackedHandJoint = TrackedHandJoint.ThumbMetacarpalJoint; break;
                case HandJoint.ThumbProximal: trackedHandJoint = TrackedHandJoint.ThumbProximalJoint; break;
                case HandJoint.ThumbDistal: trackedHandJoint = TrackedHandJoint.ThumbDistalJoint; break;
                case HandJoint.ThumbTip: trackedHandJoint = TrackedHandJoint.ThumbTip; break;

                case HandJoint.IndexMetacarpal: trackedHandJoint = TrackedHandJoint.IndexMetacarpal; break;
                case HandJoint.IndexProximal: trackedHandJoint = TrackedHandJoint.IndexKnuckle; break;
                case HandJoint.IndexIntermediate: trackedHandJoint = TrackedHandJoint.IndexMiddleJoint; break;
                case HandJoint.IndexDistal: trackedHandJoint = TrackedHandJoint.IndexDistalJoint; break;
                case HandJoint.IndexTip: trackedHandJoint = TrackedHandJoint.IndexTip; break;

                case HandJoint.MiddleMetacarpal: trackedHandJoint = TrackedHandJoint.MiddleMetacarpal; break;
                case HandJoint.MiddleProximal: trackedHandJoint = TrackedHandJoint.MiddleKnuckle; break;
                case HandJoint.MiddleIntermediate: trackedHandJoint = TrackedHandJoint.MiddleMiddleJoint; break;
                case HandJoint.MiddleDistal: trackedHandJoint = TrackedHandJoint.MiddleDistalJoint; break;
                case HandJoint.MiddleTip: trackedHandJoint = TrackedHandJoint.MiddleTip; break;

                case HandJoint.RingMetacarpal: trackedHandJoint = TrackedHandJoint.RingMetacarpal; break;
                case HandJoint.RingProximal: trackedHandJoint = TrackedHandJoint.RingKnuckle; break;
                case HandJoint.RingIntermediate: trackedHandJoint = TrackedHandJoint.RingMiddleJoint; break;
                case HandJoint.RingDistal: trackedHandJoint = TrackedHandJoint.RingDistalJoint; break;
                case HandJoint.RingTip: trackedHandJoint = TrackedHandJoint.RingTip; break;

                case HandJoint.LittleMetacarpal: trackedHandJoint = TrackedHandJoint.PinkyMetacarpal; break;
                case HandJoint.LittleProximal: trackedHandJoint = TrackedHandJoint.PinkyKnuckle; break;
                case HandJoint.LittleIntermediate: trackedHandJoint = TrackedHandJoint.PinkyMiddleJoint; break;
                case HandJoint.LittleDistal: trackedHandJoint = TrackedHandJoint.PinkyDistalJoint; break;
                case HandJoint.LittleTip: trackedHandJoint = TrackedHandJoint.PinkyTip; break;

                default: trackedHandJoint = TrackedHandJoint.None; break;
            }

            return (int)trackedHandJoint;
        }
#else
        private bool TryReadHandJoint(Bone bone, out MixedRealityPose pose)
        {
            bool positionAvailable = bone.TryGetPosition(out Vector3 position);
            bool rotationAvailable = bone.TryGetRotation(out Quaternion rotation);

            if (positionAvailable && rotationAvailable)
            {
                // We want input sources to follow the playspace, so fold in the playspace transform here to
                // put the pose into world space.
                position = MixedRealityPlayspace.TransformPoint(position);
                rotation = MixedRealityPlayspace.Rotation * rotation;

                pose = new MixedRealityPose(position, rotation);
                return true;
            }

            pose = MixedRealityPose.ZeroIdentity;
            return false;
        }

        /// <summary>
        /// Converts a Unity finger bone into an MRTK hand joint.
        /// </summary>
        /// <remarks>
        /// For HoloLens 2, Unity provides four joints for the thumb and five joints for other fingers, in index order of metacarpal (0) to tip (4).
        /// The wrist joint is provided as the hand root bone.
        /// </remarks>
        /// <param name="finger">The Unity classification of the current finger.</param>
        /// <param name="index">The Unity index of the current finger bone.</param>
        /// <returns>The current Unity finger bone converted into an MRTK joint.</returns>
        private int ConvertToArrayIndex(HandFinger finger, int index)
        {
            TrackedHandJoint trackedHandJoint;

            switch (finger)
            {
                case HandFinger.Thumb: trackedHandJoint = (index == 0) ? TrackedHandJoint.Wrist : TrackedHandJoint.ThumbMetacarpalJoint + index - 1; break;
                case HandFinger.Index: trackedHandJoint = TrackedHandJoint.IndexMetacarpal + index; break;
                case HandFinger.Middle: trackedHandJoint = TrackedHandJoint.MiddleMetacarpal + index; break;
                case HandFinger.Ring: trackedHandJoint = TrackedHandJoint.RingMetacarpal + index; break;
                case HandFinger.Pinky: trackedHandJoint = TrackedHandJoint.PinkyMetacarpal + index; break;
                default: trackedHandJoint = TrackedHandJoint.None; break;
            }

            return (int)trackedHandJoint;
        }
#endif // MSFT_OPENXR && (UNITY_STANDALONE_WIN || UNITY_WSA)
    }
}


text:
/** @file flint_spelling.h
 * @brief Spelling correction data for a flint database.
 */
/* Copyright (C) 2007,2008,2009,2010,2011 Olly Betts
 *
 * This program 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.
 *
 * This program 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 this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
 */

#ifndef XAPIAN_INCLUDED_FLINT_SPELLING_H
#define XAPIAN_INCLUDED_FLINT_SPELLING_H

#include <xapian/types.h>

#include "flint_table.h"
#include "termlist.h"

#include <map>
#include <set>
#include <string>
#include <cstring> // For memcpy() and memcmp().

struct F_fragment {
    char data[4];

    // Default constructor.
    F_fragment() { }

    // Allow implicit conversion.
    F_fragment(char data_[4]) { std::memcpy(data, data_, 4); }

    char & operator[] (unsigned i) { return data[i]; }
    const char & operator[] (unsigned i) const { return data[i]; }

    operator std::string () const {
	return std::string(data, data[0] == 'M' ? 4 : 3);
    }
};

inline bool operator<(const F_fragment &a, const F_fragment &b) {
    return std::memcmp(a.data, b.data, 4) < 0;
}

class FlintSpellingTable : public FlintTable {
    void toggle_word(const std::string & word);
    void toggle_fragment(F_fragment frag, const std::string & word);

    std::map<std::string, Xapian::termcount> wordfreq_changes;

    /** Changes to make to the termlists.
     *
     *  This list is essentially xor-ed with the list on disk, so an entry
     *  here either means a new entry needs to be added on disk, or an
     *  existing entry on disk needs to be removed.  We do it this way so
     *  we don't need to store an additional add/remove flag for every
     *  word.
     */
    std::map<F_fragment, std::set<std::string> > termlist_deltas;

  public:
    /** Create a new FlintSpellingTable object.
     *
     *  This method does not create or open the table on disk - you
     *  must call the create() or open() methods respectively!
     *
     *  @param dbdir		The directory the flint database is stored in.
     *  @param readonly		true if we're opening read-only, else false.
     */
    FlintSpellingTable(const std::string & dbdir, bool readonly)
	: FlintTable("spelling", dbdir + "/spelling.", readonly, Z_DEFAULT_STRATEGY, true) { }

    // Merge in batched-up changes.
    void merge_changes();

    void add_word(const std::string & word, Xapian::termcount freqinc);
    void remove_word(const std::string & word, Xapian::termcount freqdec);

    TermList * open_termlist(const std::string & word);

    Xapian::doccount get_word_frequency(const std::string & word) const;

    /** Override methods of FlintTable.
     *
     *  NB: these aren't virtual, but we always call them on the subclass in
     *  cases where it matters).
     *  @{
     */

    bool is_modified() const {
	return !wordfreq_changes.empty() || FlintTable::is_modified();
    }

    void create_and_open(unsigned int blocksize) {
	// The spelling table is created lazily, but erase it in case we're
	// overwriting an existing database and it already exists.
	FlintTable::erase();
	FlintTable::set_block_size(blocksize);
    }

    void flush_db() {
	merge_changes();
	FlintTable::flush_db();
    }

    void cancel() {
	// Discard batched-up changes.
	wordfreq_changes.clear();
	termlist_deltas.clear();

	FlintTable::cancel();
    }

    // @}
};

/** The list of words containing a particular trigram. */
class FlintSpellingTermList : public TermList {
    /// The encoded data.
    std::string data;

    /// Position in the data.
    unsigned p;

    /// The current term.
    std::string current_term;

    /// Copying is not allowed.
    FlintSpellingTermList(const FlintSpellingTermList &);

    /// Assignment is not allowed.
    void operator=(const FlintSpellingTermList &);

  public:
    /// Constructor.
    FlintSpellingTermList(const std::string & data_)
	: data(data_), p(0) { }

    Xapian::termcount get_approx_size() const;

    std::string get_termname() const;

    Xapian::termcount get_wdf() const;

    Xapian::doccount get_termfreq() const;

    Xapian::termcount get_collection_freq() const;

    TermList * next();

    TermList * skip_to(const std::string & term);

    bool at_end() const;

    Xapian::termcount positionlist_count() const;

    Xapian::PositionIterator positionlist_begin() const;
};

#endif // XAPIAN_INCLUDED_FLINT_SPELLING_H


text:
//---------------------------------------------------------------------
// <copyright file="IIdentifierGenerator.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

namespace Microsoft.Test.Taupo.Contracts
{
using Microsoft.Test.Taupo.Common;

    /// <summary>
    /// Generates unique identifiers for use in code.
    /// </summary>
    [ImplementationSelector("IdentifierGenerator", IsTransient = true, HelpText = "Generates unique identifiers in code.", DefaultImplementation = "Consecutive")]
    public interface IIdentifierGenerator
    {
        /// <summary>
        /// Generates an identifier for a given class.
        /// </summary>
        /// <param name="identifierClass">A string that describes class of identifiers (such as 'Class','Property','EntityType') - identifiers are guaranteed to be unique within the class</param>
        /// <returns>Generated identifier.</returns>
        string GenerateIdentifier(string identifierClass);
    }
}


text:
@interface VenueAnnotation ()

@property (nonatomic, strong) NSString *name;

@end

@implementation VenueAnnotation

@synthesize coordinate;

- (instancetype)initWithTitle:(NSString *)title
{
    self = [super init];
    if (self) {
        _name = title;
    }
    return self;
}

- (NSString *)subtitle
{
    return nil;
}

- (NSString *)title
{
    return self.name;
}

@end


text:
exports = module.exports = require('./lib/rexster');

exports.ReplyError = require('./lib/reply_error');
exports.Promise = require('bluebird');


text:
require 'spec_helper'

describe Request::Approval do
  include Travis::Testing::Stubs

  let(:approval) { Request::Approval.new(request) }

  before do
    approval.stubs(:build_pull_requests?).returns(true)
    approval.stubs(:build_pushes?).returns(true)
    request.stubs(:creates_jobs?).returns(true)
  end

  describe 'config_accepted?' do
    it 'approves the build when .travis.yml is missing, but builds with .travis.yml are allowed' do
      request.config['.result'] = 'not_found'
      approval.config_accepted?.should be_true
    end

    it 'does not approve the build if .travis.yml is missing and builds without it are not allowed' do
      request.repository.stubs(:builds_only_with_travis_yml?).returns(true)
      request.config['.result'] = 'not_found'

      approval.config_accepted?.should be_false
      approval.message.should == '.travis.yml is missing and builds without .travis.yml are disabled'
    end

    it 'approves the build when .travis.yml is present' do
      request.config['.result'] = 'configured'
      approval.config_accepted?.should be_true
    end
  end

  describe 'branch_accepted?' do
    it 'does not accept a request that belongs to the github_pages branch' do
      request.commit.stubs(:branch).returns('gh_pages')
      approval.branch_accepted?.should be_false
    end

    it 'accepts a request that belongs to the gh-pages branch if it\'s specified in branches:only' do
      request.commit.stubs(:branch).returns('gh_pages')
      request.config['branches'] = { 'only' => ['gh-pages'] }
      approval.branch_accepted?.should be_true
    end

    it "doesn't fail when the branch configuration is an array" do
      request.config['branches'] = [{ 'only' => ['gh-pages'] }]
      approval.branch_accepted?.should be_true
    end
  end

  describe 'accepted?' do
    it 'accepts a request that has a commit, belongs to a public repository, is not skipped and does not belong to the github_pages branch and it is not a rails fork' do
      approval.should be_accepted
    end

    it 'does not accept a request that does not have a commit' do
      approval.stubs(:commit).returns(nil)
      approval.should_not be_accepted
    end

    it 'does not accept a request that belongs to a private repository' do
      request.repository.stubs(:private?).returns(true)
      approval.should_not be_accepted
    end

    it 'does not accept a request that belongs to an excluded repository' do
      request.repository.stubs(:slug).returns('svenfuchs/rails')
      approval.should_not be_accepted
    end

    it 'does not accept a request that is skipped (using the commit message)' do
      request.commit.stubs(:message).returns('update README [ci:skip]')
      approval.should_not be_accepted
    end

    it 'accepts a request that belongs to the github_pages branch and is explicitly set to build that branch (String)' do
      request.commit.stubs(:branch).returns('gh_pages')
      request.stubs(:config).returns('branches' => { 'only' => 'gh_pages' })
      approval.should be_accepted
    end

    it 'accepts a request that belongs to the github_pages branch and is explicitly set to build that branch (Array)' do
      request.commit.stubs(:branch).returns('gh_pages')
      request.stubs(:config).returns('branches' => { 'only' => ['gh_pages'] })
      approval.should be_accepted
    end

    it 'does not accept a request when it is disabled in settings' do
      approval.stubs(:enabled_in_settings?).returns(false)
      approval.should_not be_accepted
    end
  end

  describe 'approved?' do
    xit 'should be specified'
  end

  describe 'message' do
    it 'returns "pull requests disabled" if pull requests are disabled' do
      approval.stubs(:enabled_in_settings?).returns(false)
      request.stubs(:pull_request?).returns(true)
      approval.message.should == 'pull requests disabled'
    end

    it 'returns "pushes disabled" if pushes are disabled' do
      approval.stubs(:enabled_in_settings?).returns(false)
      request.stubs(:pull_request?).returns(false)
      approval.message.should == 'pushes disabled'
    end

    it 'returns "missing commit" if the commit is missing' do
      approval.stubs(:commit).returns(nil)
      approval.message.should == 'missing commit'
    end

    it 'returns "private repository" if the repository is private' do
      request.repository.stubs(:private?).returns(true)
      request.stubs(:config).returns({key: 'value'})
      approval.message.should == 'private repository'
    end

    it 'returns "excluded repository" if the repository is an excluded repository' do
      request.repository.stubs(:slug).returns('svenfuchs/rails')
      approval.message.should == 'excluded repository'
    end

    it 'returns "excluded repository" if the repository is an excluded repository and exclude rule is a string' do
      Travis.config.repository_filter.stubs(:exclude).returns(["\\/rails$"])
      request.repository.stubs(:slug).returns('svenfuchs/rails')
      approval.message.should == 'excluded repository'
    end

    it 'returns "github pages branch" if the branch is a github pages branch' do
      request.commit.stubs(:branch).returns('gh-pages')
      approval.message.should == 'github pages branch'
    end

    it 'returns "missing config" if the config is not present' do
      request.stubs(:config).returns(nil)
      approval.message.should == 'missing config'
    end

    it 'returns "branch not included or excluded" if the branch was not approved' do
      request.commit.stubs(:branch).returns('feature')
      request.stubs(:config).returns('branches' => { 'only' => 'master' })
      approval.message.should == 'branch not included or excluded'
    end
  end

  describe 'skipped?' do
    it 'returns true when the commit message contains [ci skip]' do
      request.commit.stubs(:message).returns 'lets party like its 1999 [ci skip]'
      approval.send(:skipped?).should be_true
    end
  end

  describe 'github_pages?' do
    it 'returns true for a branch named gh-pages' do
      request.commit.stubs(:branch).returns 'gh-pages'
      approval.send(:github_pages?).should be_true
    end

    it 'returns true for a branch named gh_pages' do
      request.commit.stubs(:branch).returns 'gh_pages'
      approval.send(:github_pages?).should be_true
    end

    it 'returns true when a PR is for gh_pages' do
      request.commit.stubs(:ref).returns 'refs/pulls/1/merge'
      request.commit.stubs(:branch).returns 'gh_pages'
      approval.send(:github_pages?).should be_true
    end

    it 'returns false for a branch named master' do
      commit.stubs(:branch).returns 'master'
      approval.send(:github_pages?).should be_false
    end
  end

  describe 'included_repository?' do
    it 'returns true if the repository is an included repository' do
      request.repository.stubs(:slug).returns 'rails/rails'
      approval.send(:included_repository?).should be_true
    end

    it 'returns true if the repository is an included repository with rule as a string' do
      Travis.config.repository_filter.stubs(:include).returns(["rails\\/rails"])
      request.repository.stubs(:slug).returns 'rails/rails'
      approval.send(:included_repository?).should be_true
    end

    it 'returns false if the repository is not included' do
      request.repository.stubs(:slug).returns 'josh/completeness-fu'
      approval.send(:included_repository?).should be_false
    end

    it 'returns false if the repository is not included with rule as a string' do
      Travis.config.repository_filter.stubs(:include).returns(["rails\\/rails"])
      request.repository.stubs(:slug).returns 'josh/completeness-fu'
      approval.send(:included_repository?).should be_false
    end
  end

  describe 'excluded_repository?' do
    it 'returns true if the repository is an excluded repository' do
      request.repository.stubs(:slug).returns 'josh/rails'
      approval.send(:excluded_repository?).should be_true
    end

    it 'returns false if the repository is not excluded' do
      request.repository.stubs(:slug).returns 'josh/completeness-fu'
      approval.send(:excluded_repository?).should be_false
    end

    it 'returns true if the repository is an excluded repository with rule as a string' do
      Travis.config.repository_filter.stubs(:exclude).returns(["\\/rails$"])
      request.repository.stubs(:slug).returns 'josh/rails'
      approval.send(:excluded_repository?).should be_true
    end

    it 'returns false if the repository is not excluded with rule as a string' do
      Travis.config.repository_filter.stubs(:exclude).returns(["\\/rails$"])
      request.repository.stubs(:slug).returns 'josh/completeness-fu'
      approval.send(:excluded_repository?).should be_false
    end
  end

  describe 'enabled_in_settings?' do
    it 'returns true if a request is an api request' do
      request.stubs(:api_request?).returns(true)
      approval.enabled_in_settings?.should be_true
    end

    it 'returns true if pull requests are enabled and a request is a pull request' do
      request.stubs(:pull_request?).returns(true)
      approval.stubs(:build_pull_requests?).returns(true)
      approval.enabled_in_settings?.should be_true
    end

    it 'returns true if pushes are enabled and a request is a push' do
      request.stubs(:pull_request?).returns(false)
      approval.stubs(:build_pushes?).returns(true)
      approval.enabled_in_settings?.should be_true
    end

    it 'returns false if pull requests are disabled and a request is a pull request' do
      request.stubs(:pull_request?).returns(true)
      approval.stubs(:build_pull_requests?).returns(false)
      approval.enabled_in_settings?.should be_false
    end

    it 'returns false if pushes are disabled and a request is a push' do
      request.stubs(:pull_request?).returns(false)
      approval.stubs(:build_pushes?).returns(false)
      approval.enabled_in_settings?.should be_false
    end
  end
end