text:
            Key
            Default
            Description

security.ssl.algorithms

            "TLS_RSA_WITH_AES_128_CBC_SHA"
            The comma separated list of standard SSL algorithms to be supported. Read more here

security.ssl.internal.enabled

            false
            Turns on SSL for internal network communication. Optionally, specific components may override this through their own settings (rpc, data transport, REST, etc).

security.ssl.internal.key-password

            (none)
            The secret to decrypt the key in the keystore for Flink's internal endpoints (rpc, data transport, blob server).

security.ssl.internal.keystore

            (none)
            The Java keystore file with SSL Key and Certificate, to be used Flink's internal endpoints (rpc, data transport, blob server).

security.ssl.internal.keystore-password

            (none)
            The secret to decrypt the keystore file for Flink's for Flink's internal endpoints (rpc, data transport, blob server).

security.ssl.internal.truststore

            (none)
            The truststore file containing the public CA certificates to verify the peer for Flink's internal endpoints (rpc, data transport, blob server).

security.ssl.internal.truststore-password

            (none)
            The password to decrypt the truststore for Flink's internal endpoints (rpc, data transport, blob server).

security.ssl.key-password

            (none)
            The secret to decrypt the server key in the keystore.

security.ssl.keystore

            (none)
            The Java keystore file to be used by the flink endpoint for its SSL Key and Certificate.

security.ssl.keystore-password

            (none)
            The secret to decrypt the keystore file.

security.ssl.protocol

            "TLSv1.2"
            The SSL protocol version to be supported for the ssl transport. Note that it doesn't support comma separated list.

security.ssl.rest.enabled

            false
            Turns on SSL for external communication via the REST endpoints.

security.ssl.rest.key-password

            (none)
            The secret to decrypt the key in the keystore for Flink's external REST endpoints.

security.ssl.rest.keystore

            (none)
            The Java keystore file with SSL Key and Certificate, to be used Flink's external REST endpoints.

security.ssl.rest.keystore-password

            (none)
            The secret to decrypt the keystore file for Flink's for Flink's external REST endpoints.

security.ssl.rest.truststore

            (none)
            The truststore file containing the public CA certificates to verify the peer for Flink's external REST endpoints.

security.ssl.rest.truststore-password

            (none)
            The password to decrypt the truststore for Flink's external REST endpoints.

security.ssl.truststore

            (none)
            The truststore file containing the public CA certificates to be used by flink endpoints to verify the peer's certificate.

security.ssl.truststore-password

            (none)
            The secret to decrypt the truststore.

security.ssl.verify-hostname

            true
            Flag to enable peer's hostname verification during ssl handshake.


text:
<title>Zend Framework API Documentation</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta><link rel="stylesheet" href="css/black-tie/jquery-ui-1.8.2.custom.css" type="text/css"></link><link rel="stylesheet" href="css/jquery.treeview.css" type="text/css"></link><link rel="stylesheet" href="css/theme.css" type="text/css"></link>

API Documentation

Feed/Writer/Extension/RendererAbstract.php

Global

                      Classes

\Zend_Feed_Writer_Extension_RendererAbstract

Zend Framework

LICENSE

This source file is subject to the new BSD license that is bundled
with this package in the file LICENSE.txt.
It is also available through the world-wide-web at this URL:
http://framework.zend.com/license/new-bsd
If you did not receive a copy of the license and are unable to
obtain it through the world-wide-web, please send an email
to padraic dot brady at yahoo dot com so we can send you a copy immediately.

category

Zend

copyright

Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)

license

New BSD License

package

Zend_Feed_Writer

version

$Id: RendererAbstract.php 24437 2011-09-03 19:31:11Z ramon $

\Zend_Feed_Writer_Extension_RendererAbstract
jump to top

Implements

\Zend_Feed_Writer_Extension_RendererInterface

category

Zend

copyright

Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)

license

New BSD License

package

Zend_Feed_Writer

Properties

\DOMElement
                 $_base= 'null'

Default valuenullDetails

Type

\DOMElement

mixed
                 $_container= 'null'

Default valuenullDetails

Type

mixed

\DOMDocument
                 $_dom= 'null'

Default valuenullDetails

Type

\DOMDocument

string
                 $_encoding= 'UTF-8'

Encoding of all text values

Default valueUTF-8Details

Type

string

mixed
                 $_entry= 'null'

Default valuenullDetails

Type

mixed

\DOMElement
                 $_rootElement= 'null'

Default valuenullDetails

Type

\DOMElement

string
                 $_type= 'null'

Default valuenullDetails

Type

string

Methods

__construct(
          mixed $container
          )

        :
          void

Constructor

Parameters

Name
Type
Description

$container
mixed

_appendNamespaces(

          )

        :
          void

abstract
Append namespaces to feed

getDataContainer(

          )

        :
          mixed

Get data container being rendered

Returns

Type
Description

mixed

getEncoding(

          )

        :
          void

Get feed encoding

getRootElement(

          )

        :
          \DOMElement

Get root element

Returns

Type
Description

\DOMElement

getType(

          )

        :
          string

Get feedtype

Returns

Type
Description

string

render(

          )

        :
          void

Render

Inherited from:
                    \Zend_Feed_Writer_Extension_RendererInterface::render()

setDomDocument(
          \DOMDocument $dom, \DOMElement $base
          )

        :
          \Zend_Feed_Writer_Extension_RendererAbstract

Set DOMDocument and DOMElement on which to operate

Parameters

Name
Type
Description

$dom
\DOMDocument

$base
\DOMElement

Returns

Type
Description

\Zend_Feed_Writer_Extension_RendererAbstract

setEncoding(
          string $enc
          )

        :
          \Zend_Feed_Writer_Extension_RendererAbstract

Set feed encoding

Parameters

Name
Type
Description

$enc
string

Returns

Type
Description

\Zend_Feed_Writer_Extension_RendererAbstract

setRootElement(
          \DOMElement $root
          )

        :
          \Zend_Feed_Writer_Extension_RendererAbstract

Set root element of document

Parameters

Name
Type
Description

$root
\DOMElement

Returns

Type
Description

\Zend_Feed_Writer_Extension_RendererAbstract

setType(
          string $type
          )

        :
          \Zend_Feed_Writer_Extension_RendererAbstract

Set feed type

Parameters

Name
Type
Description

$type
string

Returns

Type
Description

\Zend_Feed_Writer_Extension_RendererAbstract

Documentation was generated by DocBlox 0.13.3.

redpajama_set_name: RedPajamaGithub


text:
var namespacecrossbow_1_1program__options_1_1tag =
[
    [ "description", "structcrossbow_1_1program__options_1_1tag_1_1description.html", "structcrossbow_1_1program__options_1_1tag_1_1description" ],
    [ "ignore_long", "structcrossbow_1_1program__options_1_1tag_1_1ignore__long.html", null ],
    [ "ignore_short", "structcrossbow_1_1program__options_1_1tag_1_1ignore__short.html", null ],
    [ "show", "structcrossbow_1_1program__options_1_1tag_1_1show.html", null ]
];


text:
require 'space_object/base'

module SpaceObject
  class Encoder
    def initialize(object, options = {})
      self.object = object
      @as_key = !options.has_key?(:key) || options[:key]
    end

    def encode
      raise(ArgumentError, "#{@object} is not a Hash") unless @object.is_a?(Hash)
      @object.inject(Base.new) do |space, (key, val)|
        space[key.to_space_key] = val.to_space_value
        space
      end
    end

    def object=(object)
      @object = object
    end
  end
end


text:
package Moose::Meta::Role::Application;
BEGIN {
  $Moose::Meta::Role::Application::AUTHORITY = 'cpan:STEVAN';
}
{
  $Moose::Meta::Role::Application::VERSION = '2.0602';
}

use strict;
use warnings;
use metaclass;

__PACKAGE__->meta->add_attribute('method_exclusions' => (
    init_arg => '-excludes',
    reader   => 'get_method_exclusions',
    default  => sub { [] },
    Class::MOP::_definition_context(),
));

__PACKAGE__->meta->add_attribute('method_aliases' => (
    init_arg => '-alias',
    reader   => 'get_method_aliases',
    default  => sub { {} },
    Class::MOP::_definition_context(),
));

sub new {
    my ($class, %params) = @_;
    $class->_new(\%params);
}

sub is_method_excluded {
    my ($self, $method_name) = @_;
    foreach (@{$self->get_method_exclusions}) {
        return 1 if $_ eq $method_name;
    }
    return 0;
}

sub is_method_aliased {
    my ($self, $method_name) = @_;
    exists $self->get_method_aliases->{$method_name} ? 1 : 0
}

sub is_aliased_method {
    my ($self, $method_name) = @_;
    my %aliased_names = reverse %{$self->get_method_aliases};
    exists $aliased_names{$method_name} ? 1 : 0;
}

sub apply {
    my $self = shift;

    $self->check_role_exclusions(@_);
    $self->check_required_methods(@_);
    $self->check_required_attributes(@_);

    $self->apply_attributes(@_);
    $self->apply_methods(@_);

    $self->apply_override_method_modifiers(@_);

    $self->apply_before_method_modifiers(@_);
    $self->apply_around_method_modifiers(@_);
    $self->apply_after_method_modifiers(@_);
}

sub check_role_exclusions           { Carp::croak "Abstract Method" }
sub check_required_methods          { Carp::croak "Abstract Method" }
sub check_required_attributes       { Carp::croak "Abstract Method" }

sub apply_attributes                { Carp::croak "Abstract Method" }
sub apply_methods                   { Carp::croak "Abstract Method" }
sub apply_override_method_modifiers { Carp::croak "Abstract Method" }
sub apply_method_modifiers          { Carp::croak "Abstract Method" }

sub apply_before_method_modifiers   { (shift)->apply_method_modifiers('before' => @_) }
sub apply_around_method_modifiers   { (shift)->apply_method_modifiers('around' => @_) }
sub apply_after_method_modifiers    { (shift)->apply_method_modifiers('after'  => @_) }

1;

# ABSTRACT: A base class for role application

=pod

=head1 NAME

Moose::Meta::Role::Application - A base class for role application

=head1 VERSION

version 2.0602

=head1 DESCRIPTION

This is the abstract base class for role applications.

The API for this class and its subclasses still needs some
consideration, and is intentionally not yet documented.

=head2 METHODS

=over 4

=item B<new>

=item B<meta>

=item B<get_method_exclusions>

=item B<is_method_excluded>

=item B<get_method_aliases>

=item B<is_aliased_method>

=item B<is_method_aliased>

=item B<apply>

=item B<check_role_exclusions>

=item B<check_required_methods>

=item B<check_required_attributes>

=item B<apply_attributes>

=item B<apply_methods>

=item B<apply_method_modifiers>

=item B<apply_before_method_modifiers>

=item B<apply_after_method_modifiers>

=item B<apply_around_method_modifiers>

=item B<apply_override_method_modifiers>

=back

=head1 BUGS

See L<Moose/BUGS> for details on reporting bugs.

=head1 AUTHOR

Moose is maintained by the Moose Cabal, along with the help of many contributors. See L<Moose/CABAL> and L<Moose/CONTRIBUTORS> for details.

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2012 by Infinity Interactive, Inc..

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut

__END__


text:
namespace FakeItEasy
{
    using System.Linq;
    using System.Reflection;

    /// <summary>
    /// Provides extension methods for <see cref="ParameterInfo"/>.
    /// </summary>
    internal static class ParameterInfoExtensions
    {
        private const string IsReadOnlyAttributeFullName = "System.Runtime.CompilerServices.IsReadOnlyAttribute";

        public static bool IsOutOrRef(this ParameterInfo parameterInfo)
        {
            if (!parameterInfo.ParameterType.IsByRef)
            {
                return false;
            }

#if FEATURE_PARAMETERINFO_CUSTOMATTRIBUTES_PROPERTY
            var parameterAttributes = parameterInfo.CustomAttributes;
            return parameterAttributes is null ||
                   parameterAttributes.All(customAttributeData => customAttributeData.AttributeType.FullName != IsReadOnlyAttributeFullName);
#else
            var parameterAttributes = parameterInfo.GetCustomAttributesData();
            return parameterAttributes is null ||
                   parameterAttributes.All(customAttributeData => customAttributeData.Constructor.DeclaringType?.FullName != IsReadOnlyAttributeFullName);
#endif
        }
    }
}


text:
using System;

namespace Tools
{
    public class FillupEntry
    {
        public const int SIZE_IN_BYTES = 36;

        public DateTime EntryDate { get; set; }
        public double FillAmount { get; set; }
        public double PricePerUnit { get; set; }
        public double OdometerReading { get; set; }
        public bool WasNotToppedOff { get; set; }
        public bool PreviousEntryMissed { get; set; }
        public UnitOfMeasure.Volume PumpUnit { get; set; }
        public UnitOfMeasure.Distance OdometerUnit { get; set; }

        public static FillupEntry Clone(FillupEntry entry)
        {
            return (FillupEntry)entry.MemberwiseClone();
        }
    }

}


text:
package com.nh.micro.sync.git;

import java.io.File;

import org.apache.log4j.Logger;
import org.eclipse.jgit.api.CloneCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.ResetCommand.ResetType;
import org.eclipse.jgit.internal.storage.file.FileRepository;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;

/**
 *
 * @author ninghao
 *
 */
public class MicroGitSync {
	private static Logger logger=Logger.getLogger(MicroGitSync.class);

	public String localPath;
	public String remotePath;
	public String branchName = "master";
	public String version=null;
	public String userName;
	public String password;
	public boolean cloneFlag=false;
	public boolean timeFlag=false;
	public boolean openFlag=false;

	public boolean isOpenFlag() {
		return openFlag;
	}
	public void setOpenFlag(boolean openFlag) {
		this.openFlag = openFlag;
	}
	public boolean isTimeFlag() {
		return timeFlag;
	}
	public void setTimeFlag(boolean timeFlag) {
		this.timeFlag = timeFlag;
	}
	public boolean isCloneFlag() {
		return cloneFlag;
	}
	public void setCloneFlag(boolean cloneFlag) {
		this.cloneFlag = cloneFlag;
	}
	public String getLocalPath() {
		return localPath;
	}
	public void setLocalPath(String localPath) {
		this.localPath = localPath;
	}
	public String getRemotePath() {
		return remotePath;
	}
	public void setRemotePath(String remotePath) {
		this.remotePath = remotePath;
	}
	public String getBranchName() {
		return branchName;
	}
	public void setBranchName(String branchName) {
		this.branchName = branchName;
	}
	public String getVersion() {
		return version;
	}
	public void setVersion(String version) {
		this.version = version;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public void initRep() throws Exception{
		if(openFlag==false){
			logger.info("openFlag is false skip git sync");
			return;
		}
		logger.info("begin git sync init remote="+remotePath+" local="+localPath+" branch="+branchName);
		UsernamePasswordCredentialsProvider passwordProvider=null;
		if(userName!=null && !"".equals(userName)){
			passwordProvider=new UsernamePasswordCredentialsProvider(userName,password);
		}
		if(cloneFlag==true){
			logger.info("begin git sync init clone "+remotePath);
	        File file = new File(localPath);
	        if(file.exists()){
	        	logger.info("begin git sync init deletedir "+localPath);
	            deleteDir(file);
	        }

	        CloneCommand cc=Git.cloneRepository().setURI(remotePath).setBranch(branchName)
				.setDirectory(new File(localPath));
	        if(passwordProvider!=null){
				cc.setCredentialsProvider(passwordProvider);
	        }
	        Git git=cc.call();
	        logger.info("end git sync init clone ");
		}
        String localRepo=localPath+"/.git";
        Git gitReset = new Git(new FileRepository(localRepo));
        if(version!=null && !"".equals(version)){
        	logger.info("begin git sync init reset version="+version);
        	gitReset.reset().setMode(ResetType.HARD).setRef(version).call();
        	logger.info("end git sync init reset");
        }else{
        	logger.info("skip git sync init reset");
        }
        if(timeFlag==true){

        	Thread thread=new Thread(new Runnable(){

				@Override
				public void run() {
					try {
						Thread.sleep(1000*60);
						reset();
					} catch (Exception e) {
						logger.error("loop git reset error");
					}

				}

        	});
        	thread.setName("micro-git-sync-timer");
        	thread.setDaemon(true);
        	thread.run();
        	logger.info("begin git sync timer reset");
        }else{
        	logger.info("skip git sync timer reset");
        }
        logger.info("end git sync init");

	}
	public void reset() throws Exception{
		logger.debug("begin git sync loop");
        File file = new File(localPath);
        if(!file.exists()){
            logger.debug("rep not exist");
        }
        String localRepo=localPath+"/.git";
        Git git = new Git(new FileRepository(localRepo));
        git.reset().setMode(ResetType.HARD).call();
        logger.debug("end git sync loop");
	}

    private static boolean deleteDir(File dir) {
        if (!dir.exists()) return false;
        if (dir.isDirectory()) {
            String[] childrens = dir.list();

            for (String child : childrens) {
                boolean success = deleteDir(new File(dir, child));
                if (!success) return false;
            }

        }
        return dir.delete();

    }
}


text:
using System;
using System.Linq;
using Xunit;
using Stranne.VasttrafikNET.Tests.Jsons;

namespace Stranne.VasttrafikNET.Tests
{
    public class TrafficSituationsIntegrationTest : BaseIntegrationTest
    {
        [Fact]
        public void GetForStationNumber()
        {
            const string absoluteUrl = "https://api.vasttrafik.se/ts/v1/traffic-situations/RT1193380";
            SetUpNetworkServiceMock(absoluteUrl, JsonFile.TrafficSituation);
            var sut = GetTrafficSituationsService();

            var actual = sut.ForStationNumber("RT1193380");

            VerifyNetworkMock();
            Assert.Equal("RT1193380", actual.SituationNumber);
        }

        [Fact]
        public void GetForStopPoint()
        {
            const string absoluteUrl = "https://api.vasttrafik.se/ts/v1/traffic-situations/stoppoint/9022014016200002";
            SetUpNetworkServiceMock(absoluteUrl, JsonFile.TrafficSituationsStopPoints);
            var sut = GetTrafficSituationsService();

            var actual = sut.ForStopPoint("9022014016200002");

            VerifyNetworkMock();
            Assert.Equal(2, actual.Count());
        }

        [Fact]
        public void GetAll()
        {
            const string absoluteUrl = "https://api.vasttrafik.se/ts/v1/traffic-situations";
            SetUpNetworkServiceMock(absoluteUrl, JsonFile.TrafficSituations);
            var sut = GetTrafficSituationsService();

            var actual = sut.All();

            VerifyNetworkMock();
            Assert.Equal(5, actual.Count());
        }

        [Fact]
        public void GetForLine()
        {
            const string absoluteUrl = "https://api.vasttrafik.se/ts/v1/traffic-situations/line/9011014508200000";
            SetUpNetworkServiceMock(absoluteUrl, JsonFile.TrafficSituationsLines);
            var sut = GetTrafficSituationsService();

            var actual = sut.ForLine("9011014508200000");

            VerifyNetworkMock();
            Assert.Equal(1, actual.Count());
        }

        [Fact]
        public void GetForJourney()
        {
            const string absoluteUrl = "https://api.vasttrafik.se/ts/v1/traffic-situations/journey/9015014167103831";
            SetUpNetworkServiceMock(absoluteUrl, JsonFile.TrafficSituationsJourneies);
            var sut = GetTrafficSituationsService();

            var actual = sut.ForJourney("9015014167103831");

            VerifyNetworkMock();
            Assert.Equal(1, actual.Count());
        }

        [Fact]
        public void GetForStopArea()
        {
            const string absoluteUrl = "https://api.vasttrafik.se/ts/v1/traffic-situations/stoparea/9021014037386000";
            SetUpNetworkServiceMock(absoluteUrl, JsonFile.TrafficSituationsStopAreas);
            var sut = GetTrafficSituationsService();

            var actual = sut.ForStopArea("9021014037386000");

            VerifyNetworkMock();
            Assert.Equal(1, actual.Count());
        }

        [Fact]
        public void Dispose()
        {
            var sut = new TrafficSituationsService(Key, Secret);
            sut.Dispose();
        }
    }
}


text:
<?php declare(strict_types=1);
/**
 * This file is part of Swoft.
 *
 * @link     https://swoft.org
 * @document https://swoft.org/docs
 * @contact  group@swoft.org
 * @license  https://github.com/swoft-cloud/swoft/blob/master/LICENSE
 */

use AppTest\Testing\TestApplication;

$baseDir = dirname(__DIR__);
$vendor  = dirname(__DIR__) . '/vendor';

/** @var \Composer\Autoload\ClassLoader $loader */
$loader = require dirname(__DIR__) . '/vendor/autoload.php';

$swoftFwDir = $vendor . '/swoft/framework';

// in framework developing
if (file_exists($vendor . '/swoft/component/src/framework')) {
    $swoftFwDir = $vendor . '/swoft/component/src/framework';
}

$loader->addPsr4('AppTest\\Unit\\', $baseDir . '/test/unit/');
$loader->addPsr4('AppTest\\Testing\\', $baseDir . '/test/testing/');
$loader->addPsr4('SwoftTest\\Testing\\', $swoftFwDir . '/test/testing/');
// $loader->addPsr4('Swoft\\Swlib\\', $vendor . '/swoft/swlib/src/');

$app = new TestApplication($baseDir);
$app->run();


text:
<?xml version="1.0" encoding="ISO-8859-1"?>

<project name="swat-dp-tools.template-targets" default="info" basedir=".">

    <dirname file="${ant.file.swat-dp-tools.template-targets}" property="ant_templatetargets.dir" />
    <import file="${ant_templatetargets.dir}/taskdefs.xml" />
    <import file="${ant_templatetargets.dir}/chooser.xml" />

    <target name="info">
        <echo message="Common template targets for swat-dp-tools" />
        <echoproperties prefix="swat" />
    </target>

    <target name="init">

        <tstamp>
            <format property="FILESTAMP" pattern="yyyyMMdd_HHmmss" />
        </tstamp>
        <echo message="***** template-targets initialized at ${FILESTAMP} *****" />
        <echo message="current basedir = ${basedir}" />
        <echo message="current project = ${ant.project.name}" />
        <echo message="---------- predefined properties ----------" />

        <echoproperties regex="^mgr\.[a-z1-9]*\.(?!password|pwd|passwd)" />
        <echo message="---------- swat switches ----------" />
        <echoproperties regex="^swat\.[a-z1-9]*\.(?!password|pwd|passwd)" />
    </target>

    <target name="seed-service" depends="init,choose-domain" description="Seed a new service from the template">
        <loadproperties srcfile="${swat.dp.infra}/config/zones/${mgr.target.zone.name}/${mgr.target.zone.name}.properties" />
        <loadproperties srcfile="${swat.dp.infra}/config/zones/${mgr.target.zone.name}/envs/${mgr.target.env.name}/${mgr.target.env.name}.properties" />
        <loadproperties srcfile="${swat.dp.infra}/config/zones/${mgr.target.zone.name}/envs/${mgr.target.env.name}/domains/${mgr.target.domain.alias}.properties" />

        <service-create-project-prefix-macro zone="${swat.zone.short}" domain="${swat.domain.short}" />

        <antform title="Swat4DP Seed Service Project Generator ">
            Provide project information for the new service.
            <textProperty label="Service Name: "
                          property="suffix"
                          tooltip="Suffix of the name of the new service project. (Prefix: ${service.project.prefix})." />
            <textProperty label="Service Object Name: "
                          property="name"
                          tooltip="Name of the new DataPower service object." />
            <selectionproperty label="Service Object Class: "
                               property="class"
                               values="MultiProtocolGateway,WSGateway,XMLFirewallService,WebAppFW,HTTPService,WebTokenService,SSLProxyService,TCPProxyService"
                               tooltip="DataPower specific service class." />
            <textProperty label="Service Summary: " property="summary" tooltip="Short description of the service." />
            <controlbar>
                <button label="Cancel" type="cancel" target="cancel" />
                <button label="Ok" type="ok" />
            </controlbar>
        </antform>

        <fail unless="suffix" message="suffix property not set" />
        <fail unless="name" message="service name property not set" />
        <fail unless="summary" message="service summary property not set" />
        <fail unless="service.project.prefix" message="Project name prefix has not been generated!" />

        <propertyfile file="service.properties.tmp"
                      comment="Temporary filter properties for the service project generator.">
            <entry key="service.project.name" value="${service.project.prefix}-${suffix}" />
            <entry key="service.name" value="${suffix}" />
            <entry key="service.object.name" value="${name}" />
            <entry key="service.summary" value="${summary}" />
            <entry key="service.object.class" value="${class}" />

            <entry key="zone.name" value="${swat.zone.name}" />
            <entry key="env.name" value="${swat.env.name}" />
            <entry key="domain.name" value="${swat.domain.name}" />
        </propertyfile>

        <seed-svc-template-macro filterfile="service.properties.tmp" />

        <delete>
            <fileset dir="${basedir}">
                <include name="service.properties.tmp" />
            </fileset>
        </delete>

    </target>

    <target name="seed-version-file" depends="init,choose-domain" description="Seed version file">
        <loadproperties srcfile="${swat.dp.infra}/config/zones/${mgr.target.zone.name}/${mgr.target.zone.name}.properties" />
        <loadproperties srcfile="${swat.dp.infra}/config/zones/${mgr.target.zone.name}/envs/${mgr.target.env.name}/${mgr.target.env.name}.properties" />
        <loadproperties srcfile="${swat.dp.infra}/config/zones/${mgr.target.zone.name}/envs/${mgr.target.env.name}/domains/${mgr.target.domain.alias}.properties" />

        <propertyfile file="service.properties.tmp"
                      comment="Temporary filter properties for the service project generator.">
            <entry key="service.project.name" value="${swat.current.service}" />
            <entry key="service.name" value="${service.name}" />
            <entry key="service.object.name" value="${service.object.name}" />
        </propertyfile>

        <seed-version-file-macro filterfile="service.properties.tmp" />

        <delete>
            <fileset dir="${basedir}">
                <include name="service.properties.tmp" />
            </fileset>
        </delete>

    </target>

    <target name="clone-project"
            depends="init,choose-domain"
            description="Clone an existing project and do some pattern replacement">

        <property name="clone.source.dir" value="${basedir}/.." />
        <property name="clone.target.base.dir" value="${swat.dp.customer.home}" />
        <loadproperties srcfile="${swat.dp.infra}/config/zones/${mgr.target.zone.name}/${mgr.target.zone.name}.properties" />
        <loadproperties srcfile="${swat.dp.infra}/config/zones/${mgr.target.zone.name}/envs/${mgr.target.env.name}/${mgr.target.env.name}.properties" />
        <loadproperties srcfile="${swat.dp.infra}/config/zones/${mgr.target.zone.name}/envs/${mgr.target.env.name}/domains/${mgr.target.domain.alias}.properties" />

        <service-create-project-prefix-macro zone="${swat.zone.short}" domain="${swat.domain.short}" />

        <antform title="DataPower Service Project Cloner ">
            Provide project information .
            <fileSelectionProperty label="Select source project directory : "
                                   property="clone.source.dir"
                                   directoryChooser="true"
                                   tooltip="Location of the project that should be cloned." />
            <textProperty label="Target project name prefix : "
                          property="service.project.prefix"
                          tooltip="New project name prefix. The below service name will be added." />
            <textProperty label="New service name : "
                          property="clone.target.service.name"
                          tooltip="This is the name according to the service.name property." />
            <fileSelectionProperty label="Select base project directory : "
                                   property="clone.target.base.dir"
                                   directoryChooser="true"
                                   tooltip="Base directory of the new project." />
            <controlbar>
                <button label="Cancel" type="cancel" target="cancel" />
                <button label="Ok" type="ok" />
            </controlbar>
        </antform>

        <fail unless="service.project.prefix" message="new project prefix property not set" />
        <fail unless="clone.target.service.name" message="new service name property not set" />

        <property name="clone.target.project.name" value="${service.project.prefix}-${clone.target.service.name}" />
        <property name="clone.target.dir" value="${clone.target.base.dir}/${clone.target.project.name}" />
        <basename file="${clone.source.dir}" property="clone.source.project.name" />

        <property file="${clone.source.dir}/build.properties" />
        <fail unless="service.name"
              message="Could not read service.name property from ${clone.source.dir}/build.properties" />

        <echo message="Copying source content..." />
        <copy todir="${clone.target.dir}" filtering="true" verbose="true" overwrite="false">
            <fileset dir="${clone.source.dir}" defaultexcludes="false">
                <include name="**/*.*" />
                <include name="**/.cvsignore" />
                <include name="**/.gitignore" />
                <include name="**/Jenkinsfile" />
                <exclude name="**/CVS" />
                <exclude name="**/CVS/**" />
                <exclude name="**/.svn" />
                <exclude name="**/.svn/**" />
                <exclude name="**/.git" />
                <exclude name="**/.git/**" />
                <exclude name="**/target/**" />
                <exclude name="**/dist" />
                <exclude name="**/dist/**/*" />
                <exclude name="**/in-work/**/*" />
                <exclude name="**/tmp/**/*" />
                <exclude name="**/*.tmp" />
                <exclude name="**/*.bak" />
                <exclude name="**/master/**/*.*" />
                <exclude name="**/xcfg/**/*.*" />
            </fileset>
            <filterchain>
                <tokenfilter>
                    <replaceregex pattern="^zone.name=.*$" replace="zone.name=${swat.zone.short}" />
                    <replaceregex pattern="^service.summary=(.*)$" replace="service.summary=Clone of \1" />
                </tokenfilter>
            </filterchain>
        </copy>

        <echo message="Renaming master/xcfg files by replacing pattern '${service.name}' with '${clone.target.service.name}' ..." />
        <copy todir="${clone.target.dir}" filtering="false" verbose="true" overwrite="false">
            <fileset dir="${clone.source.dir}">
                <include name="**/master/**/${service.name}/**" />
                <include name="**/xcfg/**" />
                <exclude name="**/dist/**" />
                <exclude name="**/target/**" />
            </fileset>
            <regexpmapper from="(.*)${service.name}(.*)" to="\1${clone.target.service.name}\2" />
        </copy>

        <echo message="Renaming version file by replacing pattern '${service.object.name}' with '${clone.target.service.object.name}' ..." />
        <copy todir="${clone.target.dir}" filtering="false" verbose="true" overwrite="false">
            <fileset dir="${clone.source.dir}">
                <include name="**/master/**/${service.object.name}-version.*" />
                <exclude name="**/dist/**" />
            </fileset>
            <regexpmapper from="(.*)${service.object.name}(.*)" to="\1${clone.target.service.object.name}\2" />
        </copy>

        <echo message="Copy remaining master files ..." />
        <copy todir="${clone.target.dir}" filtering="false" verbose="true" overwrite="false">
            <fileset dir="${clone.source.dir}">
                <include name="**/master/**" />
                <exclude name="**/dist/**" />
            </fileset>
        </copy>

        <echo message="Replacing service.name in build.properties ..." />
        <replaceregexp byline="true">
            <regexp pattern="(.*)${service.name}(.*)" />
            <substitution expression="\1${clone.target.service.name}\2" />
            <fileset dir="${clone.target.dir}">
                <include name="build.properties" />
            </fileset>
        </replaceregexp>

        <echo message="Replacing project name in .project, build.xml, pom.xml, Jenkinsfile ..." />
        <replaceregexp byline="true">
            <regexp pattern="${clone.source.project.name}" />
            <substitution expression="${clone.target.project.name}" />
            <fileset dir="${clone.target.dir}">
                <include name=".project" />
                <include name="build.xml" />
                <include name="pom.xml" />
                <include name="Jenkinsfile" />
            </fileset>
        </replaceregexp>

        <propertyfile file="${clone.target.dir}/build.properties"
                      comment="TODO: change service object name and summary!">
            <entry key="service.name" value="${clone.target.service.name}" />
        </propertyfile>
    </target>

    <macrodef name="seed-svc-template-macro">
        <attribute name="filterfile" default="${basedir}/service.properties" />
        <sequential>

            <property file="@{filterfile}" />

            <filterset id="content.filter" onmissingfiltersfile="ignore">
                <filter token="swat.customer" value="${swat.customer}" />
                <filtersfile file="@{filterfile}" />
            </filterset>

            <if>
                <isset property="swat.domain.mvn.aggregator" />
                <then>
                    <echo message="Maven multi-module setup has been configured: ${swat.domain.mvn.aggregator}" />
                    <property name="service.target.dir"
                              value="${swat.dp.customer.home}/${swat.domain.mvn.aggregator}/${service.project.name}" />
                </then>
                <else>
                    <property name="service.target.dir" value="${swat.dp.customer.home}/${service.project.name}" />
                </else>
            </if>

            <echo message="Copying filtered content..." />
            <copy todir="${service.target.dir}" filtering="true" verbose="true" overwrite="true">
                <fileset dir="content">
                    <exclude name="config/export/service-export-file-list.xml" />
                    <exclude name="config/export/service-export-object-list.xml" />
                    <exclude name="master/common/**/service-object-name.html" />
                    <exclude name="master/common/**/service-object-name-version.*" />
                </fileset>
                <filterset refid="content.filter" />
            </copy>
            <echo message="Copying unfiltered content..." />
            <copy todir="${service.target.dir}" filtering="false" verbose="true" overwrite="true">
                <fileset dir="content" defaultexcludes="false">
                    <include name="config/export/service-export-file-list.xml" />
                    <include name="config/export/service-export-object-list.xml" />
                    <include name="master/common/local/info/service-object-name.html" />
                    <include name="**/.gitignore" />
                </fileset>
            </copy>
            <copy todir="${service.target.dir}" filtering="false" verbose="true" overwrite="true">
                <fileset dir="content">
                    <include name="master/common/**/service-object-name.html" />
                    <include name="master/common/**/service-object-name-version.*" />
                </fileset>
                <regexpmapper from="(.*)service-object-name(.*)" to="\1${service.object.name}\2" />
            </copy>

            <echo message="Renaming resources..." />
            <move file="${service.target.dir}/config/env.properties"
                  tofile="${service.target.dir}/config/${swat.env.short}.properties" />
            <move file="${service.target.dir}/master/common/local/service"
                  tofile="${service.target.dir}/master/common/local/${service.name}"
                  failonerror="false" />
            <move file="${service.target.dir}/master/common/local/services/service"
                  tofile="${service.target.dir}/master/common/local/services/${service.name}"
                  failonerror="false" />
        </sequential>
    </macrodef>

    <macrodef name="seed-version-file-macro">
        <attribute name="filterfile" default="${basedir}/service.properties" />
        <sequential>

            <property file="@{filterfile}" />

            <filterset id="content.filter" onmissingfiltersfile="ignore">
                <filter token="swat.customer" value="${swat.customer}" />
                <filtersfile file="@{filterfile}" />
            </filterset>

            <if>
                <isset property="swat.domain.mvn.aggregator" />
                <then>
                    <echo message="Maven multi-module setup has been configured: ${swat.domain.mvn.aggregator}" />
                    <property name="service.target.dir"
                              value="${swat.dp.customer.home}/${swat.domain.mvn.aggregator}/${service.project.name}" />
                </then>
                <else>
                    <property name="service.target.dir" value="${swat.dp.customer.home}/${service.project.name}" />
                </else>
            </if>

            <echo message="Copying version file ..." />
            <copy todir="${service.target.dir}" filtering="false" verbose="true" overwrite="true">
                <fileset dir="content">
                    <include name="master/common/**/service.object.name-version.*" />
                </fileset>
                <regexpmapper from="(.*)service\.object\.name(.*)" to="\1${service.object.name}\2" />
            </copy>

        </sequential>
    </macrodef>

</project>


text:
#include <QtGui/QApplication>
#include "population.h"

Population::Population(const QString &country, QObject *parent)
    : QObject(parent), http(this)
{
    // Connect the HTTP transport's responseReady() signal.
    connect(&http, SIGNAL(responseReady()), this, SLOT(getResponse()));

    // Construct a method request message.
    QtSoapMessage request;

    // Set the method and add one argument.
    request.setMethod("getPopulation", "http://www.abundanttech.com/WebServices/Population");
    request.addMethodArgument("strCountry", "", country);

    // Submit the request the the web service.
    http.setHost("www.abundanttech.com");
    http.setAction("http://www.abundanttech.com/WebServices/Population/getPopulation");
    http.submitRequest(request, "/WebServices/Population/population.asmx");

    qDebug("Looking up population of %s...", country.toLatin1().constData());
}

void Population::getResponse()
{
    // Get a reference to the response message.
    const QtSoapMessage &message = http.getResponse();

    // Check if the response is a SOAP Fault message
    if (message.isFault()) {
        qDebug("Error: %s", message.faultString().value().toString().toLatin1().constData());
    }
    else {
        // Get the return value, and print the result.
        const QtSoapType &response = message.returnValue();
        qDebug("%s has a population of %s (last updated at %s)",
               response["Country"].value().toString().toLatin1().constData(),
               response["Pop"].value().toString().toLatin1().constData(),
               response["Date"].value().toString().toLatin1().constData());
    }
    qApp->quit();
}


text:
SYNONYM

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

#### Published in
Edinburgh J. Bot. 60:552. 2004

#### Original name
null

### Remarks
null


text:
{{#markdown}}
```html
<div class="off-canvas-wrap">
  <div class="inner-wrap">

    <a class="left-off-canvas-toggle" >Menu</a>

    <!-- Off Canvas Menu -->
    <aside class="left-off-canvas-menu">
    	<!-- whatever you want goes here -->
    	<ul>
      	<li><a href="#">Item 1</a></li>
        ...
	    </ul>
    </aside>

    <!-- main content goes here -->
    <p>Set in the year 0 F.E. ("Foundation Era"), The Psychohistorians opens on Trantor, the capital of the 12,000-year-old Galactic Empire. Though the empire appears stable and powerful, it is slowly decaying in ways that parallel the decline of the Western Roman Empire. Hari Seldon, a mathematician and psychologist, has developed psychohistory, a new field of science and psychology that equates all possibilities in large societies to mathematics, allowing for the prediction of future events.</p>

  <!-- close the off-canvas menu -->
  <a class="exit-off-canvas"></a>

  </div>
</div>
```
{{/markdown}}


text:
/*
 * Highlights a chunk of the diff.
 *
 * This will create and move four border elements around the chunk. We use
 * these border elements instead of setting a border since few browsers
 * render borders on <tbody> tags the same, and give us few options for
 * styling.
 *
 * In practice, there's only ever one highlighter on a page at a time.
 */
RB.ChunkHighlighterView = Backbone.View.extend({
    className: 'diff-highlight',

    /*
     * Initializes the highlighter.
     */
    initialize: function() {
        this._resetState();
        this._$pageContainer = null;
        this._width = null;

        _.bindAll(this, '_updatePosition');
    },

    /*
     * Renders the highlighter to the page.
     *
     * This will create all the border elements and compute any variables
     * we want to keep around for further rendering.
     */
    render: function() {
        $(window).on('resize.' + this.cid, _.throttle(_.bind(function() {
            this._recalcGlobalSizes();
            this._resetChunkSizes();

            /*
             * Other operations may impact the size of the page, so do this
             * after all resize handlers have been called.
             */
            _.defer(this._updatePosition);
        }, this)));

        this._$pageContainer = $('#page-container');

        this._recalcGlobalSizes();

        return this;
    },

    /*
     * Removes the highlighter from the page and disconnects all events.
     */
    remove: function() {
        _super(this).remove.call(this);

        $(window).off(this.cid);
    },

    /*
     * Highlights a new chunk element.
     *
     * The borders will surround the chunk element and track its position
     * and size as the page updates.
     */
    highlight: function($chunk) {
        this._resetState();

        this._$chunk = $chunk;
        this._$chunkContainer = $chunk.parents('.diff-container');

        this._updatePosition();
    },

    /*
     * Resets the calculated state for a chunk.
     */
    _resetState: function() {
        this._$chunk = null;
        this._$chunkContainer = null;

        this._resetChunkSizes();
    },

    /*
     * Resets the calculated offsets and sizes for a chunk.
     */
    _resetChunkSizes: function() {
        this._top = null;
        this._height = null;
    },

    /*
     * Re-calculates the common sizes for the page container.
     */
    _recalcGlobalSizes: function() {
        var oldWidth = this.$el.width();

        this._width = this._$pageContainer.outerWidth();

        this.$el.css({
            left: -this._$pageContainer.getExtents('p', 'l'),
            width: oldWidth
        });
    },

    /*
     * Updates the position of the borders, based on the chunk dimensions.
     */
    _updatePosition: function(e) {
        var chunkPos;

        if (e && e.target && e.target !== window &&
            !e.target.getElementsByTagName) {
            /*
             * This is not a container. It might be a text node.
             * Ignore it.
             */
            return;
        }

        if (this._$chunk === null) {
            return;
        }

        if (this._top === null) {
            chunkPos = this._$chunk.position();

            if (!chunkPos) {
                /* The diff isn't yet loaded. */
                return;
            }

            this._top = Math.floor(chunkPos.top +
                                   this._$chunkContainer.position().top);
        }

        if (this._height === null) {
            this._height = this._$chunk.outerHeight();
        }

        if (this._top === this._oldTop &&
            this._width === this._oldWidth &&
            this._height === this._oldHeight) {
            /* The position and size haven't actually changed. */
            return;
        }

        this.$el.css({
            top: this._top,
            height: this._height + 1,  // Compensate for the tbody border below.
            width: this._width
        });

        this._oldTop = this._top;
        this._oldWidth = this._width;
        this._oldHeight = this._height;
    }
});


text:
package org.apache.hadoop.hbase.master;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HRegionLocation;
import org.apache.hadoop.hbase.MetaMockingUtil;
import org.apache.hadoop.hbase.MetaTableAccessor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.RegionInfo;
import org.apache.hadoop.hbase.client.RegionLocator;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.master.assignment.AssignmentManager;
import org.apache.hadoop.hbase.testclassification.MasterTests;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.PairOfSameType;
import org.apache.hadoop.hbase.util.Threads;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TestName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Category({MasterTests.class, MediumTests.class})
public class TestCatalogJanitorInMemoryStates {

  @ClassRule
  public static final HBaseClassTestRule CLASS_RULE =
      HBaseClassTestRule.forClass(TestCatalogJanitorInMemoryStates.class);

  private static final Logger LOG = LoggerFactory.getLogger(TestCatalogJanitorInMemoryStates.class);
  @Rule public final TestName name = new TestName();
  protected final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
  private static byte [] ROW = Bytes.toBytes("testRow");
  private static byte [] FAMILY = Bytes.toBytes("testFamily");
  private static byte [] QUALIFIER = Bytes.toBytes("testQualifier");
  private static byte [] VALUE = Bytes.toBytes("testValue");

  /**
   * @throws java.lang.Exception
   */
  @BeforeClass
  public static void setUpBeforeClass() throws Exception {
    Configuration conf = TEST_UTIL.getConfiguration();
    TEST_UTIL.startMiniCluster(1);
  }

  /**
   * @throws java.lang.Exception
   */
  @AfterClass
  public static void tearDownAfterClass() throws Exception {
    TEST_UTIL.shutdownMiniCluster();
  }

  /**
   * Test clearing a split parent from memory.
   */
  @Test
  public void testInMemoryParentCleanup()
      throws IOException, InterruptedException, ExecutionException {
    final AssignmentManager am = TEST_UTIL.getHBaseCluster().getMaster().getAssignmentManager();
    final ServerManager sm = TEST_UTIL.getHBaseCluster().getMaster().getServerManager();
    final CatalogJanitor janitor = TEST_UTIL.getHBaseCluster().getMaster().getCatalogJanitor();

    Admin admin = TEST_UTIL.getAdmin();
    admin.catalogJanitorSwitch(false);

    final TableName tableName = TableName.valueOf(name.getMethodName());
    Table t = TEST_UTIL.createTable(tableName, FAMILY);
    int rowCount = TEST_UTIL.loadTable(t, FAMILY, false);

    RegionLocator locator = TEST_UTIL.getConnection().getRegionLocator(tableName);
    List<HRegionLocation> allRegionLocations = locator.getAllRegionLocations();

    // We need to create a valid split with daughter regions
    HRegionLocation parent = allRegionLocations.get(0);
    List<HRegionLocation> daughters = splitRegion(parent.getRegion());
    LOG.info("Parent region: " + parent);
    LOG.info("Daughter regions: " + daughters);
    assertNotNull("Should have found daughter regions for " + parent, daughters);

    assertTrue("Parent region should exist in RegionStates",
        am.getRegionStates().isRegionInRegionStates(parent.getRegion()));
    assertTrue("Parent region should exist in ServerManager",
        sm.isRegionInServerManagerStates(parent.getRegion()));

    // clean the parent
    Result r = MetaMockingUtil.getMetaTableRowResult(parent.getRegion(), null,
        daughters.get(0).getRegion(), daughters.get(1).getRegion());
    janitor.cleanParent(parent.getRegion(), r);
    assertFalse("Parent region should have been removed from RegionStates",
        am.getRegionStates().isRegionInRegionStates(parent.getRegion()));
    assertFalse("Parent region should have been removed from ServerManager",
        sm.isRegionInServerManagerStates(parent.getRegion()));

  }

  /**
   * Splits a region
   * @param t Region to split.
   * @return List of region locations
   */
  private List<HRegionLocation> splitRegion(final RegionInfo r)
      throws IOException, InterruptedException, ExecutionException {
    List<HRegionLocation> locations = new ArrayList<>();
    // Split this table in two.
    Admin admin = TEST_UTIL.getAdmin();
    Connection connection = TEST_UTIL.getConnection();
    admin.splitRegionAsync(r.getEncodedNameAsBytes()).get();
    admin.close();
    PairOfSameType<RegionInfo> regions = waitOnDaughters(r);
    if (regions != null) {
      try (RegionLocator rl = connection.getRegionLocator(r.getTable())) {
        locations.add(rl.getRegionLocation(regions.getFirst().getEncodedNameAsBytes()));
        locations.add(rl.getRegionLocation(regions.getSecond().getEncodedNameAsBytes()));
      }
      return locations;
    }
    return locations;
  }

  /*
   * Wait on region split. May return because we waited long enough on the split
   * and it didn't happen.  Caller should check.
   * @param r
   * @return Daughter regions; caller needs to check table actually split.
   */
  private PairOfSameType<RegionInfo> waitOnDaughters(final RegionInfo r)
      throws IOException {
    long start = System.currentTimeMillis();
    PairOfSameType<RegionInfo> pair = null;
    try (Connection conn = ConnectionFactory.createConnection(TEST_UTIL.getConfiguration());
         Table metaTable = conn.getTable(TableName.META_TABLE_NAME)) {
      Result result = null;
      RegionInfo region = null;
      while ((System.currentTimeMillis() - start) < 60000) {
        result = metaTable.get(new Get(r.getRegionName()));
        if (result == null) {
          break;
        }
        region = MetaTableAccessor.getRegionInfo(result);
        if (region.isSplitParent()) {
          LOG.debug(region.toString() + " IS a parent!");
          pair = MetaTableAccessor.getDaughterRegions(result);
          break;
        }
        Threads.sleep(100);
      }

      if (pair.getFirst() == null || pair.getSecond() == null) {
        throw new IOException("Failed to get daughters, for parent region: " + r);
      }
      return pair;
    }
  }
}


text:
Guardian
========

An authentication framework for use with Elixir applications.

Guardian is based on similar ideas to Warden and Omniauth but is re-imagined
for modern systems where Elixir manages the authentication requirements.

Guardian remains a functional system. It integrates with Plug, but can be used
outside of it. If you're implementing a TCP/UDP protocol directly, or want to
utilize your authentication via channels, Guardian is your friend.

The core currency of authentication in Guardian is JWT. You can use the JWT to
authenticate web endpoints, channels, and TCP sockets and it can contain any
authenticated assertions that the issuer wants to include.

## Installation

Guardian relies on [Joken](https://github.com/bryanjos/joken). You'll need to
install and configure Joken for your application.

Add Guardian to your application

mix.deps

```elixir
defp deps do
  [
    # ...
    {:guardian, "~> 0.6.2"}
    # ...
  ]
end
```

config.exs

```elixir
config :joken, config_module: Guardian.JWT

config :guardian, Guardian,
  issuer: "MyApp",
  ttl: { 30, :days },
  verify_issuer: true,
  secret_key: <guardian secret key>,
  serializer: MyApp.GuardianSerializer
```

## Serializer

The serializer knows how to encode and decode your resource into and out of the
token. A simple serializer:

```elixir
defmodule MyApp.GuardianSerializer do
  @behaviour Guardian.Serializer

  alias MyApp.Repo
  alias MyApp.User

  def for_token(user = %User{}), do: { :ok, "User:#{user.id}" }
  def for_token(_), do: { :error, "Unknown resource type" }

  def from_token("User:" <> id), do: { :ok, Repo.get(User, id) }
  def from_token(_), do: { :error, "Unknown resource type" }
end
```

## Plug API

Guardian ships with some plugs to help integrate into your application.

### Guardian.Plug.VerifySession

Looks for a token in the session. Useful for browser sessions.
If one is not found, this does nothing.

### Guardian.Plug.VerifyHeader

Looks for a token in the Authorization header. Useful for apis.
If one is not found, this does nothing.

### Guardian.Plug.EnsureAuthenticated

Looks for a previously verified token. If one is found, continues, otherwise it
will call the `:on_failure` function.

When you ensure a session, you must declare an error handler. This can be done
as part of a pipeline or inside a pheonix controller.

```elixir
defmodule MyApp.MyController do
  use MyApp.Web, :controller

  plug Guardian.Plug.EnsureAuthenticated, on_failure: { MyApp.MyController, :unauthenticated }
end
```

The failure function must receive the connection, and the connection params.

### Guardian.Plug.EnsurePermissions

Looks for a previously verified token. If one is found, confirms that all listed
permissions are present in the token. If not, the failure function is called.

```elixir
defmodule MyApp.MyController do
  use MyApp.Web, :controller

  plug Guardian.Plug.EnsurePermissions, on_failure: { MyApp.MyController, :forbidden }, default: [:read, :write]
end
```

### Pipelines

These plugs can be used to construct pipelines in Phoenix.

```elixir
pipeline :browser_session do
  plug Guardian.Plug.VerifySession
  plug Guardian.Plug.LoadResource
end

pipeline :api do
  plug :accepts, ["json"]
  plug Guardian.Plug.VerifyHeader
  plug Guardian.Plug.LoadResource
end

scope "/", MyApp do
  pipe_through [:browser, :browser_session] # Use the default browser stack
  # ...
end

scope "/api", MyApp.Api do
  pipe_through [:api] # Use the default browser stack
end
```

From here, you can either EnsureAuthenticated in your pipeline, or on a per-controller basis.

```elixir
defmodule MyApp.MyController do
  use MyApp.Web, :controller

  plug Guardian.Plug.EnsureAuthenticated, on_failure: { MyApp.MyHandler, :unauthenticated }
end
```

## Sign in and Sign out

It's up to you how you verify the claims to encode into the token Guardian uses.
As an example, here's the important parts of a SessionController

```elixir
defmodule MyApp.SessionController do
  use MyApp.Web, :controller

  alias MyApp.User
  alias MyApp.UserQuery

  plug :scrub_params, "user" when action in [:create]

  def create(conn, params = %{}) do
    conn
    |> put_flash(:info, "Logged in.")
    |> Guardian.Plug.sign_in(verified_user) # verify your logged in resource
    |> redirect(to: user_path(conn, :index))
  end

  def delete(conn, _params) do
    Guardian.Plug.sign_out(conn)
    |> put_flash(:info, "Logged out successfully.")
    |> redirect(to: "/")
  end
end
```

### Guardian.Plug.sign\_in

You can sign in with a resource (that the serializer knows about)

```elixir
Guardian.Plug.sign_in(conn, user) # Sign in with the default storage
```

```elixir
Guardian.Plug.sign_in(conn, user, :token, claims)  # give some claims to use for the token jwt

Guardian.Plug.sign_in(conn, user, :token, key: :secret)  # create a token in the :secret location
```

To attach permissions to the token, use the `:perms` key and pass it a map.
Note. To add permissions, you should configure them in your guardian config.

```elixir
Guardian.Plug.sign_in(conn, user, :token, perms: %{ default: [:read, :write], admin: [:all] })

Guardian.Plug.sign_in(conn, user, :token, key: :secret, perms: %{ default: [:read, :write], admin: [:all]})  # create a token in the :secret location
```

### Guardian.Plug.sign\_out

```elixir
Guardian.Plug.sign_out(conn) # Sign out everything (clear session)
```

```elixir
Guardian.Plug.sign_out(conn, :secret) # Clear the token and associated user from the 'secret' location
```

### Current resource, token and claims

Access to the current resource, token and claims is useful. Note, you'll need to
have run the VerifySession/Header for token and claim access, and LoadResource to access the resource.

```elixir
Guardian.Plug.claims(conn) # Access the claims in the default location
Guardian.Plug.claims(conn, :secret) # Access the claims in the secret location
```

```elixir
Guardian.Plug.current_token(conn) # access the token in the default location
Guardian.Plug.current_token(conn, :secret) # access the token in the secret location
```

For the resource

```elixir
Guardian.Plug.current_resource(conn) # Access the loaded resource in the default location
Guardian.Plug.current_resource(conn, :secret) # Access the loaded resource in the secret location
```

### Without Plug

There are many instances where Plug might not be in use. Channels, and raw
sockets for e.g. If you need to do things your own way.

```elixir
{ :ok, jwt, encoded_claims } = Guardian.encode_and_sign(resource, <token_type>, claims_map)
```

This will give you a new JWT to use with the claims ready to go.
The token type is encoded into the JWT as the 'aud' field and is intended to be
used as the _type_ of token.

```elixir
{ :ok, jwt, full_claims } = Guardian.encode_and_sign(resource, :token)
```

Add some permissions

```elixir
{ :ok, jwt, full_claims } = Guardian.encode_and_sign(resource, :token, perms: %{ default: [:read, :write], admin: Guardian.Permissions.max})
```

Currently suggested token types are:

* `"token"` - Use for API or CORS access. These are basic tokens.

You can also customize the claims you're asserting.

```elixir
claims = Guardian.Claims.app_claims
         |> Dict.put(:some_claim, some_value)
         |> Guardian.Claims.ttl({3, :days})

{ :ok, jwt, full_claims } = Guardian.encode_and_sign(resource, :token, claims)
```

To verify the token:

```elixir
case Guardian.decode_and_verify(jwt) do
  { :ok, claims } -> do_things_with_claims(claims)
  { :error, reason } -> do_things_with_an_error(reason)
end
```

Accessing the resource from a set of claims:

```elixir
case Guardian.serializer.from_token(claims.sub) do
  { :ok, resource } -> do_things_with_resource(resource)
  { :error, reason } -> do_things_without_a_resource(reason)
end
```

### Permissions

Guardian includes support for including permissions. Declare your permissions in
your configuration. All known permissions must be included.

```elixir
config :guardian, Guardian,
       permissions: %{
         default: [:read, :write],
         admin: [:dashboard, :reconcile]
       }
```

JWTs need to be kept reasonably small so that they can fit into an authorization
header. For this reason, permissions are encded as bits (an integer) in the
token. You can have up to 64 permissions per set, and as many sets as you like.
In the example above, we have the `:default` set, and the `:admin` set.

The bit value of the permissions within a set is determined by it's position in
the config.

```elixir
# Fetch permissions from the claims map

Guardian.Permissions.from_claims(claims, :default)
Guardian.Permissions.from_claims(claims, :admin)

# Check the permissions for all present

Guardian.Permissions.from_claims(claims, :default) |> Guardian.Permissions.all?([:read, :write], :default)
Guardian.Permissions.from_claims(claims, :admin) |> Guardian.Permissions.all?([:reconcile], :admin)

# Check for any permissions
Guardian.Permissions.from_claims(claims, :default) |> Guardian.Permissions.any?([:read, :write], :default)
Guardian.Permissions.from_claims(claims, :admin) |> Guardian.Permissions.any?([:reconcile, :dashboard], :admin)
```

You can use a plug to ensure permissions are present. See Guardian.Plug.EnsurePermissions

#### Setting permissions

When you generate (or sign in) a token, you can inject permissions into it.

```elixir
Guardian.encode_and_sign(resource, :token, perms: %{ admin: [:dashaboard], default: Guardian.Permissions.max}})
```

By setting a permission using Guardian.Permission.max you're setting all the bits, so even if new permissions are added, they will be set.

You can similarly pass a `:perms` key to the sign\_in method to have the
permissions encoded into the token.

### Hooks

Often you'll need to take action on some event within the lifecycle of
authentication. Recording logins etc. Guardian provides hooks to allow you to do
this. Use the Guardian.Hooks module to setup. Default implementations are
available for all callbacks.

```elixir
defmodule MyApp.GuardianHooks do
  use Guardian.Hooks

  def after_sign_in(conn, location) do
    user = Guardian.Plug.current_resource(conn, location)
    IO.puts("SIGNED INTO LOCATION WITH: #{user.email}")
    conn
  end
end
```

By default, JWTs are not tracked. This means that after 'logout' the token can
still be used if it is stored outside the system. This is because Guardian does
not track tokens and only interprates them live. When using Guardian in this
way, be sure you consider the expiry time as this is one of the few options you
have to make your tokens invalid.

If you want more control over this you should implement a hook that tracks the
tokens in some storage. When calling `Guardian.revoke!` (called automatically
with sign\_out).

To keep track of all tokens and ensure they're revoked on sign out you can use
[GuardianDb](https://github.com/hassox/guardian_db). This is a simple
Guardian.Hooks module that implements database integration.

    config :guardian, Guardian,
           hooks: GuardianDb

    config :guardian_db, GuardianDb, repo: MyRepo

Configure Guardian to know which module to use.

```elixir
config :guardian, Guardian,
       hooks: MyApp.GuardianHooks,
       #…
```

### Phoenix Channels

Guardian uses JWTs to make the integration of authentication management as
seamless as possible. Channel integration is part of that.

```elixir
defmodule MyApp.UsersChannel do
  use Phoenix.Channel
  use Guardian.Channel

  def join(_room, %{ claims: claims, resource: resource }, socket) do
    { :ok, %{ message: "Joined" }, socket }
  end

  def join(room, _, socket) do
    { :error,  :authentication_required }
  end

  def handle_in("ping", _payload, socket) do
    user = Guardian.Channel.current_resource(socket)
    broadcast socket, "pong", %{ message: "pong", from: user.email }
    { :noreply, socket }
  end
end
```

Guardian picks up on joins that have been made and automatically verifies the
token and makes available the claims and resource making the request.

```javascript
let socket = new Socket("/ws");
socket.connect();
let guardianToken = jQuery('meta[name="guardian_token"]').attr('content');
let chan = socket.chan("pings", { guardian_token: guardianToken });
```

How to get the tokens onto the page?

```eex
<%= if Guardian.Plug.current_token(@conn) do %>
  <meta name='guardian_token' content="<%= Guardian.Plug.current_token(@conn) %>">
<% end %>
```

# Acknowledgements

Many thanks to Sonny Scroggin (@scrogson) for the name Guardian and great
feedback to get up and running.

### TODO

- [x] Flexible serialization
- [x] Integration with Plug
- [x] Basic integrations like raw TCP
- [x] Sevice2Service credentials. That is, pass the authentication results through many downstream requests.
- [-] Create a "csrf" token type that ensures that CSRF protection is included
- [x] Integration with Phoenix channels
- [x] Integrated permission sets
- [x] Hooks into the authentication cycle
- [x] Revoke tokens
- [ ] Refresh tokens
- [ ] Two-factor authentication
- [ ] Single sign-in
- [ ] Device specific signing (can be implemented via custom claims atm)


text:
package yuku.readingplanconverter;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class RpaInput {

	public static class Rpa {

		public Map<String, String> infos;
		public List<int[]> plans;

		private void addInfo(String k, String v) {
			if (infos == null) infos = new LinkedHashMap<String, String>();
			infos.put(k, v);
		}

		private void addPlans(int[] aris) {
			if (plans == null) plans = new ArrayList<int[]>();
			plans.add(aris);
		}
	}

	public Rpa parse(String inputFile) {
		Rpa brp = new Rpa();

		try {
			Scanner scanner = new Scanner(new File(inputFile), "utf-8");

			while (scanner.hasNextLine()) {
				String line = scanner.nextLine();
				String[] splits = line.split("\t", -1);

				if ("info".equals(splits[0])) {
					brp.addInfo(splits[1], splits[2]);
				} else if ("plan".equals(splits[0])) {
					int count = Integer.parseInt(splits[1]) * 2;
					int[] aris = new int[count];
					for (int i = 0; i < count; i++) {
						aris[i] = Integer.parseInt(splits[i + 2]);
					}
					brp.addPlans(aris);
				}
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		return brp;
	}
}


text:
package de.sambalmueslie.quiz_game;

import de.sambalmueslie.quiz_game.controller.GameFinishedReason;
import javafx.fxml.FXML;
import javafx.scene.control.Label;

public class FinishedWindowController {
	/**
	 * Setup.
	 *
	 * @param reason
	 *            the {@link GameFinishedReason}
	 * @param prize
	 *            the prize
	 */
	public void setup(final GameFinishedReason reason, final int prize) {
		if (reason == null) return;
		switch (reason) {
		case WON:
		case EXIT:
			result.setText("Herzlichen Glückwunsch");
			break;
		case TIMEOUT:
			result.setText("Leider zu langsam");
			break;
		case WRONG_ANSWER:
			result.setText("Leider falsche Antwort");
			break;
		default:
			break;
		}
		win.setText("Ihr Gewinn beträgt: " + prize + " €");
	}

	@FXML
	private Label result;
	@FXML
	private Label win;
}


text:
package org.jgroups.blocks;

import org.jgroups.*;
import org.jgroups.blocks.mux.MuxRpcDispatcher;
import org.jgroups.blocks.mux.MuxUpHandler;
import org.jgroups.tests.ChannelTestBase;
import org.jgroups.util.Rsp;
import org.jgroups.util.Util;
import org.testng.Assert;
import org.testng.annotations.*;

import java.util.Map;

/**
 * @author Paul Ferraro
 */
@Test(groups={Global.STACK_DEPENDENT},singleThreaded=true)
public class MuxRpcDispatcherTest extends ChannelTestBase {

    private JChannel[]        channels = null;
    private RpcDispatcher[]   dispatchers  = null;
    private RpcDispatcher[][] muxDispatchers = null;

    @BeforeMethod
    void setUp() throws Exception {
        channels       = new JChannel[2];
        dispatchers    = new RpcDispatcher[2];
        muxDispatchers = new RpcDispatcher[2][2];

        channels[0] = createChannel(true, 2, "A");
        channels[1] = createChannel(channels[0], "B");

        for (int i = 0; i < dispatchers.length; i++) {

            dispatchers[i] = new RpcDispatcher(channels[i], new Server("dispatcher[" + i + "]"));

            channels[i].setUpHandler(new MuxUpHandler(dispatchers[i].getProtocolAdapter()));

            for (int j = 0; j < muxDispatchers[i].length; j++) {
                muxDispatchers[i][j] = new MuxRpcDispatcher((short) j, channels[i], null, null, new Server("muxDispatcher[" + i + "][" + j + "]"));
            }

            channels[i].connect("MuxRpcDispatcherTest");

            Util.sleep(1000);
        }

        Util.waitUntilAllChannelsHaveSameSize(10000, 1000, channels);
    }

    @AfterMethod
    void tearDown() throws Exception {
        for (int i = 0; i < dispatchers.length; ++i) {
            dispatchers[i].stop();
            for (int j = 0; j < muxDispatchers[i].length; ++j)
                muxDispatchers[i][j].stop();
        }
        for(JChannel ch: channels)
            Util.close(ch);
    }

    public void testUnicastRPCs() throws Exception {
        RequestOptions options=RequestOptions.SYNC().setTimeout(30000);
        MethodCall method = new MethodCall("getName", new Object[0], new Class[0]);

        final Address address = channels[1].getAddress();

        // Validate normal dispatchers
        Object response = dispatchers[0].callRemoteMethod(address, method, options);
        Assert.assertEquals(response, "dispatcher[1]");

        // Validate muxed dispatchers
        for (int j = 0; j < muxDispatchers[0].length; ++j) {
            response = muxDispatchers[0][j].callRemoteMethod(address, method, options);
            Assert.assertEquals(response, "muxDispatcher[1][" + j + "]");
        }

        // Filter testing is disabled for now pending filter improvements in JGroups 3

        // Validate muxed rpc dispatchers w/filter

        RspFilter filter = new RspFilter() {
            @Override public boolean isAcceptable(Object response, Address sender) {return !sender.equals(address);}
            @Override public boolean needMoreResponses() {return true;}
        };

        response = muxDispatchers[0][0].callRemoteMethod(address, method, RequestOptions.SYNC().setRspFilter(filter));
        assert response == null;

        // Validate stopped mux dispatcher response is auto-filtered
        muxDispatchers[1][0].stop();

        try {
            response = muxDispatchers[0][0].callRemoteMethod(address, method, RequestOptions.SYNC().setTimeout(2000).setRspFilter(null));
            assert false : "should have run into a TimeoutException";
        }
        catch(TimeoutException timeout) {
            System.out.println("received " + timeout + " - as expected");
        }

        Assert.assertNull(response);

        // Validate restarted mux dispatcher functions normally
        muxDispatchers[1][0].start();

        response = muxDispatchers[0][0].callRemoteMethod(address, method, RequestOptions.SYNC().setRspFilter(null));

        Assert.assertEquals(response, "muxDispatcher[1][0]");
    }

    public void testMulticastRPCs() throws Exception {
        MethodCall method = new MethodCall("getName", new Object[0], new Class[0]);
        RequestOptions options=RequestOptions.SYNC().setTimeout(30000);

        // Validate normal dispatchers
        Map<Address, Rsp<String>> responses = dispatchers[0].callRemoteMethods(null, method, options);
        Assert.assertEquals(responses.size(), 2);

        for (int i = 0; i < dispatchers.length; ++i)
            verifyResponse(responses, channels[i], "dispatcher[" + i + "]");

        // Validate muxed dispatchers
        for (int j = 0; j < muxDispatchers[0].length; ++j) {
            responses = muxDispatchers[0][j].callRemoteMethods(null, method, options);
            Assert.assertEquals(responses.size(), 2);
            for (int i = 0; i < dispatchers.length; ++i)
                verifyResponse(responses, channels[i], "muxDispatcher[" + i + "][" + j + "]");
        }

        // Validate muxed rpc dispatchers w/filter
        final Address address = channels[0].getAddress();

        RspFilter filter = new RspFilter() {
            public boolean isAcceptable(Object response, Address sender) {
                return !sender.equals(address);
            }
            public boolean needMoreResponses() {
                return true;
            }
        };

        responses = muxDispatchers[0][0].callRemoteMethods(null,method,RequestOptions.SYNC().setTimeout(30000).setRspFilter(filter));

        Assert.assertEquals(responses.size(), 2);
        verifyResponse(responses, channels[0], null);
        verifyResponse(responses, channels[1], "muxDispatcher[1][0]");

        // Validate stopped mux dispatcher response is auto-filtered
        muxDispatchers[1][0].stop();

        responses = muxDispatchers[0][0].callRemoteMethods(null, method, options.setTimeout(2000));
        Assert.assertEquals(responses.size(), 2);
        verifyResponse(responses, channels[0], "muxDispatcher[0][0]");
        verifyResponse(responses, channels[1], null);

        // Validate stopped mux dispatcher response is auto-filtered and custom filter is applied
        responses = muxDispatchers[0][0].callRemoteMethods(null,method,RequestOptions.SYNC().setTimeout(2000).setRspFilter(filter));

        Assert.assertEquals(responses.size(), 2);
        verifyResponse(responses, channels[0], null);
        verifyResponse(responses, channels[1], null);

        // Validate restarted mux dispatcher functions normally
        muxDispatchers[1][0].start();

        responses = muxDispatchers[0][0].callRemoteMethods(null, method, options.setTimeout(30000));

        Assert.assertEquals(responses.size(), 2);
        verifyResponse(responses, channels[0], "muxDispatcher[0][0]");
        verifyResponse(responses, channels[1], "muxDispatcher[1][0]");
    }

    private static void verifyResponse(Map<Address,Rsp<String>> responses, Channel channel, Object expected) {
        Rsp<?> response = responses.get(channel.getAddress());
        String address = channel.getAddress().toString();
        Assert.assertNotNull(response, address);
        Assert.assertFalse(response.wasSuspected(), address);
        if (expected != null) {
            Assert.assertTrue(response.wasReceived(), address);
            Assert.assertEquals(response.getValue(), expected, address);
        } else {
            Assert.assertFalse(response.wasReceived(), address);
        }
    }

    public static class Server {
        private final String name;

        public Server(String name) {
            this.name = name;
        }

        public String getName() {
            return this.name;
        }
    }
}


text:
#ifndef ALITRACKLETALG_H
#define ALITRACKLETALG_H

//_________________________________________________________________________
//
//        Implementation of the ITS-SPD trackleter class
//   Clone version of the AliITSMultReconstructor class (October 2010)
//   that can be used in an AliAnalysisTask
//
//_________________________________________________________________________
#include "AliTrackleter.h"

class TBits;
class TTree;
class TH1F;
class TH2F;
class AliITSDetTypeRec;
class AliITSgeom;
class AliESDEvent;
class AliESDtrack;
class AliVertex;
class AliESDVertex;
class AliMultiplicity;

class AliTrackletAlg : public AliTrackleter
{
public:
  //
  enum {kClTh,kClPh,kClZ,kClMC0,kClMC1,kClMC2,kClNPar};
  enum {kTrTheta,kTrPhi,kTrDPhi,kTrDTheta,kTrLab1,kTrLab2,kClID1,kClID2,kTrNPar};
  enum {kSCTh,kSCPh,kSCLab,kSCID,kSCNPar};
  enum {kITSTPC,kITSSAP,kITSTPCBit=BIT(kITSTPC),kITSSAPBit=BIT(kITSSAP)}; // RS
  AliTrackletAlg();
  virtual ~AliTrackletAlg();

  void Reconstruct(AliESDEvent* esd, TTree* treeRP);
  void Reconstruct(TTree* tree, Float_t* vtx, Float_t* vtxRes);   // old reconstructor invocation
  void FindTracklets(const Float_t* vtx);
  void LoadClusterFiredChips(TTree* tree);
  void FlagClustersInOverlapRegions(Int_t ic1,Int_t ic2);
  void FlagTrackClusters(Int_t id);
  void FlagIfSecondary(AliESDtrack* track, const AliVertex* vtx);
  void FlagV0s(const AliESDVertex *vtx);
  void ProcessESDTracks();
  Bool_t  CanBeElectron(const AliESDtrack* trc) const;

  void CreateMultiplicityObject();
  //
  void SetPhiWindow(Float_t w=0.08) {fPhiWindow=w;}
  void SetThetaWindow(Float_t w=0.025) {fThetaWindow=w;}
  void SetPhiShift(Float_t w=0.0045) {fPhiShift=w;}
  void SetRemoveClustersFromOverlaps(Bool_t b = kFALSE) {fRemoveClustersFromOverlaps = b;}
  void SetPhiOverlapCut(Float_t w=0.005) {fPhiOverlapCut=w;}
  void SetZetaOverlapCut(Float_t w=0.05) {fZetaOverlapCut=w;}
  void SetPhiRotationAngle(Float_t w=0.0) {fPhiRotationAngle=w;}

  Int_t GetNClustersLayer1() const {return fNClustersLay1;}
  Int_t GetNClustersLayer2() const {return fNClustersLay2;}
  Int_t GetNTracklets() const {return fNTracklets;}
  Int_t GetNSingleClusters() const {return fNSingleCluster;}
  Short_t GetNFiredChips(Int_t layer) const {return fNFiredChips[layer];}

  Float_t* GetClusterLayer1(Int_t n) {return &fClustersLay1[n*kClNPar];}
  Float_t* GetClusterLayer2(Int_t n) {return &fClustersLay2[n*kClNPar];}

  Float_t* GetTracklet(Int_t n) {return fTracklets[n];}
  Float_t* GetCluster(Int_t n) {return fSClusters[n];}

  void SetHistOn(Bool_t b=kFALSE) {fHistOn=b;}
  void SaveHists();

  AliITSDetTypeRec *GetDetTypeRec() const {return fDetTypeRec;}
  void SetDetTypeRec(AliITSDetTypeRec *ptr){fDetTypeRec = ptr;}
  //
  void    SetCutPxDrSPDin(Float_t v=0.1)             { fCutPxDrSPDin = v;}
  void    SetCutPxDrSPDout(Float_t v=0.15)           { fCutPxDrSPDout = v;}
  void    SetCutPxDz(Float_t v=0.2)                  { fCutPxDz = v;}
  void    SetCutDCArz(Float_t v=0.5)                 { fCutDCArz = v;}
  void    SetCutMinElectronProbTPC(Float_t v=0.5)    { fCutMinElectronProbTPC = v;}
  void    SetCutMinElectronProbESD(Float_t v=0.1)    { fCutMinElectronProbESD = v;}
  void    SetCutMinP(Float_t v=0.05)                 { fCutMinP = v;}
  void    SetCutMinRGamma(Float_t v=2.)              { fCutMinRGamma = v;}
  void    SetCutMinRK0(Float_t v=1.)                 { fCutMinRK0 = v;}
  void    SetCutMinPointAngle(Float_t v=0.98)        { fCutMinPointAngle = v;}
  void    SetCutMaxDCADauther(Float_t v=0.5)         { fCutMaxDCADauther = v;}
  void    SetCutMassGamma(Float_t v=0.03)            { fCutMassGamma = v;}
  void    SetCutMassGammaNSigma(Float_t v=5.)        { fCutMassGammaNSigma = v;}
  void    SetCutMassK0(Float_t v=0.03)               { fCutMassK0 = v;}
  void    SetCutMassK0NSigma(Float_t v=5.)           { fCutMassK0NSigma = v;}
  void    SetCutChi2cGamma(Float_t v=2.)             { fCutChi2cGamma = v;}
  void    SetCutChi2cK0(Float_t v=2.)                { fCutChi2cK0 = v;}
  void    SetCutGammaSFromDecay(Float_t v=-10.)      { fCutGammaSFromDecay = v;}
  void    SetCutK0SFromDecay(Float_t v=-10.)         { fCutK0SFromDecay = v;}
  void    SetCutMaxDCA(Float_t v=1.)                 { fCutMaxDCA = v;}
  //
  Float_t GetCutPxDrSPDin()                    const {return fCutPxDrSPDin;}
  Float_t GetCutPxDrSPDout()                   const {return fCutPxDrSPDout;}
  Float_t GetCutPxDz()                         const {return fCutPxDz;}
  Float_t GetCutDCArz()                        const {return fCutDCArz;}
  Float_t GetCutMinElectronProbTPC()           const {return fCutMinElectronProbTPC;}
  Float_t GetCutMinElectronProbESD()           const {return fCutMinElectronProbESD;}
  Float_t GetCutMinP()                         const {return fCutMinP;}
  Float_t GetCutMinRGamma()                    const {return fCutMinRGamma;}
  Float_t GetCutMinRK0()                       const {return fCutMinRK0;}
  Float_t GetCutMinPointAngle()                const {return fCutMinPointAngle;}
  Float_t GetCutMaxDCADauther()                const {return fCutMaxDCADauther;}
  Float_t GetCutMassGamma()                    const {return fCutMassGamma;}
  Float_t GetCutMassGammaNSigma()              const {return fCutMassGammaNSigma;}
  Float_t GetCutMassK0()                       const {return fCutMassK0;}
  Float_t GetCutMassK0NSigma()                 const {return fCutMassK0NSigma;}
  Float_t GetCutChi2cGamma()                   const {return fCutChi2cGamma;}
  Float_t GetCutChi2cK0()                      const {return fCutChi2cK0;}
  Float_t GetCutGammaSFromDecay()              const {return fCutGammaSFromDecay;}
  Float_t GetCutK0SFromDecay()                 const {return fCutK0SFromDecay;}
  Float_t GetCutMaxDCA()                       const {return fCutMaxDCA;}

  //
protected:
  AliTrackletAlg(const AliTrackletAlg& mr);
  AliTrackletAlg& operator=(const AliTrackletAlg& mr);
  AliITSDetTypeRec* fDetTypeRec;            //! pointer to DetTypeRec
  AliESDEvent*      fESDEvent;              //! pointer to ESD event
  TTree*            fTreeRP;                //! ITS recpoints

  UInt_t*       fUsedClusLay1;               // RS: flag of clusters usage in ESD tracks: 0=unused, else ID+1 in word0=TPC/ITS+ITSSA, word1=ITSSA_Pure
  UInt_t*       fUsedClusLay2;               // RS: flag of clusters usage in ESD tracks: 0=unused, else ID+1 word0=TPC/ITS+ITSSA, word1=ITSSA_Pure

  Float_t*      fClustersLay1;               // clusters in the 1st layer of ITS
  Float_t*      fClustersLay2;               // clusters in the 2nd layer of ITS
  Int_t*        fDetectorIndexClustersLay1;  // module index for clusters 1st ITS layer
  Int_t*        fDetectorIndexClustersLay2;  // module index for clusters 2nd ITS layer
  Bool_t*       fOverlapFlagClustersLay1;    // flag for clusters in the overlap regions 1st ITS layer
  Bool_t*       fOverlapFlagClustersLay2;    // flag for clusters in the overlap regions 2nd ITS layer

  Float_t**     fTracklets;            // tracklets
  Float_t**     fSClusters;            // single clusters (unassociated)

  Int_t         fNClustersLay1;        // Number of clusters (Layer1)
  Int_t         fNClustersLay2;        // Number of clusters (Layer2)
  Int_t         fNTracklets;           // Number of tracklets
  Int_t         fNSingleCluster;       // Number of unassociated clusters
  Short_t       fNFiredChips[2];       // Number of fired chips in the two SPD layers
  //
  // Following members are set via AliITSRecoParam
  //
  Float_t       fPhiWindow;                    // Search window in phi
  Float_t       fThetaWindow;                  // Search window in theta
  Float_t       fPhiShift;                     // Phi shift reference value (at 0.5 T)
  Bool_t        fRemoveClustersFromOverlaps;   // Option to skip clusters in the overlaps
  Float_t       fPhiOverlapCut;                // Fiducial window in phi for overlap cut
  Float_t       fZetaOverlapCut;               // Fiducial window in eta for overlap cut
  Float_t       fPhiRotationAngle;             // Angle to rotate the inner layer cluster for combinatorial reco only

  // cuts for secondaries identification
  Float_t       fCutPxDrSPDin;                 // max P*DR for primaries involving at least 1 SPD
  Float_t       fCutPxDrSPDout;                // max P*DR for primaries not involving any SPD
  Float_t       fCutPxDz;                      // max P*DZ for primaries
  Float_t       fCutDCArz;                     // max DR or DZ for primares
  //
  // cuts for flagging tracks in V0s
  Float_t       fCutMinElectronProbTPC;     // min probability for e+/e- PID involving TPC
  Float_t       fCutMinElectronProbESD;     // min probability for e+/e- PID not involving TPC
  //
  Float_t       fCutMinP;                   // min P of V0
  Float_t       fCutMinRGamma;              // min transv. distance from ESDVertex to V0 for gammas
  Float_t       fCutMinRK0;                 // min transv. distance from ESDVertex to V0 for K0s
  Float_t       fCutMinPointAngle;          // min pointing angle cosine
  Float_t       fCutMaxDCADauther;          // max DCA of daughters at V0
  Float_t       fCutMassGamma;              // max gamma mass
  Float_t       fCutMassGammaNSigma;        // max standard deviations from 0 for gamma
  Float_t       fCutMassK0;                 // max K0 mass difference from PGD value
  Float_t       fCutMassK0NSigma;           // max standard deviations for K0 mass from PDG value
  Float_t       fCutChi2cGamma;             // max constrained chi2 cut for gammas
  Float_t       fCutChi2cK0;                // max constrained chi2 cut for K0s
  Float_t       fCutGammaSFromDecay;        // min path*P for gammas
  Float_t       fCutK0SFromDecay;           // min path*P for K0s
  Float_t       fCutMaxDCA;                 // max DCA for V0 at ESD vertex

  Bool_t        fHistOn;               // Option to define and fill the histograms

  TH1F*         fhClustersDPhiAcc;     // Phi2 - Phi1 for tracklets
  TH1F*         fhClustersDThetaAcc;   // Theta2 - Theta1 for tracklets
  TH1F*         fhClustersDPhiAll;     // Phi2 - Phi1 all the combinations
  TH1F*         fhClustersDThetaAll;   // Theta2 - Theta1 all the combinations

  TH2F*         fhDPhiVsDThetaAll;     // 2D plot for all the combinations
  TH2F*         fhDPhiVsDThetaAcc;     // same plot for tracklets

  TH1F*         fhetaTracklets;        // Pseudorapidity distr. for tracklets
  TH1F*         fhphiTracklets;        // Azimuthal (Phi) distr. for tracklets
  TH1F*         fhetaClustersLay1;     // Pseudorapidity distr. for Clusters L. 1
  TH1F*         fhphiClustersLay1;     // Azimuthal (Phi) distr. for Clusters L. 1

  void LoadClusterArrays(TTree* tree);

  ClassDef(AliTrackletAlg,1)
};

#endif


text:
set -e

cd cmd/hardhat

CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o hardhat .


text: sudo apt remove rustc


text:
namespace blink {

void DetailsMarkerPainter::paint(const PaintInfo& paintInfo, const LayoutPoint& paintOffset)
{
    if (paintInfo.phase != PaintPhaseForeground || m_layoutDetailsMarker.style()->visibility() != VISIBLE) {
        BlockPainter(m_layoutDetailsMarker).paint(paintInfo, paintOffset);
        return;
    }

    LayoutPoint boxOrigin(paintOffset + m_layoutDetailsMarker.location());
    LayoutRect overflowRect(m_layoutDetailsMarker.visualOverflowRect());
    overflowRect.moveBy(boxOrigin);

    if (!paintInfo.rect.intersects(pixelSnappedIntRect(overflowRect)))
        return;

    LayoutObjectDrawingRecorder renderDrawingRecorder(*paintInfo.context, m_layoutDetailsMarker, paintInfo.phase, overflowRect);
    if (renderDrawingRecorder.canUseCachedDrawing())
        return;

    const Color color(m_layoutDetailsMarker.resolveColor(CSSPropertyColor));
    paintInfo.context->setStrokeColor(color);
    paintInfo.context->setStrokeStyle(SolidStroke);
    paintInfo.context->setStrokeThickness(1.0f);
    paintInfo.context->setFillColor(color);

    boxOrigin.move(m_layoutDetailsMarker.borderLeft() + m_layoutDetailsMarker.paddingLeft(), m_layoutDetailsMarker.borderTop() + m_layoutDetailsMarker.paddingTop());
    paintInfo.context->fillPath(getPath(boxOrigin));
}

static Path createPath(const FloatPoint* path)
{
    Path result;
    result.moveTo(FloatPoint(path[0].x(), path[0].y()));
    for (int i = 1; i < 4; ++i)
        result.addLineTo(FloatPoint(path[i].x(), path[i].y()));
    return result;
}

static Path createDownArrowPath()
{
    FloatPoint points[4] = { FloatPoint(0.0f, 0.07f), FloatPoint(0.5f, 0.93f), FloatPoint(1.0f, 0.07f), FloatPoint(0.0f, 0.07f) };
    return createPath(points);
}

static Path createUpArrowPath()
{
    FloatPoint points[4] = { FloatPoint(0.0f, 0.93f), FloatPoint(0.5f, 0.07f), FloatPoint(1.0f, 0.93f), FloatPoint(0.0f, 0.93f) };
    return createPath(points);
}

static Path createLeftArrowPath()
{
    FloatPoint points[4] = { FloatPoint(1.0f, 0.0f), FloatPoint(0.14f, 0.5f), FloatPoint(1.0f, 1.0f), FloatPoint(1.0f, 0.0f) };
    return createPath(points);
}

static Path createRightArrowPath()
{
    FloatPoint points[4] = { FloatPoint(0.0f, 0.0f), FloatPoint(0.86f, 0.5f), FloatPoint(0.0f, 1.0f), FloatPoint(0.0f, 0.0f) };
    return createPath(points);
}

Path DetailsMarkerPainter::getCanonicalPath() const
{
    switch (m_layoutDetailsMarker.orientation()) {
    case LayoutDetailsMarker::Left: return createLeftArrowPath();
    case LayoutDetailsMarker::Right: return createRightArrowPath();
    case LayoutDetailsMarker::Up: return createUpArrowPath();
    case LayoutDetailsMarker::Down: return createDownArrowPath();
    }

    return Path();
}

Path DetailsMarkerPainter::getPath(const LayoutPoint& origin) const
{
    Path result = getCanonicalPath();
    result.transform(AffineTransform().scale(m_layoutDetailsMarker.contentWidth().toFloat(), m_layoutDetailsMarker.contentHeight().toFloat()));
    result.translate(FloatSize(origin.x().toFloat(), origin.y().toFloat()));
    return result;
}

} // namespace paint


text:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe CommitAttribute do
  before(:each) do
    @valid_attributes = {
      :name => "value for name",
      :value => "value for value"
    }
  end

  it "should create a new instance given valid attributes" do
    CommitAttribute.create!(@valid_attributes)
  end
end


text:
import Data.Int

data NumberOrBool =
    Numba Int8
  | BoolyBool Bool
  deriving (Eq, Show)


text:
import * as assert from 'assert';
import 'mocha';
import VikingRecord from 'viking/record';
import { hasMany, belongsTo } from 'viking/record/associations';
import * as Errors from 'viking/errors';
import {extendClass} from 'viking/support/class';

describe('Viking.Record::associations', () => {

    describe('cyclical association', () => {
        class Requirement extends VikingRecord {
            static associations = [ hasMany(Phase) ]
        }

        function Phase () {
          var NewTarget = Object.getPrototypeOf(this).constructor;
          return Reflect.construct(VikingRecord, arguments, NewTarget);
        }

        extendClass('Phase', VikingRecord, Phase, {
          associations: [ belongsTo(Requirement) ]
        });

        it("load association", function(done) {
            let model = new Requirement({id: 24});
            model.phases.load().then((models) => {
                assert.equal(models.length, 1);
                assert.ok(models[0] instanceof Phase);
                assert.equal(models[0].readAttribute('id'), 24);
                assert.equal(models[0].readAttribute('name'), 'Viking');
            }).then(done, done);
            this.withRequest('GET', '/phases', { params: {where: {requirement_id: 24}, order: {id: 'desc'}} }, (xhr) => {
                xhr.respond(200, {}, '[{"id": 24, "name": "Viking"}]');
            });
        });

        it("clone association", function (done) {
            let model = new Requirement({id: 24});
            model.phases.load().then(models => {
                const clone = model.phases.clone()
                assert.ok(clone.loaded);
                assert.notEqual(clone.listenerId, model.phases.listenerId)
                assert.notEqual(clone.target[0].cid, model.phases.target[0].cid)
                assert.equal(clone.target[0].readAttribute('id'), model.phases.target[0].readAttribute('id'))
            }).then(done, done)

            this.withRequest('GET', '/phases', { params: {where: {requirement_id: 24}, order: {id: 'desc'}} }, (xhr) => {
                xhr.respond(200, {}, '[{"id": 24, "name": "Viking"}]');
            });
        })

    });

});


text:
package ninja.template;

import java.io.IOException;
import java.io.OutputStream;

import javax.inject.Singleton;

import ninja.Context;
import ninja.Result;
import ninja.utils.ResponseStreams;

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

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.google.inject.Inject;

@Singleton
public class TemplateEngineXml implements TemplateEngine {

    private static final Logger logger = LoggerFactory.getLogger(TemplateEngineXml.class);

    private final XmlMapper xmlMapper;

    @Inject
    public TemplateEngineXml(XmlMapper xmlMapper) {

        this.xmlMapper = xmlMapper;
    }

    @Override
    public void invoke(Context context, Result result) {

        ResponseStreams responseStreams = context.finalizeHeaders(result);

        try (OutputStream outputStream = responseStreams.getOutputStream()) {

                xmlMapper.writeValue(outputStream, result.getRenderable());

        } catch (IOException e) {

            logger.error("Error while rendering json", e);
        }

    }

    @Override
    public String getContentType() {
        return Result.APPLICATION_XML;
    }

    @Override
    public String getSuffixOfTemplatingEngine() {
        // intentionally returns null...
        return null;
    }
}


text:
package com.shanbay.app;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.shanbay.http.APIClient;
import com.shanbay.http.ModelResponseException;
import com.shanbay.util.LogUtils;

public class BaseFragment<T extends APIClient> extends Fragment
{
  protected final String TAG = LogUtils.makeLogTag(getClass());
  protected T mClient;

  protected void d(String paramString)
  {
    LogUtils.LOGD(this.TAG, paramString);
  }

  protected void d(String paramString, Throwable paramThrowable)
  {
    LogUtils.LOGD(this.TAG, paramString, paramThrowable);
  }

  public void dismissProgressDialog()
  {
    if (isAttached())
      getBaseActivity().dismissProgressDialog();
  }

  public View findViewById(int paramInt)
  {
    if (getView() != null)
      return getView().findViewById(paramInt);
    if (isAttached())
      return getActivity().findViewById(paramInt);
    return null;
  }

  public BaseActivity<T> getBaseActivity()
  {
    return (BaseActivity)getActivity();
  }

  public boolean handleCommonException(ModelResponseException paramModelResponseException)
  {
    if (isAttached())
      return getBaseActivity().handleCommonException(paramModelResponseException);
    return false;
  }

  public boolean isAttached()
  {
    return (getActivity() != null) && (!getActivity().isFinishing());
  }

  public boolean isCommonException(ModelResponseException paramModelResponseException)
  {
    if (isAttached())
      return getBaseActivity().isCommonException(paramModelResponseException);
    return false;
  }

  protected boolean isRenderable()
  {
    return true;
  }

  public void onActivityCreated(Bundle paramBundle)
  {
    super.onActivityCreated(paramBundle);
    this.mClient = getBaseActivity().getClient();
    d(LogUtils.getMethodName());
  }

  public void onAttach(Activity paramActivity)
  {
    if (!(paramActivity instanceof BaseActivity))
      throw new ClassCastException(this + " must attach to BaseActivity");
    super.onAttach(paramActivity);
    d(LogUtils.getMethodName());
  }

  public void onCreate(Bundle paramBundle)
  {
    super.onCreate(paramBundle);
    d(LogUtils.getMethodName());
  }

  public View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle)
  {
    d(LogUtils.getMethodName());
    return super.onCreateView(paramLayoutInflater, paramViewGroup, paramBundle);
  }

  public void onDestroy()
  {
    super.onDestroy();
    d(LogUtils.getMethodName());
  }

  public void onDestroyView()
  {
    super.onDestroyView();
    d(LogUtils.getMethodName());
  }

  public void onDetach()
  {
    super.onDetach();
    this.mClient = null;
    d(LogUtils.getMethodName());
  }

  public void onPause()
  {
    super.onPause();
    d(LogUtils.getMethodName());
  }

  public void onResume()
  {
    super.onResume();
    d(LogUtils.getMethodName());
  }

  public void onStart()
  {
    super.onStart();
    d(LogUtils.getMethodName());
  }

  public void onStop()
  {
    super.onStop();
    d(LogUtils.getMethodName());
  }

  public void onViewStateRestored(Bundle paramBundle)
  {
    super.onViewStateRestored(paramBundle);
    d(LogUtils.getMethodName());
  }

  public final void render()
  {
    render(getView());
  }

  protected final void render(View view)
  {
    if (isRenderable())
    {
      renderInternal();
      if (view != null)
        view.setVisibility(View.VISIBLE);
    }else{
      if (view != null)
        view.setVisibility(View.INVISIBLE);
    }
  }

  protected void renderInternal()
  {
  }

  public void showProgressDialog()
  {
    if (isAttached())
      getBaseActivity().showProgressDialog();
  }

  public void showToast(int paramInt)
  {
    if (isAttached())
      getBaseActivity().showToast(paramInt);
  }

  public void showToast(String paramString)
  {
    if (isAttached())
      getBaseActivity().showToast(paramString);
  }
}


text:
var data = require("../public/data.json");

exports.updatePref = function(req, res) {
    console.log("hi");
    data["preferences"][0] = {
        "pref" : req.query.pref,
        "odometer" : req.query.odometer,
        "expectedmpg" : req.query.expectedmpg,
        "oil" : req.query.oil
    };
    console.log(data["preferences"][0]);
    res.render('preferences', data);
};


text:
CSRC=lidar-client.c log.c wrapper.c

# the executable program that you want to build
TARGET=lidar-client

# define the following line to enable debugging output
#CPPFLAGS+=-DENABLE_DEBUG

CFLAGS+=-O
# CFLAGS+=-Wall -Werror
# CFLAGS+=-Wno-unused-function

LDFLAGS+=-lm

OBJS=$(CSRC:.c=.o)

.PHONY: all clean world

all:: $(TARGET)

$(TARGET):: $(OBJS)
	$(LINK.c) -o $@ $^

clean::
	rm -f *.o $(TARGET)

world:: clean all