text:
<?php

namespace Onyx\Service;

class Soap{
    const SESSION_NAME = 'OnyxSoapService';
    const SESSION_AUTHENTICATED_FIELD = 'authenticatedUser';

    private $authenticatedUser=NULL;

    /**
     * @var \Doctrine\ORM\EntityManager
     */
    protected $em;

    public function __construct($em=NULL) {
        $this->em = $em;
        //$this->em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\DebugStack());
    }

    /**
     * Verifies the authentication
     *
     * @param string $sessionId With the session ID to validate
     * @throws \SoapFault if the request was not authenticated
     */
    public function verifyAuthentication($sessionId=NULL){
        if(!empty($sessionId)):
            session_id($sessionId);
            if(((function_exists("session_status") && session_status() !== PHP_SESSION_ACTIVE) || session_id() === "") && session_start()):
                if(isset($_SESSION[self::SESSION_AUTHENTICATED_FIELD])):
                    $this->authenticatedUser = $_SESSION[self::SESSION_AUTHENTICATED_FIELD];
                endif;
            endif;
        endif;
        if(empty($this->authenticatedUser)):
            throw new \SoapFault("Failed to authenticate. The request must be authenticated with a soap header to authenticate the request.", 412);
        endif;
    }

    /**
     * Verifies the entity manager presence
     *
     * @throws \SoapFault if no entity manager was found
     */
    private function verifyEntityManager(){
        if(is_null($this->em)):
            throw new \SoapFault("No entity manager found.", 500);
        endif;
    }

    /**
     * Copy the properties from an object to another
     *
     * @param object $origin
     * @param object $destination
     * @return object $destination
     */
    private static function copyProperties($origin, $destination){
        foreach($origin as $property => $value):
            $destination->$property = $value;
        endforeach;
        return $destination;
    }

    /**
     * Create a QueryBuilder with the data from $dataObject
     *
     * @param string $entity with the entity name reference
     * @param object $dataObject with the entity data to copy
     * @param string $prefix with the prefix for the fields
     * @return \Doctrine\ORM\QueryBuilder instance
     */
    private function createQbFromObject($entity, $dataObject, $prefix=NULL){
        $qb = $this->em->createQueryBuilder();
        $qb->update($entity, $prefix);
        foreach($dataObject as $property=>$value):
            if(isset($value)):
                $qb->set((!empty($prefix)?"{$prefix}.":'').$property, $qb->expr()->literal($value));
            endif;
        endforeach;
        return $qb;
    }

    /**
     * Authenticates the SOAP request.
     *
     * @param \Onyx\Service\SoapAuthentication
     * @return string with the session ID
     */
    public function authenticate($login){
        if(!empty($login->username) && !empty($login->password)):
            if($login->username=="pass" && $login->password=="pass"):
                $this->authenticatedUser = $login->username;

                session_name(self::SESSION_NAME);
                if(session_start()):
                    $_SESSION[self::SESSION_AUTHENTICATED_FIELD] = $login->username;
                    return session_id();
                endif;
                return true;
            endif;
            throw new \SOAPFault("Incorrect username and or password.", 401);
        else:
            throw new \SOAPFault("Invalid username and password format. Values may not be empty and are case-sensitive.", 400);
        endif;
    }

    /**
     * Get a teacher by Fiscal Identification Number
     *
     * @param string $fin with the Fiscal Identification Number
     * @param string $sessionId with the optional session ID from the authenticate method
     * @return \Onyx\Entity\Docentes
     *
     * @uses \Onyx\Service\Soap::authenticate to authenticate the request
     * @uses \Onyx\Service\Soap::verifyEntityManager to check for entity manager
     */
    public function getTeacherByFin($fin, $sessionId=""){
        $this->verifyAuthentication($sessionId);
        $this->verifyEntityManager();

        return $this->em->getRepository("Onyx\Entity\Docentes")->findOneBy(array('nif' => $fin));
    }

    /**
     * Check if a teacher exists by Fiscal Identification Number
     *
     * @param \Onyx\Entity\Docentes $teacher with the teacher to check
     * @param string $sessionId with the optional session ID from the authenticate method
     * @return boolean true if it exists, false otherwise
     *
     * @uses \Onyx\Service\Soap::authenticate to authenticate the request
     * @uses \Onyx\Service\Soap::verifyEntityManager to check for entity manager
     */
    public function teacherExists($teacher, $sessionId=""){
        return (!is_null($this->getTeacherByFin($teacher->nif, $sessionId)));
    }

    /**
     * Insert a new teacher based on their FIN
     *
     * @param \Onyx\Entity\Docentes $teacher with the teacher data to insert
     * @param string $sessionId with the optional session ID from the authenticate method
     * @return boolean true if the operation was successfuly terminated, false otherwise
     *
     * @uses \Onyx\Service\Soap::authenticate to authenticate the request
     * @uses \Onyx\Service\Soap::verifyEntityManager to check for entity manager
     */
    public function insertTeacher($teacher, $sessionId=""){
        return $this->updateTeacher($teacher, $sessionId);
    }

    /**
     * Update a teacher data based on their FIN
     *
     * @param \Onyx\Entity\Docentes $teacher with the teacher data to update
     * @param string $sessionId with the optional session ID from the authenticate method
     * @return boolean true if the operation was successfuly terminated, false otherwise
     *
     * @uses \Onyx\Service\Soap::authenticate to authenticate the request
     * @uses \Onyx\Service\Soap::verifyEntityManager to check for entity manager
     */
    public function updateTeacher($teacher, $sessionId=""){
        $this->verifyAuthentication($sessionId);
        $this->verifyEntityManager();

        if(!$this->teacherExists($teacher, $sessionId)):
            // Insert
            $teacher = self::copyProperties($teacher, new \Onyx\Entity\Docentes());
            $this->em->persist($teacher);
            $this->em->flush();
            return $this->teacherExists($teacher, $sessionId);

        else:
            // Update
            $qb = $this->createQbFromObject('Onyx\Entity\Docentes', $teacher, 'd');
            $qb->where('d.nif = :identifier')->setParameter('identifier', $teacher->nif);
            return $qb->getQuery()->execute();
        endif;
        return false;
    }

    /**
     * Deletes a teacher based on their FIN
     *
     * @param \Onyx\Entity\Docentes $teacher with the teacher data to delete
     * @param string $sessionId with the optional session ID from the authenticate method
     * @return boolean true if the operation was successfuly terminated, false otherwise
     *
     * @uses \Onyx\Service\Soap::authenticate to authenticate the request
     * @uses \Onyx\Service\Soap::verifyEntityManager to check for entity manager
     */
    public function deleteTeacher($teacher, $sessionId=""){
        $this->verifyAuthentication($sessionId);
        $this->verifyEntityManager();

        if($this->teacherExists($teacher, $sessionId)):
            // Delete
            $qb = $this->em->createQueryBuilder()->delete('Onyx\Entity\Docentes', 'd');
            $qb->where('d.nif = :identifier')->setParameter('identifier', $teacher->nif);
            return $qb->getQuery()->execute();
        endif;
        return true;
    }

    /**
     * Get future course editions based on the current date
     *
     * @param string $sessionId with the optional session ID from the authenticate method
     * @return \Onyx\Entity\Edicaocursosemestreletivo[]
     *
     * @uses \Onyx\Service\Soap::authenticate to authenticate the request
     * @uses \Onyx\Service\Soap::verifyEntityManager to check for entity manager
     */
    public function getFutureCoursesEditions($sessionId=""){
        $this->verifyAuthentication($sessionId);
        $this->verifyEntityManager();

        try{

            $result = $this->em->createQueryBuilder()
            ->select('ecsl')
            ->distinct()
            ->from('Onyx\Entity\Edicaocursosemestreletivo', 'ecsl')
            ->where('ecsl.datainicio > CURRENT_DATE()')
            ->getQuery()
            ->setFetchMode('Onyx\Entity\Edicaocursosemestreletivo', 'codplanocursofk', \Doctrine\ORM\Mapping\ClassMetadataInfo::FETCH_EAGER)
            ->setFetchMode('Onyx\Entity\Edicaocursosemestreletivo', 'iddiretorcursoedicaofk', \Doctrine\ORM\Mapping\ClassMetadataInfo::FETCH_EAGER)
            ->execute();

            return $result;
        } catch (Exception $e){
            throw new \SOAPFault("Error occurred ".$e, 500);
        }

        return array();
    }

    /**
     * Get the curricular units associated with a course
     *
     * @param \Onyx\Entity\Planocurso $course with the codplanocurso with curricular units associated with
     * @param string $sessionId with the optional session ID from the authenticate method
     * @return \Onyx\Entity\Planounidcurr[]
     *
     * @uses \Onyx\Service\Soap::authenticate to authenticate the request
     * @uses \Onyx\Service\Soap::verifyEntityManager to check for entity manager
     */
    public function getCourseCurricularUnits($course, $sessionId=""){
        $this->verifyAuthentication($sessionId);
        $this->verifyEntityManager();

        try{
            return $this->em->createQueryBuilder()->select('puc')
            ->from('Onyx\Entity\Planounidcurr', 'puc')
            ->where('puc.codplanocursofk = :identifier')
            ->setParameter('identifier', $course->codplanocurso)
            ->getQuery()
            ->execute();

        } catch (Exception $e){
            throw new \SOAPFault("Error occurred".$e, 500);
        }

        return array();
    }

    /**
     * Get the curricular units associated with courses ids
     *
     * @param \Onyx\Entity\Planocurso[] $coursesIds with an array of Planocurso with codplanocurso defined
     * @param string $sessionId with the optional session ID from the authenticate method
     * @return \Onyx\Entity\Planounidcurr[]
     *
     * @uses \Onyx\Service\Soap::authenticate to authenticate the request
     * @uses \Onyx\Service\Soap::verifyEntityManager to check for entity manager
     */
    public function getCoursesCurricularUnits($courses, $sessionId=""){
        $this->verifyAuthentication($sessionId);
        $this->verifyEntityManager();

        $coursesIds = array();
        foreach ($courses as $course):
            $coursesIds[] = $course->codplanocurso;
        endforeach;

        try{
            return $this->em->createQueryBuilder()
            ->select('puc')
            ->from('Onyx\Entity\Planounidcurr', 'puc')
            ->where('puc.codplanocursofk IN (:ids)')
            ->orderBy('puc.nome', 'ASC')
            ->setParameter('ids', $coursesIds)
            ->getQuery()
            ->setFetchMode('Onyx\Entity\Planounidcurr', 'codplanocursofk', \Doctrine\ORM\Mapping\ClassMetadataInfo::FETCH_EAGER)
            ->execute();

        } catch (Exception $e){
            throw new \SOAPFault("Error occurred".$e, 500);
        }

        return array();
    }

    /**
     * Get the full data about the given curricular units associated with the given courses
     *
     * @param \Onyx\Entity\Planounidcurr[] $courseCurricularUnits with an array of Planounidcurr with codplanocursofk->codplanocurso and codplanounidcurr defined
     * @param string $sessionId with the optional session ID from the authenticate method
     * @return \Onyx\Entity\Planounidcurr[]
     *
     * @uses Onyx\Service\Soap::authenticate to authenticate the request
     * @uses Onyx\Service\Soap::verifyEntityManager to check for entity manager
     */
    public function getCurricularUnits($courseCurricularUnits, $sessionId=""){
        $this->verifyAuthentication($sessionId);
        $this->verifyEntityManager();
        try{
            $qb = $this->em->createQueryBuilder()
            ->select('puc')
            ->from('Onyx\Entity\Planounidcurr', 'puc')
            ->orderBy('puc.nome', 'ASC');

            $i=0;
            foreach ($courseCurricularUnits as $course):
                if(isset($course->codplanocursofk) && isset($course->codplanocursofk->codplanocurso) && isset($course->codplanounidcurr)):
                    if($i==0):
                        $qb->where("(puc.codplanocursofk = :cpc{$i} AND puc.codplanounidcurr = :cpuc{$i})");
                    else:
                        $qb->orWhere("(puc.codplanocursofk = :cpc{$i} AND puc.codplanounidcurr = :cpuc{$i})");
                    endif;
                    $qb->setParameter("cpc{$i}", $course->codplanocursofk->codplanocurso);
                    $qb->setParameter("cpuc{$i}", $course->codplanounidcurr);
                    $i++;
                endif;
            endforeach;

            return $qb->getQuery()
            ->setFetchMode('Onyx\Entity\Planounidcurr', 'codplanocursofk', \Doctrine\ORM\Mapping\ClassMetadataInfo::FETCH_EAGER)
            ->execute();

        } catch (Exception $e){
            throw new \SOAPFault("Error occurred".$e, 500);
        }

        return array();
    }

    /**
     * Set the teacher for given curricular units associated with given courses
     *
     * @param \Onyx\Entity\Edicaounidcurrdocentes[] $curricularUnits with an array of Planounidcurr with codplanocursofk->codplanocurso and codplanounidcurr defined
     * @param string $fin with the Fiscal Identification Number
     * @param string $sessionId with the optional session ID from the authenticate method
     * @return boolean true on sucess, false otherwise
     *
     * @uses Onyx\Service\Soap::authenticate to authenticate the request
     * @uses Onyx\Service\Soap::verifyEntityManager to check for entity manager
     */
    public function setTeacherCurricularUnits($curricularUnits, $fin="", $sessionId=""){

        $this->verifyAuthentication($sessionId);
        $this->verifyEntityManager();
        try{
            $result = true;

            $conn = $this->em->getConnection();
            foreach ($curricularUnits as $curricularUnit):

                // Get the teacher
                $teacher = isset($curricularUnit->iddocentefk->iddocente)?$curricularUnit->iddocentefk->iddocente:"";
                if(!empty($fin)):
                    $teacher = $this->em->getRepository("Onyx\Entity\Docentes")->findOneBy(array('nif' => $fin));
                    if(!is_null($teacher)):
                        $teacher = $teacher->getIddocente();
                    endif;
                endif;

                // Check the data
                if( empty($teacher) ||
                    empty($curricularUnit) ||
                    empty($curricularUnit->codplanocursofk2) ||
                    empty($curricularUnit->codplanocursofk2->codplanocursofk) ||
                    empty($curricularUnit->codplanocursofk2->codplanocursofk->codplanocurso) ||
                    empty($curricularUnit->codplanounidcurrfk) ||
                    empty($curricularUnit->codplanounidcurrfk->codplanounidcurr) ||
                    empty($curricularUnit->anoletivofk) ||
                    empty($curricularUnit->anoletivofk->anoletivo) ||
                    empty($curricularUnit->semestrefk) ||
                    empty($curricularUnit->semestrefk->semestre)
                ):
                    if($result):
                        $result = false;
                    endif;
                    continue;
                endif;

                // Prepare the data
                $courseId = $curricularUnit->codplanocursofk2->codplanocursofk->codplanocurso;
                $curricularUnitId = $curricularUnit->codplanounidcurrfk->codplanounidcurr;
                $year = $curricularUnit->anoletivofk->anoletivo;
                $semester = $curricularUnit->semestrefk->semestre;
                $percentage = "50"; // @ TODO: should be calculated here
                $semesterHours = ""; // @ TODO: should be calculated here
                $salary = ""; // @ TODO: should be calculated here
                $textualSalaryValue = ""; // @ TODO: should be calculated here

                // Check for similar data
                $existant = $this->em->getRepository("Onyx\Entity\Edicaounidcurrdocentes")->findOneBy(array(
                    'codplanocursofk2' => $courseId,
                    'codplanounidcurrfk' => $curricularUnitId,
                    'anoletivofk' => $year,
                    'semestrefk' => $semester,
                    'iddocentefk' => $teacher,
                    'percentagemservdocfk' => $percentage
                ));

                // If none found, insert it on the database
                if(is_null($existant)):
                    if($conn->insert('edicaoUnidCurrDocentes', array(
                    'codplanocursofk2' => $courseId,
                    'codplanounidcurrfk' => $curricularUnitId,
                    'anoletivofk' => $year,
                    'semestrefk' => $semester,
                    'iddocentefk' => $teacher,
                    'percentagemservdocfk' => $percentage,
                    'horassemestre' => $semesterHours,
                    'vencimento' => $salary,
                    'vencimentoextenso' => $textualSalaryValue
                    ))==0):
                        if($result):
                            $result = false;
                        endif;
                    endif;
                else:
                    // Update if needed
                endif;
            endforeach;

            return $result;

        } catch (Exception $e){
            throw new \SOAPFault("Error occurred".$e, 500);
        }

        return false;
    }
}


text:
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.structuralsearch.inspection;

import com.intellij.codeInspection.ex.LocalInspectionToolWrapper;
import com.intellij.structuralsearch.plugin.ui.Configuration;
import com.intellij.util.SmartList;
import org.jetbrains.annotations.NotNull;

import java.util.Collection;
import java.util.List;

/**
 * @author Bas Leijdekkers
 */
public class StructuralSearchInspectionToolWrapper extends LocalInspectionToolWrapper {

  public StructuralSearchInspectionToolWrapper(@NotNull Collection<@NotNull Configuration> configurations) {
    super(new StructuralSearchFakeInspection(configurations));
  }

  @NotNull
  @Override
  public LocalInspectionToolWrapper createCopy() {
    final StructuralSearchFakeInspection inspection = (StructuralSearchFakeInspection)getTool();
    final List<Configuration> copies = new SmartList<>();
    for (Configuration configuration : inspection.getConfigurations()) {
      copies.add(configuration.copy());
    }
    return new StructuralSearchInspectionToolWrapper(copies);
  }

  @NotNull
  @Override
  public String getDisplayName() {
    return getTool().getDisplayName();
  }

  @Override
  public boolean isEnabledByDefault() {
    return true;
  }

  @Override
  public String getID() {
    return getTool().getID();
  }

  @NotNull
  @Override
  public String getGroupDisplayName() {
    return getTool().getGroupDisplayName();
  }
}

redpajama_set_name: RedPajamaGithub


text:
.class public Landroid/support/v4/app/NotificationCompat$InboxStyle;
.super Landroid/support/v4/app/NotificationCompat$Style;
.source "NotificationCompat.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/support/v4/app/NotificationCompat;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x9
    name = "InboxStyle"
.end annotation

# instance fields
.field mTexts:Ljava/util/ArrayList;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/ArrayList",
            "<",
            "Ljava/lang/CharSequence;",
            ">;"
        }
    .end annotation
.end field

# direct methods
.method public constructor <init>()V
    .locals 1

    .prologue
    .line 723
    invoke-direct {p0}, Landroid/support/v4/app/NotificationCompat$Style;-><init>()V

    .line 721
    new-instance v0, Ljava/util/ArrayList;

    invoke-direct {v0}, Ljava/util/ArrayList;-><init>()V

    iput-object v0, p0, Landroid/support/v4/app/NotificationCompat$InboxStyle;->mTexts:Ljava/util/ArrayList;

    .line 724
    return-void
.end method

.method public constructor <init>(Landroid/support/v4/app/NotificationCompat$Builder;)V
    .locals 1
    .parameter "builder"

    .prologue
    .line 726
    invoke-direct {p0}, Landroid/support/v4/app/NotificationCompat$Style;-><init>()V

    .line 721
    new-instance v0, Ljava/util/ArrayList;

    invoke-direct {v0}, Ljava/util/ArrayList;-><init>()V

    iput-object v0, p0, Landroid/support/v4/app/NotificationCompat$InboxStyle;->mTexts:Ljava/util/ArrayList;

    .line 727
    invoke-virtual {p0, p1}, Landroid/support/v4/app/NotificationCompat$Style;->setBuilder(Landroid/support/v4/app/NotificationCompat$Builder;)V

    .line 728
    return-void
.end method

# virtual methods
.method public addLine(Ljava/lang/CharSequence;)Landroid/support/v4/app/NotificationCompat$InboxStyle;
    .locals 1
    .parameter "cs"

    .prologue
    .line 752
    iget-object v0, p0, Landroid/support/v4/app/NotificationCompat$InboxStyle;->mTexts:Ljava/util/ArrayList;

    invoke-virtual {v0, p1}, Ljava/util/ArrayList;->add(Ljava/lang/Object;)Z

    .line 753
    return-object p0
.end method

.method public setBigContentTitle(Ljava/lang/CharSequence;)Landroid/support/v4/app/NotificationCompat$InboxStyle;
    .locals 0
    .parameter "title"

    .prologue
    .line 735
    iput-object p1, p0, Landroid/support/v4/app/NotificationCompat$Style;->mBigContentTitle:Ljava/lang/CharSequence;

    .line 736
    return-object p0
.end method

.method public setSummaryText(Ljava/lang/CharSequence;)Landroid/support/v4/app/NotificationCompat$InboxStyle;
    .locals 1
    .parameter "cs"

    .prologue
    .line 743
    iput-object p1, p0, Landroid/support/v4/app/NotificationCompat$Style;->mSummaryText:Ljava/lang/CharSequence;

    .line 744
    const/4 v0, 0x1

    iput-boolean v0, p0, Landroid/support/v4/app/NotificationCompat$Style;->mSummaryTextSet:Z

    .line 745
    return-object p0
.end method


text:
<!DOCTYPE html>

    <title> Recursion Tracing Exercise: Two Successive Recursive calls</title>

        <var id="i"> randRange(1, 10)</var>
        <var id="ANS">Math.pow(2, Math.floor(Math.log2(i))+1) - 1</var>

Consider the following function:
            <textarea id="codeTextarea" name="codeTextarea">
void asterisksPrinter(int i) {
  if (i > 1) {
    asterisksPrinter(i / 2);
    asterisksPrinter(i / 2);
  }
  System.out.print("*");
}</textarea>
            How many asterisks are printed by the method call
            <tt>asterisksPrinter(<var>i</var>)</tt>?

            (Either write a number, or write "infinite recursion".)

<var>ANS</var>

 Note that there are two recursive calls.

Don't forget that the print statement will be exectued
              on the rollback for EACH of the recursive calls.


text:
package com.manning.nettyinaction.chapter14;

import java.util.Random;

public class MemcachedRequest {
    private static final Random rand = new Random();
    private final int magic = 0x80;//fixed so hard coded
    private final byte opCode; //the operation e.g. set or get
    private final String key; //the key to delete, get or set
    private final int flags = 0xdeadbeef; //random
    private final int expires; //0 = item never expires
    private final String body; //if opCode is set, the value
    private final int id = rand.nextInt(); //Opaque
    private final long cas = 0; //data version check...not used
    private final boolean hasExtras; //not all ops have extras

    public MemcachedRequest(byte opcode, String key, String value) {
        this.opCode = opcode;
        this.key = key;
        this.body = value == null ? "" : value;
        this.expires = 0;
        //only set command has extras in our example
        hasExtras = opcode == Opcode.SET;
    }

    public MemcachedRequest(byte opCode, String key) {
        this(opCode, key, null);
    }

    public int magic() {
        return magic;
    }

    public int opCode() {
        return opCode;
    }

    public String key() {
        return key;
    }

    public int flags() {
        return flags;
    }

    public int expires() {
        return expires;
    }

    public String body() {
        return body;
    }

    public int id() {
        return id;
    }

    public long cas() {
        return cas;
    }

    public boolean hasExtras() {
        return hasExtras;
    }
}


text:
dir=$(dirname $0)
gnomeVersion="$(expr "$(gnome-terminal --version)" : '.* \(.*[.].*[.].*\)$')"

# newGnome=1 if the gnome-terminal version >= 3.8
if [[ ("$(echo "$gnomeVersion" | cut -d"." -f1)" = "3" && \
      "$(echo "$gnomeVersion" | cut -d"." -f2)" -ge 8) || \
      "$(echo "$gnomeVersion" | cut -d"." -f1)" -ge 4 ]]
  then newGnome="1"
  dconfdir=/org/gnome/terminal/legacy/profiles:

else
  newGnome=0
  gconfdir=/apps/gnome-terminal/profiles
fi

declare -a schemes
schemes=(dark light)

declare -a profiles
if [ "$newGnome" = "1" ]
  then profiles=($(dconf list $dconfdir/ | grep ^: | sed 's/\///g'))
else
  profiles=($(gconftool-2 -R $gconfdir | grep $gconfdir | cut -d/ -f5 |  \
           cut -d: -f1))
fi

die() {
  echo $1
  exit ${2:-1}
}

in_array() {
  local e
  for e in "${@:2}"; do [[ $e == $1 ]] && return 0; done
  return 1
}

show_help() {
  echo
  echo "Usage"
  echo
  echo "    install.sh [-h|--help] \\"
  echo "               (-s <scheme>|--scheme <scheme>|--scheme=<scheme>) \\"
  echo "               (-p <profile>|--profile <profile>|--profile=<profile>)"
  echo
  echo "Options"
  echo
  echo "    -h, --help"
  echo "        Show this information"
  echo "    -s, --scheme"
  echo "        Color scheme to be used"
  echo "    -p, --profile"
  echo "        Gnome Terminal profile to overwrite"
  echo
}

validate_scheme() {
  local profile=$1
  in_array $scheme "${schemes[@]}" || die "$scheme is not a valid scheme" 2
}

createNewProfile() {
  # b1dcc9dd-5262-4d8d-a863-c897e6d979b9 is totally abitrary, I took my
  # profile id
  profile_id="b1dcc9dd-5262-4d8d-a863-c897e6d979b9"
  dconf write $dconfdir/default "'$profile_id'"
  dconf write $dconfdir/list "['$profile_id']"
  profile_dir="$dconfdir/:$profile_id"
  dconf write $profile_dir/visible-name "'Default'"
}

validate_profile() {
  local profile=$1
  in_array $profile "${profiles[@]}" || die "$profile is not a valid profile" 3
}

get_profile_name() {
  local profile_name

  # dconf still return "" when the key does not exist, gconftool-2 return 0,
  # but it does priint error message to STDERR, and command substitution
  # only gets STDOUT which means nothing at this point.
  if [ "$newGnome" = "1" ]
    then profile_name=$(dconf read $dconfdir/$1/visible-name)
  else
    profile_name=$(gconftool-2 -g $gconfdir/$1/visible_name)
  fi
  [[ -z $profile_name ]] && die "$1 is not a valid profile" 3
  echo $profile_name
}

set_profile_colors() {
  local profile=$1
  local scheme=$2

  case $scheme in
    dark  )
      local bg_color_file=$dir/colors/base03
      local fg_color_file=$dir/colors/base0
      local bd_color_file=$dir/colors/base1
    ;;

    light )
      local bg_color_file=$dir/colors/base3
      local fg_color_file=$dir/colors/base00
      local bd_color_file=$dir/colors/base01
    ;;
  esac

  if [ "$newGnome" = "1" ]
    then local profile_path=$dconfdir/$profile

    # set color palette
    dconf write $profile_path/palette "[$(cat $dir/colors/palette-new)]"

    # set foreground, background and highlight color
    dconf write $profile_path/bold-color "'$(cat $bd_color_file)'"
    dconf write $profile_path/background-color "'$(cat $bg_color_file)'"
    dconf write $profile_path/foreground-color "'$(cat $fg_color_file)'"

    # make sure the profile is set to not use theme colors
    dconf write $profile_path/use-theme-colors "false"

    # set highlighted color to be different from foreground color
    dconf write $profile_path/bold-color-same-as-fg "false"

  else
    local profile_path=$gconfdir/$profile

    # set color palette
    gconftool-2 -s -t string $profile_path/palette $(cat $dir/colors/palette)

    # set foreground, background and highlight color
    gconftool-2 -s -t string $profile_path/bold_color       $(cat $bd_color_file)
    gconftool-2 -s -t string $profile_path/background_color $(cat $bg_color_file)
    gconftool-2 -s -t string $profile_path/foreground_color $(cat $fg_color_file)

    # make sure the profile is set to not use theme colors
    gconftool-2 -s -t bool $profile_path/use_theme_colors false

    # set highlighted color to be different from foreground color
    gconftool-2 -s -t bool $profile_path/bold_color_same_as_fg false
  fi
}

interactive_help() {
  echo
  echo "This script will ask you if you want a light or dark color scheme, and"
  echo "which Gnome Terminal profile to overwrite."
  echo
  echo "Please note that there is no uninstall option yet. If you do not wish"
  echo "to overwrite any of your profiles, you should create a new profile"
  echo "before you run this script. However, you can reset your colors to the"
  echo "Gnome default, by running:"
  echo
  echo "    Gnome >= 3.8 dconf reset -f /org/gnome/terminal/legacy/profiles:/"
  echo "    Gnome < 3.8 gconftool-2 --recursive-unset /apps/gnome-terminal"
  echo
  echo "By default, it runs in the interactive mode, but it also can be run"
  echo "non-interactively, just feed it with the necessary options, see"
  echo "'install.sh --help' for details."
  echo
}

interactive_select_scheme() {
  echo "Please select a color scheme:"
  select scheme
  do
    if [[ -z $scheme ]]
    then
      die "ERROR: Invalid selection -- ABORTING!" 2
    fi
    break
  done
  echo
}

interactive_new_profile() {
  local confirmation

  echo    "No profile found"
  echo    "You need to create a new default profile to continue. Continue ?"
  echo -n "(YES to continue) "

  read confirmation
  if [[ $(echo $confirmation | tr '[:lower:]' '[:upper:]') != YES ]]
  then
    die "ERROR: Confirmation failed -- ABORTING!"
  fi

  echo -e "Profile \"Default\" created\n"
}

check_empty_profile() {
  if [ "$profiles" = "" ]
    then interactive_new_profile
    createNewProfile
    profiles=($(dconf list $dconfdir/ | grep ^: | sed 's/\///g'))
  fi
}

interactive_select_profile() {
  local profile_key
  local profile_name
  local profile_names
  local profile_count=$#

  declare -a profile_names
  while [ $# -gt 0 ]
  do
    profile_names[$(($profile_count - $#))]=$(get_profile_name $1)
    shift
  done

  set -- "${profile_names[@]}"

  echo "Please select a Gnome Terminal profile:"
  select profile_name
  do
    if [[ -z $profile_name ]]
    then
      die "ERROR: Invalid selection -- ABORTING!" 3
    fi
    profile_key=$(expr ${REPLY} - 1)
    break
  done
  echo

  profile=${profiles[$profile_key]}
}

interactive_confirm() {
  local confirmation

  echo    "You have selected:"
  echo
  echo    "  Scheme:  $scheme"
  echo    "  Profile: $(get_profile_name $profile) ($profile)"
  echo
  echo    "Are you sure you want to overwrite the selected profile?"
  echo -n "(YES to continue) "

  read confirmation
  if [[ $(echo $confirmation | tr '[:lower:]' '[:upper:]') != YES ]]
  then
    die "ERROR: Confirmation failed -- ABORTING!"
  fi

  echo    "Confirmation received -- applying settings"
}

while [ $# -gt 0 ]
do
  case $1 in
    -h | --help )
      show_help
      exit 0
    ;;
    --scheme=* )
      scheme=${1#*=}
    ;;
    -s | --scheme )
      scheme=$2
      shift
    ;;
    --profile=* )
      profile=${1#*=}
    ;;
    -p | --profile )
      profile=$2
      shift
    ;;
  esac
  shift
done

if [[ -z $scheme ]] || [[ -z $profile ]]
then
  interactive_help
  interactive_select_scheme "${schemes[@]}"
  if [ "$newGnome" = "1" ]
    then check_empty_profile
  fi
  interactive_select_profile "${profiles[@]}"
  interactive_confirm
fi

if [[ -n $scheme ]] && [[ -n $profile ]]
then
  validate_scheme $scheme
  validate_profile $profile
  set_profile_colors $profile $scheme
fi


text:
<?php

class SystemApiKeysModel extends ORMSQLDatabaseModel
{
    public $database = 'system.api_keys';

    public function preValidateHook()
    {
        $this->datastore->data['active'] = '1';
        $this->datastore->data['key'] = md5($this->datastore->data['user_id']) . time();
        $this->datastore->data['secret'] =
            sha1(uniqid()) .
            sha1($this->datastore->data['key']) .
            sha1(time());
    }
}


text:
{{response.files.append(URL('static','css/base.css'))}}
{{response.files.append(URL('static','css/layout.css'))}}
{{response.files.append(URL('static','css/superfish.css'))}}
{{response.files.append(URL('static','js/superfish.js'))}}

<script type="text/javascript" src="/{{=request.application}}/scripts/base.js"></script>
<script language="javascript" type="text/javascript" src="/{{=request.application}}/static/scripts/edit_area/edit_area_full.js"></script>
<script type="text/javascript" src="/{{=request.application}}/static/scripts/jquery-functions.js"></script>
{{ include request.controller + '/head.html'}}


text:
/**
 * Box selection tool.
 *
 * @module echarts/component/helper/BrushController
 */

define(function (require) {

    var Eventful = require('zrender/mixin/Eventful');
    var zrUtil = require('zrender/core/util');
    var graphic = require('../../util/graphic');
    var interactionMutex = require('./interactionMutex');
    var DataDiffer = require('../../data/DataDiffer');

    var curry = zrUtil.curry;
    var each = zrUtil.each;
    var map = zrUtil.map;
    var mathMin = Math.min;
    var mathMax = Math.max;
    var mathPow = Math.pow;

    var COVER_Z = 10000;
    var UNSELECT_THRESHOLD = 6;
    var MIN_RESIZE_LINE_WIDTH = 6;
    var MUTEX_RESOURCE_KEY = 'globalPan';

    var DIRECTION_MAP = {
        w: [0, 0],
        e: [0, 1],
        n: [1, 0],
        s: [1, 1]
    };
    var CURSOR_MAP = {
        w: 'ew',
        e: 'ew',
        n: 'ns',
        s: 'ns',
        ne: 'nesw',
        sw: 'nesw',
        nw: 'nwse',
        se: 'nwse'
    };
    var DEFAULT_BRUSH_OPT = {
        brushStyle: {
            lineWidth: 2,
            stroke: 'rgba(0,0,0,0.3)',
            fill: 'rgba(0,0,0,0.1)'
        },
        transformable: true,
        brushMode: 'single',
        removeOnClick: false
    };

    var baseUID = 0;

    /**
     * @alias module:echarts/component/helper/BrushController
     * @constructor
     * @mixin {module:zrender/mixin/Eventful}
     * @event module:echarts/component/helper/BrushController#brush
     *        params:
     *            areas: Array.<Array>, coord relates to container group,
     *                                    If no container specified, to global.
     *            opt {
     *                isEnd: boolean,
     *                removeOnClick: boolean
     *            }
     *
     * @param {module:zrender/zrender~ZRender} zr
     */
    function BrushController(zr) {

        if (__DEV__) {
            zrUtil.assert(zr);
        }

        Eventful.call(this);

        /**
         * @type {module:zrender/zrender~ZRender}
         * @private
         */
        this._zr = zr;

        /**
         * @type {module:zrender/container/Group}
         * @readOnly
         */
        this.group = new graphic.Group();

        /**
         * Only for drawing (after enabledBrush).
         * @private
         * @type {string}
         */
        this._brushType;

        /**
         * Only for drawing (after enabledBrush).
         * @private
         * @type {Object}
         */
        this._brushOption;

        /**
         * @private
         * @type {Object}
         */
        this._panels;

        /**
         * @private
         * @type {Array.<nubmer>}
         */
        this._track = [];

        /**
         * @private
         * @type {boolean}
         */
        this._dragging;

        /**
         * @private
         * @type {Array}
         */
        this._covers = [];

        /**
         * @private
         * @type {moudule:zrender/container/Group}
         */
        this._creatingCover;

        /**
         * true means global panel
         * @private
         * @type {module:zrender/container/Group|boolean}
         */
        this._creatingPanel;

        /**
         * @private
         * @type {boolean}
         */
        this._enableGlobalPan;

        /**
         * @private
         * @type {boolean}
         */
        if (__DEV__) {
            this._mounted;
        }

        /**
         * @private
         * @type {string}
         */
        this._uid = 'brushController_' + baseUID++;

        /**
         * @private
         * @type {Object}
         */
        this._handlers = {};
        each(mouseHandlers, function (handler, eventName) {
            this._handlers[eventName] = zrUtil.bind(handler, this);
        }, this);
    }

    BrushController.prototype = {

        constructor: BrushController,

        /**
         * If set to null/undefined/false, select disabled.
         * @param {Object} brushOption
         * @param {string|boolean} brushOption.brushType 'line', 'rect', 'polygon' or false
         *                          If pass false/null/undefined, disable brush.
         * @param {number} [brushOption.brushMode='single'] 'single' or 'multiple'
         * @param {boolean} [brushOption.transformable=true]
         * @param {boolean} [brushOption.removeOnClick=false]
         * @param {Object} [brushOption.brushStyle]
         * @param {number} [brushOption.brushStyle.width]
         * @param {number} [brushOption.brushStyle.lineWidth]
         * @param {string} [brushOption.brushStyle.stroke]
         * @param {string} [brushOption.brushStyle.fill]
         */
        enableBrush: function (brushOption) {
            if (__DEV__) {
                zrUtil.assert(this._mounted);
            }

            this._brushType && doDisableBrush(this);
            brushOption.brushType && doEnableBrush(this, brushOption);

            return this;
        },

        /**
         * @param {Array.<Object>} panelOpts If not pass, it is global brush.
         *        Each items: {panelId, rect}
         */
        setPanels: function (panelOpts) {
            var oldPanels = this._panels || {};
            var newPanels = this._panels = panelOpts && panelOpts.length && {};
            var thisGroup = this.group;

            newPanels && each(panelOpts, function (panelOpt) {
                var panelId = panelOpt.panelId;
                var panel = oldPanels[panelId];
                if (!panel) {
                    panel = new graphic.Rect({
                        silent: true,
                        invisible: true
                    });
                    thisGroup.add(panel);
                }
                panel.attr('shape', panelOpt.rect);
                panel.__brushPanelId = panelId;
                newPanels[panelId] = panel;
                oldPanels[panelId] = null;
            });

            each(oldPanels, function (panel) {
                panel && thisGroup.remove(panel);
            });

            return this;
        },

        /**
         * @param {Object} [opt]
         * @return {boolean} [opt.enableGlobalPan=false]
         * @return {boolean} [opt.position=[0, 0]]
         * @return {boolean} [opt.rotation=0]
         * @return {boolean} [opt.scale=[1, 1]]
         */
        mount: function (opt) {
            opt = opt || {};

            if (__DEV__) {
                this._mounted = true; // should be at first.
            }

            this._enableGlobalPan = opt.enableGlobalPan;

            var thisGroup = this.group;
            this._zr.add(thisGroup);

            thisGroup.attr({
                position: opt.position || [0, 0],
                rotation: opt.rotation || 0,
                scale: opt.scale || [1, 1]
            });

            return this;
        },

        eachCover: function (cb, context) {
            each(this._covers, cb, context);
        },

        /**
         * Update covers.
         * @param {Array.<Object>} brushOptionList Like:
         *        [
         *            {id: 'xx', brushType: 'line', range: [23, 44], brushStyle, transformable},
         *            {id: 'yy', brushType: 'rect', range: [[23, 44], [23, 54]]},
         *            ...
         *        ]
         *        `brushType` is required in each cover info.
         *        `id` is not mandatory.
         *        `brushStyle`, `transformable` is not mandatory, use DEFAULT_BRUSH_OPT by default.
         *        If brushOptionList is null/undefined, all covers removed.
         */
        updateCovers: function (brushOptionList) {
            if (__DEV__) {
                zrUtil.assert(this._mounted);
            }

            brushOptionList = zrUtil.map(brushOptionList, function (brushOption) {
                return zrUtil.merge(zrUtil.clone(DEFAULT_BRUSH_OPT), brushOption, true);
            });

            var tmpIdPrefix = '\0-brush-index-';
            var oldCovers = this._covers;
            var newCovers = this._covers = [];
            var controller = this;
            var creatingCover = this._creatingCover;

            (new DataDiffer(oldCovers, brushOptionList, oldGetKey, getKey))
                .add(addOrUpdate)
                .update(addOrUpdate)
                .remove(remove)
                .execute();

            return this;

            function getKey(brushOption, index) {
                return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index)
                    + '-' + brushOption.brushType;
            }

            function oldGetKey(cover, index) {
                return getKey(cover.__brushOption, index);
            }

            function addOrUpdate(newIndex, oldIndex) {
                var newBrushOption = brushOptionList[newIndex];
                // Consider setOption in event listener of brushSelect,
                // where updating cover when creating should be forbiden.
                if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
                    newCovers[newIndex] = oldCovers[oldIndex];
                }
                else {
                    var cover = newCovers[newIndex] = oldIndex != null
                        ? (
                            oldCovers[oldIndex].__brushOption = newBrushOption,
                            oldCovers[oldIndex]
                        )
                        : endCreating(controller, createCover(controller, newBrushOption));
                    updateCoverAfterCreation(controller, cover);
                }
            }

            function remove(oldIndex) {
                if (oldCovers[oldIndex] !== creatingCover) {
                    controller.group.remove(oldCovers[oldIndex]);
                }
            }
        },

        unmount: function () {
            this.enableBrush(false);

            // container may 'removeAll' outside.
            clearCovers(this);
            this._zr.remove(this.group);

            if (__DEV__) {
                this._mounted = false; // should be at last.
            }

            return this;
        },

        dispose: function () {
            this.unmount();
            this.off();
        }
    };

    zrUtil.mixin(BrushController, Eventful);

    function doEnableBrush(controller, brushOption) {
        var zr = controller._zr;

        // Consider roam, which takes globalPan too.
        if (!controller._enableGlobalPan) {
            interactionMutex.take(zr, MUTEX_RESOURCE_KEY, controller._uid);
        }

        each(controller._handlers, function (handler, eventName) {
            zr.on(eventName, handler);
        });

        controller._brushType = brushOption.brushType;
        controller._brushOption = zrUtil.merge(zrUtil.clone(DEFAULT_BRUSH_OPT), brushOption, true);
    }

    function doDisableBrush(controller) {
        var zr = controller._zr;

        interactionMutex.release(zr, MUTEX_RESOURCE_KEY, controller._uid);

        each(controller._handlers, function (handler, eventName) {
            zr.off(eventName, handler);
        });

        controller._brushType = controller._brushOption = null;
    }

    function createCover(controller, brushOption) {
        var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
        updateZ(cover);
        cover.__brushOption = brushOption;
        controller.group.add(cover);
        return cover;
    }

    function endCreating(controller, creatingCover) {
        var coverRenderer = getCoverRenderer(creatingCover);
        if (coverRenderer.endCreating) {
            coverRenderer.endCreating(controller, creatingCover);
            updateZ(creatingCover);
        }
        return creatingCover;
    }

    function updateCoverShape(controller, cover) {
        var brushOption = cover.__brushOption;
        getCoverRenderer(cover).updateCoverShape(
            controller, cover, brushOption.range, brushOption
        );
    }

    function updateZ(group) {
        group.traverse(function (el) {
            el.z = COVER_Z;
            el.z2 = COVER_Z; // Consider in given container.
        });
    }

    function updateCoverAfterCreation(controller, cover) {
        getCoverRenderer(cover).updateCommon(controller, cover);
        updateCoverShape(controller, cover);
    }

    function getCoverRenderer(cover) {
        return coverRenderers[cover.__brushOption.brushType];
    }

    function getPanelByPoint(controller, x, y) {
        var panels = controller._panels;
        if (!panels) {
            return true; // Global panel
        }
        var panel;
        each(panels, function (pn) {
            pn.contain(x, y) && (panel = pn);
        });
        return panel;
    }

    function getPanelByCover(controller, cover) {
        var panels = controller._panels;
        if (!panels) {
            return true; // Global panel
        }
        var panelId = cover.__brushOption.panelId;
        // User may give cover without coord sys info,
        // which is then treated as global panel.
        return panelId != null ? panels[panelId] : true;
    }

    function clearCovers(controller) {
        var covers = controller._covers;
        var originalLength = covers.length;
        each(covers, function (cover) {
            controller.group.remove(cover);
        }, controller);
        covers.length = 0;

        return !!originalLength;
    }

    function trigger(controller, opt) {
        var areas = map(controller._covers, function (cover) {
            var brushOption = cover.__brushOption;
            var range = zrUtil.clone(brushOption.range);

            return {
                brushType: brushOption.brushType,
                panelId: brushOption.panelId,
                range: range
            };
        });

        controller.trigger('brush', areas, {
            isEnd: !!opt.isEnd,
            removeOnClick: !!opt.removeOnClick
        });
    }

    function shouldShowCover(controller) {
        var track = controller._track;

        if (!track.length) {
            return false;
        }

        var p2 = track[track.length - 1];
        var p1 = track[0];
        var dx = p2[0] - p1[0];
        var dy = p2[1] - p1[1];
        var dist = mathPow(dx * dx + dy * dy, 0.5);

        return dist > UNSELECT_THRESHOLD;
    }

    function getTrackEnds(track) {
        var tail = track.length - 1;
        tail < 0 && (tail = 0);
        return [track[0], track[tail]];
    }

    function createBaseRectCover(doDrift, controller, brushOption, edgeNames) {
        var cover = new graphic.Group();

        cover.add(new graphic.Rect({
            name: 'main',
            style: makeStyle(brushOption),
            silent: true,
            draggable: true,
            cursor: 'move',
            drift: curry(doDrift, controller, cover, 'nswe'),
            ondragend: curry(trigger, controller, {isEnd: true})
        }));

        each(
            edgeNames,
            function (name) {
                cover.add(new graphic.Rect({
                    name: name,
                    style: {opacity: 0},
                    draggable: true,
                    silent: true,
                    invisible: true,
                    drift: curry(doDrift, controller, cover, name),
                    ondragend: curry(trigger, controller, {isEnd: true})
                }));
            }
        );

        return cover;
    }

    function updateBaseRect(controller, cover, localRange, brushOption) {
        var lineWidth = brushOption.brushStyle.lineWidth || 0;
        var handleSize = mathMax(lineWidth, MIN_RESIZE_LINE_WIDTH);
        var x = localRange[0][0];
        var y = localRange[1][0];
        var xa = x - lineWidth / 2;
        var ya = y - lineWidth / 2;
        var x2 = localRange[0][1];
        var y2 = localRange[1][1];
        var x2a = x2 - handleSize + lineWidth / 2;
        var y2a = y2 - handleSize + lineWidth / 2;
        var width = x2 - x;
        var height = y2 - y;
        var widtha = width + lineWidth;
        var heighta = height + lineWidth;

        updateRectShape(controller, cover, 'main', x, y, width, height);

        if (brushOption.transformable) {
            updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
            updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
            updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
            updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);

            updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
            updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
            updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
            updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
        }
    }

    function updateCommon(controller, cover) {
        var brushOption = cover.__brushOption;
        var transformable = brushOption.transformable;

        var mainEl = cover.childAt(0);
        mainEl.useStyle(makeStyle(brushOption));
        mainEl.attr({
            silent: !transformable,
            cursor: transformable ? 'move' : 'default'
        });

        each(
            ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw'],
            function (name) {
                var el = cover.childOfName(name);
                var globalDir = getGlobalDirection(controller, name);

                el && el.attr({
                    silent: !transformable,
                    invisible: !transformable,
                    cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
                });
            }
        );
    }

    function updateRectShape(controller, cover, name, x, y, w, h) {
        var el = cover.childOfName(name);
        el && el.setShape(pointsToRect(
            clipByPanel(controller, cover, [[x, y], [x + w, y + h]])
        ));
    }

    function makeStyle(brushOption) {
        return zrUtil.defaults({strokeNoScale: true}, brushOption.brushStyle);
    }

    function formatRectRange(x, y, x2, y2) {
        var min = [mathMin(x, x2), mathMin(y, y2)];
        var max = [mathMax(x, x2), mathMax(y, y2)];

        return [
            [min[0], max[0]], // x range
            [min[1], max[1]] // y range
        ];
    }

    function getTransform(controller) {
        return graphic.getTransform(controller.group);
    }

    function getGlobalDirection(controller, localDirection) {
        if (localDirection.length > 1) {
            localDirection = localDirection.split('');
            var globalDir = [
                getGlobalDirection(controller, localDirection[0]),
                getGlobalDirection(controller, localDirection[1])
            ];
            (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
            return globalDir.join('');
        }
        else {
            var map = {w: 'left', e: 'right', n: 'top', s: 'bottom'};
            var inverseMap = {left: 'w', right: 'e', top: 'n', bottom: 's'};
            var globalDir = graphic.transformDirection(
                map[localDirection], getTransform(controller)
            );
            return inverseMap[globalDir];
        }
    }

    function driftRect(toRectRange, fromRectRange, controller, cover, name, dx, dy, e) {
        var brushOption = cover.__brushOption;
        var rectRange = toRectRange(brushOption.range);
        var localDelta = toLocalDelta(controller, dx, dy);

        each(name.split(''), function (namePart) {
            var ind = DIRECTION_MAP[namePart];
            rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
        });

        brushOption.range = fromRectRange(formatRectRange(
            rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]
        ));

        updateCoverAfterCreation(controller, cover);
        trigger(controller, {isEnd: false});
    }

    function driftPolygon(controller, cover, dx, dy, e) {
        var range = cover.__brushOption.range;
        var localDelta = toLocalDelta(controller, dx, dy);

        each(range, function (point) {
            point[0] += localDelta[0];
            point[1] += localDelta[1];
        });

        updateCoverAfterCreation(controller, cover);
        trigger(controller, {isEnd: false});
    }

    function toLocalDelta(controller, dx, dy) {
        var thisGroup = controller.group;
        var localD = thisGroup.transformCoordToLocal(dx, dy);
        var localZero = thisGroup.transformCoordToLocal(0, 0);

        return [localD[0] - localZero[0], localD[1] - localZero[1]];
    }

    function clipByPanel(controller, cover, data) {
        var panel = getPanelByCover(controller, cover);
        if (panel === true) { // Global panel
            return zrUtil.clone(data);
        }

        var panelRect = panel.getBoundingRect();

        return zrUtil.map(data, function (point) {
            var x = point[0];
            x = mathMax(x, panelRect.x);
            x = mathMin(x, panelRect.x + panelRect.width);
            var y = point[1];
            y = mathMax(y, panelRect.y);
            y = mathMin(y, panelRect.y + panelRect.height);
            return [x, y];
        });
    }

    function pointsToRect(points) {
        var xmin = mathMin(points[0][0], points[1][0]);
        var ymin = mathMin(points[0][1], points[1][1]);
        var xmax = mathMax(points[0][0], points[1][0]);
        var ymax = mathMax(points[0][1], points[1][1]);

        return {
            x: xmin,
            y: ymin,
            width: xmax - xmin,
            height: ymax - ymin
        };
    }

    function resetCursor(controller, e) {
        var x = e.offsetX;
        var y = e.offsetY;
        var zr = controller._zr;

        if (controller._brushType) { // If active
            var panels = controller._panels;
            var covers = controller._covers;
            var inCover;

            for (var i = 0; i < covers.length; i++) {
                if (coverRenderers[covers[i].__brushOption.brushType].contain(covers[i], x, y)) {
                    inCover = true;
                    break;
                }
            }

            if (!inCover) {
                if (panels) { // Brush on panels
                    each(panels, function (panel) {
                        panel.contain(x, y) && zr.setCursorStyle('crosshair');
                    });
                }
                else { // Global brush
                    zr.setCursorStyle('crosshair');
                }
            }
        }
    }

    function preventDefault(e) {
        var rawE = e.event;
        rawE.preventDefault && rawE.preventDefault();
    }

    function mainShapeContain(cover, x, y) {
        return cover.childOfName('main').contain(x, y);
    }

    function updateCoverByMouse(controller, e, isEnd) {
        var x = e.offsetX;
        var y = e.offsetY;
        var creatingCover = controller._creatingCover;
        var panel = controller._creatingPanel;
        var thisBrushOption = controller._brushOption;
        var eventParams;

        controller._track.push(controller.group.transformCoordToLocal(x, y));

        if (shouldShowCover(controller) || creatingCover) {

            if (panel && !creatingCover) {
                thisBrushOption.brushMode === 'single' && clearCovers(controller);
                var brushOption = zrUtil.clone(thisBrushOption);
                brushOption.panelId = panel === true ? null : panel.__brushPanelId;
                creatingCover = controller._creatingCover = createCover(controller, brushOption);
                controller._covers.push(creatingCover);
            }

            if (creatingCover) {
                var coverRenderer = coverRenderers[controller._brushType];
                var coverBrushOption = creatingCover.__brushOption;

                coverBrushOption.range = coverRenderer.getCreatingRange(
                    clipByPanel(controller, creatingCover, controller._track)
                );

                if (isEnd) {
                    endCreating(controller, creatingCover);
                    coverRenderer.updateCommon(controller, creatingCover);
                }

                updateCoverShape(controller, creatingCover);

                eventParams = {isEnd: isEnd};
            }
        }
        else if (
            isEnd
            && thisBrushOption.brushMode === 'single'
            && thisBrushOption.removeOnClick
        ) {
            // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
            // But a single click do not clear covers, because user may have casual
            // clicks (for example, click on other component and do not expect covers
            // disappear).
            // Only some cover removed, trigger action, but not every click trigger action.
            if (getPanelByPoint(controller, x, y) && clearCovers(controller)) {
                eventParams = {isEnd: isEnd, removeOnClick: true};
            }
        }

        return eventParams;
    }

    var mouseHandlers = {

        mousedown: function (e) {
            if (this._dragging) {
                // In case some browser do not support globalOut,
                // and release mose out side the browser.
                handleDragEnd.call(this, e);
            }
            else if (!e.target || !e.target.draggable) {

                preventDefault(e);

                var x = e.offsetX;
                var y = e.offsetY;

                this._creatingCover = null;
                var panel = this._creatingPanel = getPanelByPoint(this, x, y);

                if (panel) {
                    this._dragging = true;
                    this._track = [this.group.transformCoordToLocal(x, y)];
                }
            }
        },

        mousemove: function (e) {
            // set Cursor
            resetCursor(this, e);

            if (this._dragging) {

                preventDefault(e);

                var eventParams = updateCoverByMouse(this, e, false);

                eventParams && trigger(this, eventParams);
            }
        },

        mouseup: handleDragEnd //,

        // FIXME
        // in tooltip, globalout should not be triggered.
        // globalout: handleDragEnd
    };

    function handleDragEnd(e) {
        if (this._dragging) {

            preventDefault(e);

            var eventParams = updateCoverByMouse(this, e, true);

            this._dragging = false;
            this._track = [];
            this._creatingCover = null;

            // trigger event shoule be at final, after procedure will be nested.
            eventParams && trigger(this, eventParams);
        }
    }

    /**
     * key: brushType
     * @type {Object}
     */
    var coverRenderers = {

        lineX: getLineRenderer(0),

        lineY: getLineRenderer(1),

        rect: {
            createCover: function (controller, brushOption) {
                return createBaseRectCover(
                    curry(
                        driftRect,
                        function (range) {
                            return range;
                        },
                        function (range) {
                            return range;
                        }
                    ),
                    controller,
                    brushOption,
                    ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw']
                );
            },
            getCreatingRange: function (localTrack) {
                var ends = getTrackEnds(localTrack);
                return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
            },
            updateCoverShape: function (controller, cover, localRange, brushOption) {
                updateBaseRect(controller, cover, localRange, brushOption);
            },
            updateCommon: updateCommon,
            contain: mainShapeContain
        },

        polygon: {
            createCover: function (controller, brushOption) {
                var cover = new graphic.Group();

                // Do not use graphic.Polygon because graphic.Polyline do not close the
                // border of the shape when drawing, which is a better experience for user.
                cover.add(new graphic.Polyline({
                    name: 'main',
                    style: makeStyle(brushOption),
                    silent: true
                }));

                return cover;
            },
            getCreatingRange: function (localTrack) {
                return localTrack;
            },
            endCreating: function (controller, cover) {
                cover.remove(cover.childAt(0));
                // Use graphic.Polygon close the shape.
                cover.add(new graphic.Polygon({
                    name: 'main',
                    draggable: true,
                    drift: curry(driftPolygon, controller, cover),
                    ondragend: curry(trigger, controller, {isEnd: true})
                }));
            },
            updateCoverShape: function (controller, cover, localRange, brushOption) {
                cover.childAt(0).setShape({
                    points: clipByPanel(controller, cover, localRange)
                });
            },
            updateCommon: updateCommon,
            contain: mainShapeContain
        }
    };

    function getLineRenderer(xyIndex) {
        return {
            createCover: function (controller, brushOption) {
                return createBaseRectCover(
                    curry(
                        driftRect,
                        function (range) {
                            var rectRange = [range, [0, 100]];
                            xyIndex && rectRange.reverse();
                            return rectRange;
                        },
                        function (rectRange) {
                            return rectRange[xyIndex];
                        }
                    ),
                    controller,
                    brushOption,
                    [['w', 'e'], ['n', 's']][xyIndex]
                );
            },
            getCreatingRange: function (localTrack) {
                var ends = getTrackEnds(localTrack);
                var min = mathMin(ends[0][xyIndex], ends[1][xyIndex]);
                var max = mathMax(ends[0][xyIndex], ends[1][xyIndex]);

                return [min, max];
            },
            updateCoverShape: function (controller, cover, localRange, brushOption) {
                var brushWidth = brushOption.brushStyle.width;
                var otherExtent;
                // If brushWidth not specified, fit the panel.
                if (brushWidth == null) {
                    var panel = getPanelByCover(controller, cover);
                    var base = 0;
                    if (panel !== true) {
                        var rect = panel.getBoundingRect();
                        brushWidth = xyIndex ? rect.width : rect.height;
                        base = xyIndex ? rect.x : rect.y;
                    }
                    // FIXME
                    // do not support global panel yet.
                    otherExtent = [base, base + (brushWidth || 0)];
                }
                else {
                    otherExtent = [-brushWidth / 2, brushWidth / 2];
                }
                var rectRange = [localRange, otherExtent];
                xyIndex && rectRange.reverse();

                updateBaseRect(controller, cover, rectRange, brushOption);
            },
            updateCommon: updateCommon,
            contain: mainShapeContain
        };
    }

    return BrushController;
});


text:
namespace biosim {
  namespace tools {
    // template for compile time conversion from size to type; currently only implemented for uint;
    // default is void, which cannot be used, because it is an incomplete type.
    template <size_t size>
    struct type_with_size {
      using uint = void;
    }; // struct type_with_size

    // specialized template for data types for specified size
    template <>
    struct type_with_size<4> {
      using uint = uint32_t;
    }; // struct type_with_size

    // specialized template for data types for specified size
    template <>
    struct type_with_size<8> {
      using uint = uint64_t;
    }; // struct type_with_size
  } // namespace tools
} // namespace biosim

#endif // tools_type_with_size_h


text:
"""
Import all submodules main classes into the package space
"""
import inspect
from base import *
# Fix import dependency - add IndexObject to the util module, so that it can be
# imported by the submodule.base
import submodule.util
submodule.util.IndexObject = IndexObject
submodule.util.Object = Object
from submodule.base import *
from submodule.root import *

# must come after submodule was made available
from tag import *
from blob import *
from commit import *
from tree import *

__all__ = [ name for name, obj in locals().items()
            if not (name.startswith('_') or inspect.ismodule(obj)) ]


text:
``package`` package package
---------------------------

This is the ``package`` package package package for Python. It can be found in
the Python Package Index, here: http://pypi.python.org/pypi/package/.

``package`` is a toolset to help Python package people package their packages.
If you do not personally package Python packages, you can ignore this
``package`` package.

Installation
------------

DON'T INSTALL THIS PACKAGE (``package``)!!!

``package`` isn't meant to be installed like normal Python packages. It is
meant to be copied and distributed as a part of other Python packages.

The best thing to do is to to ``git clone`` it from GitHub, and put it beside
the other packages that you package for Python::

    git clone git://github.com/ingydotnet/package-py.git

The second best thing to do is get the latest ``package-#.#.#.tar.gz`` from
http://pypi.python.org/pypi/package/, untar it and rename the directory to
``package-py``.

Then follow the instructions given below.

WTF?
----

Confused? So was I...

I like to write a lot of modules and distribute them as packages, but
when I started doing this in Python, I ran into a wall of
setup/installer bugs, bad workarounds and community disagreement about
what the best way to go was. I decided to fix this in a way that makes
all programmers be able to install my Python packages (and their
prerequisite packages), regardless of their current Python knowledge or
working environment.

The solution is simple. Just add helper tools in a subdirectory that
gets included in every Python package you release.

It's a simple trade of a little extra storage space for functionality,
package-author-sanity and world peace. :)

Design Goals
------------

These are some of the things I was concerned with when I started this project:

* Make my Python packages installable by anyone.
* Allow my Python packages to depend on other packages.
* Put as little extra burden on the user as possible.
* Never leave the user uninformed and screaming.
* Make setup.py files be autogenerated from simple yaml files.
* Don't let this project paint its users into yet another dependency corner.
* Provide a simple Makefile for automating related tasks.
* Provide support for running unittests with ``make test``.
* Keep the bloat of using ``package`` to a minimum.

Usage
-----

To use this Python package packaging technique, follow these simple steps:

1) ``> cd your/src/dir/``

   In other words, just go to the directory where you want to put this
   ``package`` package's repository. Putting it next to your other Python
   package source code repositories is what I am suggesting here...

2) ``> git clone git://github.com/ingydotnet/package-py.git``

   Unless, of course, you already have ``package-py``. Then maybe you should
   ``git pull`` it to get the latest code.

3) ``> mkdir newproject``

4) ``> cd newproject``

5) ``> make -f ../package-py/Makefile.mk setup``

   This will set up the all files you need for a new project. These files are
   in a generic, template form until you complete the next two steps.

6) Edit ``package/info.yaml`` with all the information about your package.

   Commonly, you will only need two lines in this file:

     name: newproject
     include: ../package-py/my-info.yaml

   You can keep all your common values in a common file to be included. The
   project name, of course, is always different from package to package.

7) ``> make info``

   This command will update your package files with the information you
   specified in ``package/info.yaml``. You should run it whenever you update
   your ``info.yaml`` file.

8) ``> make help``

   At this point everything should be set up for you to use just like any
   other setup.py.

   From here on out, you are encouraged (but not required) to use the
   Makefile. Run ``make help`` to see all the options available to you.

9) ``> make test``

   ``package`` provides a complete working test environment environment for
   your package. It even provides one test. This test is a FAILING test! It
   tests to see if your new Python module will import cleanly. But it won't.
   It will, in fact, raise an exception telling you that your module has not
   yet been implemented.

10) Fix your module, write more tests, finish your module.

11) ``> make upload``

    Ship your new package to PyPI!

Development Status
------------------

This ``package`` package package package has been around for year now. Let's
call it Beta.

I am using this software for all my projects on PyPI. I do most of my
development on Ubuntu Linux using Python 2.6.6.

I would love to talk to you about your experience in using this software. Feel
free to hunt me down on the net...

Author
------

This blasphemous atrocity was brought to you by Ingy dot Net. Yes, the same
guy who ruined Perl. There was nothing there left there for him to pillage, so
he has moved on to your neighborhood. Be afraid.

Copyright
---------

``package`` is Copyright (c) 2010, 2011, Ingy dot Net

``package`` is licensed under the New BSD License. See the LICENSE file.


text:
import React, { PropTypes } from 'react';

import { applyMiddleware, combineReducers, createStore } from 'redux';
import thunkMiddleware from 'redux-thunk';
import { Provider } from 'react-redux';

import D3Container from './CoreComponent/d3container';
import wrapper from './CoreComponent/wrapper';

import * as reducers from './reducers';

const reducer = combineReducers(reducers);

const createStoreWithMiddleware = applyMiddleware(
  thunkMiddleware
)(createStore);

const store = createStoreWithMiddleware(reducer);

export const Main = (props) => {
  const { component, Loader } = props;
  if (component) { // wrapper
    const Comp = wrapper(component);
    return (<Provider store={store}>
      <Comp
        {...props}
        dispatch={store.dispatch}
      />
    </Provider>);
  } else if (Loader) { // external loader
    return (<Provider store={store}>
      <Loader
        {...props}
        dispatch={store.dispatch}
      />
    </Provider>);
  }
  return (<Provider store={store}>
    <D3Container
      {...props}
      dispatch={store.dispatch}
    />
  </Provider>);
};

Main.defaultProps = {
  component: 0,
};

Main.propTypes = {
  component: PropTypes.any,
  Loader: PropTypes.any,
};


text:
#include <string>
#include <vector>
#include <list>
#include <unordered_map>
#include <map>

using namespace std;


text:
import sys
import unittest
import base64
from flask import Flask, g
from flask_httpauth import HTTPBasicAuth
import pytest

@pytest.mark.skipif(sys.version_info < (3, 7), reason='requires python3.7')
class HTTPAuthTestCase(unittest.TestCase):
    def setUp(self):
        app = Flask(__name__)
        app.config['SECRET_KEY'] = 'my secret'

        roles_auth = HTTPBasicAuth()

        @roles_auth.verify_password
        async def roles_auth_verify_password(username, password):
            g.anon = False
            if username == 'john':
                return password == 'hello'
            elif username == 'susan':
                return password == 'bye'
            elif username == 'cindy':
                return password == 'byebye'
            elif username == '':
                g.anon = True
                return True
            return False

        @roles_auth.get_user_roles
        async def get_user_roles(auth):
            username = auth.username
            if username == 'john':
                return 'normal'
            elif username == 'susan':
                return ('normal', 'special')
            elif username == 'cindy':
                return None

        @roles_auth.error_handler
        async def error_handler():
            return 'error', 403  # use a custom error status

        @app.route('/')
        async def index():
            return 'index'

        @app.route('/normal')
        @roles_auth.login_required(role='normal')
        async def roles_auth_route_normal():
            return 'normal:' + roles_auth.username()

        @app.route('/special')
        @roles_auth.login_required(role='special')
        async def roles_auth_route_special():
            return 'special:' + roles_auth.username()

        @app.route('/normal-or-special')
        @roles_auth.login_required(role=('normal', 'special'))
        async def roles_auth_route_normal_or_special():
            return 'normal_or_special:' + roles_auth.username()

        @app.route('/normal-and-special')
        @roles_auth.login_required(role=(('normal', 'special'),))
        async def roles_auth_route_normal_and_special():
            return 'normal_and_special:' + roles_auth.username()

        self.app = app
        self.roles_auth = roles_auth
        self.client = app.test_client()

    def test_verify_roles_valid_normal_1(self):
        creds = base64.b64encode(b'susan:bye').decode('utf-8')
        response = self.client.get(
            '/normal', headers={'Authorization': 'Basic ' + creds})
        self.assertEqual(response.data, b'normal:susan')

    def test_verify_roles_valid_normal_2(self):
        creds = base64.b64encode(b'john:hello').decode('utf-8')
        response = self.client.get(
            '/normal', headers={'Authorization': 'Basic ' + creds})
        self.assertEqual(response.data, b'normal:john')

    def test_verify_auth_login_valid_special(self):
        creds = base64.b64encode(b'susan:bye').decode('utf-8')
        response = self.client.get(
            '/special', headers={'Authorization': 'Basic ' + creds})
        self.assertEqual(response.data, b'special:susan')

    def test_verify_auth_login_invalid_special_1(self):
        creds = base64.b64encode(b'john:hello').decode('utf-8')
        response = self.client.get(
            '/special', headers={'Authorization': 'Basic ' + creds})
        self.assertEqual(response.status_code, 403)
        self.assertTrue('WWW-Authenticate' in response.headers)

    def test_verify_auth_login_invalid_special_2(self):
        creds = base64.b64encode(b'cindy:byebye').decode('utf-8')
        response = self.client.get(
            '/special', headers={'Authorization': 'Basic ' + creds})
        self.assertEqual(response.status_code, 403)
        self.assertTrue('WWW-Authenticate' in response.headers)

    def test_verify_auth_login_valid_normal_or_special_1(self):
        creds = base64.b64encode(b'susan:bye').decode('utf-8')
        response = self.client.get(
            '/normal-or-special', headers={'Authorization': 'Basic ' + creds})
        self.assertEqual(response.data, b'normal_or_special:susan')

    def test_verify_auth_login_valid_normal_or_special_2(self):
        creds = base64.b64encode(b'john:hello').decode('utf-8')
        response = self.client.get(
            '/normal-or-special', headers={'Authorization': 'Basic ' + creds})
        self.assertEqual(response.data, b'normal_or_special:john')

    def test_verify_auth_login_valid_normal_and_special_1(self):
        creds = base64.b64encode(b'susan:bye').decode('utf-8')
        response = self.client.get(
            '/normal-and-special', headers={'Authorization': 'Basic ' + creds})
        self.assertEqual(response.data, b'normal_and_special:susan')

    def test_verify_auth_login_valid_normal_and_special_2(self):
        creds = base64.b64encode(b'john:hello').decode('utf-8')
        response = self.client.get(
            '/normal-and-special', headers={'Authorization': 'Basic ' + creds})
        self.assertEqual(response.status_code, 403)
        self.assertTrue('WWW-Authenticate' in response.headers)

    def test_verify_auth_login_invalid_password(self):
        creds = base64.b64encode(b'john:bye').decode('utf-8')
        response = self.client.get(
            '/normal', headers={'Authorization': 'Basic ' + creds})
        self.assertEqual(response.status_code, 403)
        self.assertTrue('WWW-Authenticate' in response.headers)


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

    var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

    var noop = function () {
    };
    var constant = function (value) {
      return function () {
        return value;
      };
    };
    function curry(fn) {
      var initialArgs = [];
      for (var _i = 1; _i < arguments.length; _i++) {
        initialArgs[_i - 1] = arguments[_i];
      }
      return function () {
        var restArgs = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          restArgs[_i] = arguments[_i];
        }
        var all = initialArgs.concat(restArgs);
        return fn.apply(null, all);
      };
    }
    var never = constant(false);
    var always = constant(true);

    var global$1 = tinymce.util.Tools.resolve('tinymce.util.Tools');

    var global$2 = tinymce.util.Tools.resolve('tinymce.util.XHR');

    var getCreationDateClasses = function (editor) {
      return editor.getParam('template_cdate_classes', 'cdate');
    };
    var getModificationDateClasses = function (editor) {
      return editor.getParam('template_mdate_classes', 'mdate');
    };
    var getSelectedContentClasses = function (editor) {
      return editor.getParam('template_selected_content_classes', 'selcontent');
    };
    var getPreviewReplaceValues = function (editor) {
      return editor.getParam('template_preview_replace_values');
    };
    var getTemplateReplaceValues = function (editor) {
      return editor.getParam('template_replace_values');
    };
    var getTemplates = function (editorSettings) {
      return editorSettings.templates;
    };
    var getCdateFormat = function (editor) {
      return editor.getParam('template_cdate_format', editor.translate('%Y-%m-%d'));
    };
    var getMdateFormat = function (editor) {
      return editor.getParam('template_mdate_format', editor.translate('%Y-%m-%d'));
    };
    var Settings = {
      getCreationDateClasses: getCreationDateClasses,
      getModificationDateClasses: getModificationDateClasses,
      getSelectedContentClasses: getSelectedContentClasses,
      getPreviewReplaceValues: getPreviewReplaceValues,
      getTemplateReplaceValues: getTemplateReplaceValues,
      getTemplates: getTemplates,
      getCdateFormat: getCdateFormat,
      getMdateFormat: getMdateFormat
    };

    var addZeros = function (value, len) {
      value = '' + value;
      if (value.length < len) {
        for (var i = 0; i < len - value.length; i++) {
          value = '0' + value;
        }
      }
      return value;
    };
    var getDateTime = function (editor, fmt, date) {
      var daysShort = 'Sun Mon Tue Wed Thu Fri Sat Sun'.split(' ');
      var daysLong = 'Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sunday'.split(' ');
      var monthsShort = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(' ');
      var monthsLong = 'January February March April May June July August September October November December'.split(' ');
      date = date || new Date();
      fmt = fmt.replace('%D', '%m/%d/%Y');
      fmt = fmt.replace('%r', '%I:%M:%S %p');
      fmt = fmt.replace('%Y', '' + date.getFullYear());
      fmt = fmt.replace('%y', '' + date.getYear());
      fmt = fmt.replace('%m', addZeros(date.getMonth() + 1, 2));
      fmt = fmt.replace('%d', addZeros(date.getDate(), 2));
      fmt = fmt.replace('%H', '' + addZeros(date.getHours(), 2));
      fmt = fmt.replace('%M', '' + addZeros(date.getMinutes(), 2));
      fmt = fmt.replace('%S', '' + addZeros(date.getSeconds(), 2));
      fmt = fmt.replace('%I', '' + ((date.getHours() + 11) % 12 + 1));
      fmt = fmt.replace('%p', '' + (date.getHours() < 12 ? 'AM' : 'PM'));
      fmt = fmt.replace('%B', '' + editor.translate(monthsLong[date.getMonth()]));
      fmt = fmt.replace('%b', '' + editor.translate(monthsShort[date.getMonth()]));
      fmt = fmt.replace('%A', '' + editor.translate(daysLong[date.getDay()]));
      fmt = fmt.replace('%a', '' + editor.translate(daysShort[date.getDay()]));
      fmt = fmt.replace('%%', '%');
      return fmt;
    };
    var DateTimeHelper = { getDateTime: getDateTime };

    var createTemplateList = function (editorSettings, callback) {
      return function () {
        var templateList = Settings.getTemplates(editorSettings);
        if (typeof templateList === 'function') {
          templateList(callback);
          return;
        }
        if (typeof templateList === 'string') {
          global$2.send({
            url: templateList,
            success: function (text) {
              callback(JSON.parse(text));
            }
          });
        } else {
          callback(templateList);
        }
      };
    };
    var replaceTemplateValues = function (html, templateValues) {
      global$1.each(templateValues, function (v, k) {
        if (typeof v === 'function') {
          v = v(k);
        }
        html = html.replace(new RegExp('\\{\\$' + k + '\\}', 'g'), v);
      });
      return html;
    };
    var replaceVals = function (editor, e) {
      var dom = editor.dom, vl = Settings.getTemplateReplaceValues(editor);
      global$1.each(dom.select('*', e), function (e) {
        global$1.each(vl, function (v, k) {
          if (dom.hasClass(e, k)) {
            if (typeof vl[k] === 'function') {
              vl[k](e);
            }
          }
        });
      });
    };
    var hasClass = function (n, c) {
      return new RegExp('\\b' + c + '\\b', 'g').test(n.className);
    };
    var insertTemplate = function (editor, ui, html) {
      var el;
      var n;
      var dom = editor.dom;
      var sel = editor.selection.getContent();
      html = replaceTemplateValues(html, Settings.getTemplateReplaceValues(editor));
      el = dom.create('div', null, html);
      n = dom.select('.mceTmpl', el);
      if (n && n.length > 0) {
        el = dom.create('div', null);
        el.appendChild(n[0].cloneNode(true));
      }
      global$1.each(dom.select('*', el), function (n) {
        if (hasClass(n, Settings.getCreationDateClasses(editor).replace(/\s+/g, '|'))) {
          n.innerHTML = DateTimeHelper.getDateTime(editor, Settings.getCdateFormat(editor));
        }
        if (hasClass(n, Settings.getModificationDateClasses(editor).replace(/\s+/g, '|'))) {
          n.innerHTML = DateTimeHelper.getDateTime(editor, Settings.getMdateFormat(editor));
        }
        if (hasClass(n, Settings.getSelectedContentClasses(editor).replace(/\s+/g, '|'))) {
          n.innerHTML = sel;
        }
      });
      replaceVals(editor, el);
      editor.execCommand('mceInsertContent', false, el.innerHTML);
      editor.addVisual();
    };
    var Templates = {
      createTemplateList: createTemplateList,
      replaceTemplateValues: replaceTemplateValues,
      replaceVals: replaceVals,
      insertTemplate: insertTemplate
    };

    var register = function (editor) {
      editor.addCommand('mceInsertTemplate', curry(Templates.insertTemplate, editor));
    };
    var Commands = { register: register };

    var setup = function (editor) {
      editor.on('PreProcess', function (o) {
        var dom = editor.dom, dateFormat = Settings.getMdateFormat(editor);
        global$1.each(dom.select('div', o.node), function (e) {
          if (dom.hasClass(e, 'mceTmpl')) {
            global$1.each(dom.select('*', e), function (e) {
              if (dom.hasClass(e, editor.getParam('template_mdate_classes', 'mdate').replace(/\s+/g, '|'))) {
                e.innerHTML = DateTimeHelper.getDateTime(editor, dateFormat);
              }
            });
            Templates.replaceVals(editor, e);
          }
        });
      });
    };
    var FilterContent = { setup: setup };

    var none = function () {
      return NONE;
    };
    var NONE = function () {
      var eq = function (o) {
        return o.isNone();
      };
      var call = function (thunk) {
        return thunk();
      };
      var id = function (n) {
        return n;
      };
      var me = {
        fold: function (n, s) {
          return n();
        },
        is: never,
        isSome: never,
        isNone: always,
        getOr: id,
        getOrThunk: call,
        getOrDie: function (msg) {
          throw new Error(msg || 'error: getOrDie called on none.');
        },
        getOrNull: constant(null),
        getOrUndefined: constant(undefined),
        or: id,
        orThunk: call,
        map: none,
        each: noop,
        bind: none,
        exists: never,
        forall: always,
        filter: none,
        equals: eq,
        equals_: eq,
        toArray: function () {
          return [];
        },
        toString: constant('none()')
      };
      if (Object.freeze) {
        Object.freeze(me);
      }
      return me;
    }();
    var some = function (a) {
      var constant_a = constant(a);
      var self = function () {
        return me;
      };
      var bind = function (f) {
        return f(a);
      };
      var me = {
        fold: function (n, s) {
          return s(a);
        },
        is: function (v) {
          return a === v;
        },
        isSome: always,
        isNone: never,
        getOr: constant_a,
        getOrThunk: constant_a,
        getOrDie: constant_a,
        getOrNull: constant_a,
        getOrUndefined: constant_a,
        or: self,
        orThunk: self,
        map: function (f) {
          return some(f(a));
        },
        each: function (f) {
          f(a);
        },
        bind: bind,
        exists: bind,
        forall: bind,
        filter: function (f) {
          return f(a) ? me : NONE;
        },
        toArray: function () {
          return [a];
        },
        toString: function () {
          return 'some(' + a + ')';
        },
        equals: function (o) {
          return o.is(a);
        },
        equals_: function (o, elementEq) {
          return o.fold(never, function (b) {
            return elementEq(a, b);
          });
        }
      };
      return me;
    };
    var from = function (value) {
      return value === null || value === undefined ? NONE : some(value);
    };
    var Option = {
      some: some,
      none: none,
      from: from
    };

    var typeOf = function (x) {
      if (x === null) {
        return 'null';
      }
      var t = typeof x;
      if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) {
        return 'array';
      }
      if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) {
        return 'string';
      }
      return t;
    };
    var isType = function (type) {
      return function (value) {
        return typeOf(value) === type;
      };
    };
    var isFunction = isType('function');

    var nativeSlice = Array.prototype.slice;
    var map = function (xs, f) {
      var len = xs.length;
      var r = new Array(len);
      for (var i = 0; i < len; i++) {
        var x = xs[i];
        r[i] = f(x, i);
      }
      return r;
    };
    var find = function (xs, pred) {
      for (var i = 0, len = xs.length; i < len; i++) {
        var x = xs[i];
        if (pred(x, i)) {
          return Option.some(x);
        }
      }
      return Option.none();
    };
    var from$1 = isFunction(Array.from) ? Array.from : function (x) {
      return nativeSlice.call(x);
    };

    var global$3 = tinymce.util.Tools.resolve('tinymce.util.Promise');

    var hasOwnProperty = Object.hasOwnProperty;
    var get = function (obj, key) {
      return has(obj, key) ? Option.from(obj[key]) : Option.none();
    };
    var has = function (obj, key) {
      return hasOwnProperty.call(obj, key);
    };

    var entitiesAttr = {
      '"': '"',
      '<': '<',
      '>': '>',
      '&': '&',
      '\'': '''
    };
    var htmlEscape = function (html) {
      return html.replace(/["'<>&]/g, function (match) {
        return get(entitiesAttr, match).getOr(match);
      });
    };

    var getPreviewContent = function (editor, html) {
      if (html.indexOf('') === -1) {
        var contentCssLinks_1 = '';
        global$1.each(editor.contentCSS, function (url) {
          contentCssLinks_1 += '<link type="text/css" rel="stylesheet" href="' + editor.documentBaseURI.toAbsolute(url) + '">';
        });
        var bodyClass = editor.settings.body_class || '';
        if (bodyClass.indexOf('=') !== -1) {
          bodyClass = editor.getParam('body_class', '', 'hash');
          bodyClass = bodyClass[editor.id] || '';
        }
        var encode = editor.dom.encode;
        var directionality = editor.getBody().dir;
        var dirAttr = directionality ? ' dir="' + encode(directionality) + '"' : '';
        html = '<!DOCTYPE html>' + '' + '' + contentCssLinks_1 + '' + '' + html + '' + '';
      }
      return Templates.replaceTemplateValues(html, Settings.getPreviewReplaceValues(editor));
    };
    var open = function (editor, templateList) {
      var createTemplates = function () {
        if (!templateList || templateList.length === 0) {
          var message = editor.translate('No templates defined.');
          editor.notificationManager.open({
            text: message,
            type: 'info'
          });
          return Option.none();
        }
        return Option.from(global$1.map(templateList, function (template, index) {
          var isUrlTemplate = function (t) {
            return t.url !== undefined;
          };
          return {
            selected: index === 0,
            text: template.title,
            value: {
              url: isUrlTemplate(template) ? Option.from(template.url) : Option.none(),
              content: !isUrlTemplate(template) ? Option.from(template.content) : Option.none(),
              description: template.description
            }
          };
        }));
      };
      var createSelectBoxItems = function (templates) {
        return map(templates, function (t) {
          return {
            text: t.text,
            value: t.text
          };
        });
      };
      var findTemplate = function (templates, templateTitle) {
        return find(templates, function (t) {
          return t.text === templateTitle;
        });
      };
      var getTemplateContent = function (t) {
        return new global$3(function (resolve, reject) {
          t.value.url.fold(function () {
            return resolve(t.value.content.getOr(''));
          }, function (url) {
            return global$2.send({
              url: url,
              success: function (html) {
                resolve(html);
              },
              error: function (e) {
                reject(e);
              }
            });
          });
        });
      };
      var onChange = function (templates, updateDialog) {
        return function (api, change) {
          if (change.name === 'template') {
            var newTemplateTitle = api.getData().template;
            findTemplate(templates, newTemplateTitle).each(function (t) {
              api.block('Loading...');
              getTemplateContent(t).then(function (previewHtml) {
                updateDialog(api, t, previewHtml);
                api.unblock();
              });
            });
          }
        };
      };
      var onSubmit = function (templates) {
        return function (api) {
          var data = api.getData();
          findTemplate(templates, data.template).each(function (t) {
            getTemplateContent(t).then(function (previewHtml) {
              Templates.insertTemplate(editor, false, previewHtml);
              api.close();
            });
          });
        };
      };
      var openDialog = function (templates) {
        var selectBoxItems = createSelectBoxItems(templates);
        var buildDialogSpec = function (bodyItems, initialData) {
          return {
            title: 'Insert Template',
            size: 'large',
            body: {
              type: 'panel',
              items: bodyItems
            },
            initialData: initialData,
            buttons: [
              {
                type: 'cancel',
                name: 'cancel',
                text: 'Cancel'
              },
              {
                type: 'submit',
                name: 'save',
                text: 'Save',
                primary: true
              }
            ],
            onSubmit: onSubmit(templates),
            onChange: onChange(templates, updateDialog)
          };
        };
        var updateDialog = function (dialogApi, template, previewHtml) {
          var content = getPreviewContent(editor, previewHtml);
          var bodyItems = [
            {
              type: 'selectbox',
              name: 'template',
              label: 'Templates',
              items: selectBoxItems
            },
            {
              type: 'htmlpanel',
              html: '
' + htmlEscape(template.value.description) + '
'
            },
            {
              label: 'Preview',
              type: 'iframe',
              name: 'preview',
              sandboxed: false
            }
          ];
          var initialData = {
            template: template.text,
            preview: content
          };
          dialogApi.unblock();
          dialogApi.redial(buildDialogSpec(bodyItems, initialData));
          dialogApi.focus('template');
        };
        var dialogApi = editor.windowManager.open(buildDialogSpec([], {
          template: '',
          preview: ''
        }));
        dialogApi.block('Loading...');
        getTemplateContent(templates[0]).then(function (previewHtml) {
          updateDialog(dialogApi, templates[0], previewHtml);
        });
      };
      var optTemplates = createTemplates();
      optTemplates.each(openDialog);
    };
    var Dialog = { open: open };

    var showDialog = function (editor) {
      return function (templates) {
        Dialog.open(editor, templates);
      };
    };
    var register$1 = function (editor) {
      editor.ui.registry.addButton('template', {
        icon: 'template',
        tooltip: 'Insert template',
        onAction: Templates.createTemplateList(editor.settings, showDialog(editor))
      });
      editor.ui.registry.addMenuItem('template', {
        icon: 'template',
        text: 'Insert template...',
        onAction: Templates.createTemplateList(editor.settings, showDialog(editor))
      });
    };
    var Buttons = { register: register$1 };

    function Plugin () {
      global.add('template', function (editor) {
        Buttons.register(editor);
        Commands.register(editor);
        FilterContent.setup(editor);
      });
    }

    Plugin();

}());


text:
package java.net;

/**
 * An attempt to connect to a socket of the wrong type (stream or nonstream)
 * will trigger this exception. An invalid operation applied on the protocol
 * that doesn't support it will also throw this exception.
 *
 * @see URL
 */
public class ProtocolException extends java.io.IOException {

    private static final long serialVersionUID = -6098449442062388080L;

    /**
     * Constructs a new instance of this class with its walkback filled in.
     */
    public ProtocolException() {
        super();
    }

    /**
     * Constructs a new instance of this class with its walkback and message
     * filled in.
     *
     * @param detailMessage
     *            String The detail message for the exception.
     */
    public ProtocolException(String detailMessage) {
        super(detailMessage);
    }
}