text:
package eventstreams.tx

import _root_.core.sysevents.SyseventOps.symbolToSyseventOps
import _root_.core.sysevents.WithSyseventPublisher
import _root_.core.sysevents.ref.ComponentWithBaseSysevents
import akka.actor.Props
import akka.stream.actor.{MaxInFlightRequestStrategy, RequestStrategy}
import eventstreams.Tools._
import eventstreams._
import eventstreams.core.actors.{ActorWithTicks, StateChangeSysevents, StoppableSubscribingPublisherActor}
import eventstreams.instructions.Types._
import eventstreams.instructions.{DateInstructionConstants, InstructionConstants}
import play.api.libs.json._

import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scalaz.Scalaz._
import scalaz._

trait TransactionInstructionSysevents
  extends ComponentWithBaseSysevents
  with StateChangeSysevents {
  val TxInstructionInstance = 'TxInstructionInstance.trace

  val NewTransaction = 'NewTransaction.trace
  val TransactionStart = 'TransactionStart.trace
  val TransactionFinish = 'TransactionFinish.trace
  val TransactionCompleted = 'TransactionCompleted.trace
  val TransactionEvicted = 'TransactionEvicted.trace

  override def componentId: String = "Instruction.Tx"

}

trait TransactionInstructionConstants extends InstructionConstants with TransactionInstructionSysevents {
  val CfgFName = "name"
  val CfgFCorrelationIdTemplates = "correlationIdTemplates"
  val CfgFTxStartCondition = "txStartCondition"
  val CfgFTxEndSuccessCondition = "txEndSuccessCondition"
  val CfgFTxEndFailureCondition = "txEndFailureCondition"
  val CfgFMaxOpenTransactions = "maxOpenTransactions"
  val CfgFTimestampSource = "timestampSource"
  val CfgFTargetTxField = "targetTxField"
  val CfgFTargetTxElapsedMsField = "targetTxElapsedMsField"
  val CfgFTargetTxStatusField = "targetTxStatusField"
  val CfgFBuffer = "buffer"

  val CfgFEventIdTemplate = "eventIdTemplate"
  val CfgFStreamKeyTemplate = "streamKeyTemplate"
  val CfgFStreamSeedTemplate = "streamSeedTemplate"

  val CfgFTags = "tags"
  val CfgFTxTypeTemplate = "txTypeTemplate"

  val ValueStatusClosedSuccess = "closed_success"
  val ValueStatusClosedFailure = "closed_success"
  val ValueStatusIncomplete = "incomplete"

}

object TransactionInstructionConstants extends TransactionInstructionConstants

class TransactionInstruction extends BuilderFromConfig[InstructionType] with TransactionInstructionConstants {
  val configId = "tx"

  override def build(props: JsValue, maybeState: Option[JsValue], id: Option[String] = None): \/[Fail, InstructionType] =
    for (
      _ <- props ~> CfgFCorrelationIdTemplates
        orFail s"Invalid $configId instruction. Missing '$CfgFCorrelationIdTemplates' value. Contents: ${Json.stringify(props)}";
      _ <- props ~> CfgFTxStartCondition
        orFail s"Invalid $configId instruction. Missing '$CfgFTxStartCondition' value. Contents: ${Json.stringify(props)}";
      _ <- SimpleCondition.optionalCondition(props ~> CfgFTxEndSuccessCondition)
        orFail s"Invalid $configId instruction. Missing or invalid '$CfgFTxEndSuccessCondition' value. Contents: ${Json.stringify(props)}"
    ) yield TransactionInstructionActor.props(props)

}

private object TransactionInstructionActor {
  def props(config: JsValue) = Props(new TransactionInstructionActor(config))
}

private class TransactionInstructionActor(props: JsValue)
  extends StoppableSubscribingPublisherActor
  with ActorWithTicks
  with NowProvider
  with TransactionInstructionConstants
  with WithSyseventPublisher {

  implicit val ec = context.dispatcher

  val correlationIdTemplatesSeq: Seq[String] = (props ~> CfgFCorrelationIdTemplates | "").split(',').map(_.trim).filter(!_.isEmpty)

  val name = props ~> CfgFName | "default"
  val txStartCondition = SimpleCondition.optionalCondition(props ~> CfgFTxStartCondition)
  val txEndSuccessCondition = SimpleCondition.optionalCondition(props ~> CfgFTxEndSuccessCondition)
  val txEndFailureCondition = SimpleCondition.optionalCondition(props ~> CfgFTxEndFailureCondition)

  val eventIdTemplate = props ~> CfgFEventIdTemplate | "${first.eventId}:${last.eventId}"
  val streamKeyTemplate = props ~> CfgFStreamKeyTemplate | "${first.streamKey}"
  val streamSeedTemplate = props ~> CfgFStreamSeedTemplate | "0"
  val tags = (props ~> CfgFTags).map(_.split(',').map(_.trim).filterNot(_.isEmpty))
  val txTypeTemplate = props ~> CfgFTxTypeTemplate

  val maxOpenTransactions = props +> CfgFMaxOpenTransactions | 100000
  val timestampSource = props ~> CfgFTimestampSource | DateInstructionConstants.default_targetTsField

  val targetTxField = props ~> CfgFTargetTxField | "txId"
  val targetTxElapsedMsField = props ~> CfgFTargetTxElapsedMsField | "txElapsedMs"
  val targetTxStatusField = props ~> CfgFTargetTxStatusField | "txStatus"

  val maxInFlight = props +> CfgFBuffer | 1000

  val txById: mutable.Map[String, TxTimeline] = mutable.Map()
  var openTransactions: Int = 0

  override def onBecameActive(): Unit = {
    super.onBecameActive()
  }

  override def preStart(): Unit = {
    super.preStart()
    TxInstructionInstance >>> Seq(
      'Name -> name,
      'Templates -> correlationIdTemplatesSeq,
      'Start -> props ~> CfgFTxStartCondition,
      'EndSuccess -> props ~> CfgFTxEndSuccessCondition,
      'EndFailure -> props ~> CfgFTxEndFailureCondition,
      'MaxOpen -> maxOpenTransactions,
      'Buffer -> maxInFlight
    )
  }

  override def execute(value: EventFrame): Option[Seq[EventFrame]] =
    accountEvent(value) match {
      case Some(x) => Some(x :+ value)
      case None => Some(Seq(value))
    }

  override protected def requestStrategy: RequestStrategy = new MaxInFlightRequestStrategy(maxInFlight) {
    override def inFlightInternally: Int =
      pendingToDownstreamCount
  }

  private def accountEvent(value: EventFrame): Option[Seq[EventFrame]] =
    for (
      eId <- value.eventId;
      txStartC <- txStartCondition;
      txEndSC <- txEndSuccessCondition;
      ts <- value ++> timestampSource;
      ids <- listOfTxIds(value);
      txEndFC = txEndFailureCondition | NeverTrueCondition();
      txB <- toDemarcType(ts, value, txStartC.metFor(value).isRight, txEndSC.metFor(value).isRight, txEndFC.metFor(value).isRight, ids)
    ) yield ids.flatMap(toEvents(_, txB)) ++ removeOldestIfMaxOpenExceeded()

  private def toDemarcType(ts: Long, evt: EventFrame, start: Boolean, finishWithSuccess: Boolean, finishWithFailure: Boolean, ids: Seq[String]): Option[TxDemarcation] =
    if (start) {
      TransactionStart >>('EventId -> evt.eventIdOrNA, 'TxIds -> ids.mkString(","))
      Some(TxStart(ts, evt))
    } else if (finishWithFailure) {
      TransactionFinish >>('EventId -> evt.eventIdOrNA, 'Success -> false, 'TxIds -> ids.mkString(","))
      Some(TxFinishFailure(ts, evt))
    } else if (finishWithSuccess) {
      TransactionFinish >>('EventId -> evt.eventIdOrNA, 'Success -> true, 'TxIds -> ids.mkString(","))
      Some(TxFinishSuccess(ts, evt))
    }
    else None

  private def toEvent(tx: Tx): EventFrame = {
    var e = EventFrame(
      targetTxField -> tx.id,
      targetTxElapsedMsField -> tx.elapsedMs,
      targetTxStatusField -> (if (tx.completed) {
        if (tx.isCompletedSuccessfully) ValueStatusClosedSuccess else ValueStatusClosedFailure
      } else ValueStatusIncomplete),
      "first" -> (tx.start.map(_.evt.asInstanceOf[EventData]) | EventDataValueNil()),
      "last" -> (tx.finish.map(_.evt.asInstanceOf[EventData]) | EventDataValueNil())
    )
    txTypeTemplate.foreach { t =>
      e = e + ('txType -> Tools.macroReplacement(e, t))
    }
    tags.foreach(_.foreach { t =>
      e = Tools.setValue("as", Tools.macroReplacement(e, t), "tags", e)
    })
    e
      .setEventId(Tools.macroReplacement(e, eventIdTemplate) match {
      case s if s.trim.isEmpty => UUIDTools.generateShortUUID
      case s => s
    })
      .setStreamKey(Tools.macroReplacement(e, streamKeyTemplate))
      .setStreamSeed(Tools.macroReplacement(e, streamSeedTemplate))
  }

  private def toEvents(id: String, txB: TxDemarcation): Seq[EventFrame] =
    txById.get(id) match {
      case None =>
        txById += (id -> (new TxTimeline() + (new Tx(id) + txB)))
        Seq()
      case Some(tl) =>
        tl ? txB match {
          case None =>
            tl + (new Tx(id) + txB)
            Seq()
          case Some(tx) => tx + txB match {
            case t if t.completed =>
              if ((tl - t).empty) txById -= id
              TransactionCompleted >>(
                'TxId -> id,
                'EventIdStart -> (tx.start.map(_.evt.eventIdOrNA) | "N/A"),
                'EventIdFinish -> (tx.finish.map(_.evt.eventIdOrNA) | "N/A"),
                'Success -> tx.isCompletedSuccessfully,
                'OpenTxCount -> openTransactions)
              Seq(toEvent(t))
            case _ => Seq()
          }
        }
    }

  private def removeOldestIfMaxOpenExceeded(): Seq[EventFrame] =
    if (openTransactions > maxOpenTransactions)
      txById.foldLeft[Option[(String, TxTimeline, Tx)]](None) {
        case (None, (k, v)) => Some((k, v, v.oldest))
        case (Some((bk, btl, btx)), (k, v)) if v.oldest.olderThan(btx) => Some((k, v, v.oldest))
        case (x, _) => x
      } match {
        case Some((k, tl, tx)) =>
          if ((tl - tx).empty) txById -= k
          TransactionEvicted >>(
            'TxId -> tx.id,
            'EventIdStart -> (tx.start.map(_.evt.eventIdOrNA) | "N/A"),
            'EventIdFinish -> (tx.finish.map(_.evt.eventIdOrNA) | "N/A"),
            'OpenTxCount -> openTransactions)
          Seq(toEvent(tx))
        case None => Seq()
      }
    else Seq()

  private def listOfTxIds(value: EventFrame): Option[Seq[String]] =
    correlationIdTemplatesSeq.map(Tools.macroReplacement(value, _)).map(_.trim).filter(!_.isEmpty) match {
      case Nil => None
      case x => Some(x)
    }

  sealed trait TxDemarcation {
    def ts: Long

    def evt: EventFrame
  }

  class Tx(val id: String) {

    var start: Option[TxDemarcation] = None
    var finish: Option[TxDemarcation] = None

    def +(d: TxDemarcation): Tx = {
      d match {
        case x: TxStart => start = Some(x)
        case x => finish = Some(x)
      }
      this
    }

    def elapsedMs: Long = if (!completed) -1 else finish.get.ts - start.get.ts

    def completed: Boolean = start.isDefined && finish.isDefined

    def olderThan(tx: Tx): Boolean = getOldestTs < tx.getOldestTs

    def isCompletedSuccessfully: Boolean = finish match {
      case Some(x: TxFinishSuccess) => completed
      case _ => false
    }

    private def getOldestTs = (start.map(_.ts).toList ++ finish.map(_.ts).toList).min
  }

  class TxTimeline {
    private val list: mutable.ListBuffer[Tx] = ListBuffer()

    def +(tx: Tx): TxTimeline = {
      openTransactions += 1
      NewTransaction >>('TxId -> tx.id, 'OpenTxCount -> openTransactions)
      list.indexWhere(_.olderThan(tx)) match {
        case i if i < 0 => list.append(tx)
        case i => list.insert(i, tx)
      }
      this
    }

    def -(tx: Tx): TxTimeline = {
      openTransactions -= 1
      list -= tx
      this
    }

    def ?(d: TxDemarcation): Option[Tx] =
      d match {
        case x: TxStart =>
          list.reverseIterator.collectFirst {
            case tx if tx.start.isEmpty && (tx.finish.map(_.ts >= x.ts) | false) => tx
          }
        case x =>
          list.collectFirst {
            case tx if tx.finish.isEmpty && (tx.start.map(_.ts <= x.ts) | false) => tx
          }
      }

    def empty: Boolean = list.isEmpty

    def oldest: Tx = list.last
  }

  case class TxStart(ts: Long, evt: EventFrame) extends TxDemarcation

  case class TxFinishSuccess(ts: Long, evt: EventFrame) extends TxDemarcation

  case class TxFinishFailure(ts: Long, evt: EventFrame) extends TxDemarcation

}


text:
package org.vaadin.maps.shared.ui.handler;

import com.vaadin.shared.communication.ServerRpc;

/**
 * @author Kamil Morong
 */
public interface ZoomHandlerRpc extends ServerRpc {

    void zoomChange(long timestamp, double zoomStep);

}

redpajama_set_name: RedPajamaGithub


text:
<?php
declare(strict_types=1);

namespace HomoChecker\Test\Middleware;

use HomoChecker\Http\ErrorResponse;
use HomoChecker\Middleware\ErrorMiddleware;
use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;
use Mockery as m;
use Mockery\MockInterface;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Server\RequestHandlerInterface;
use RuntimeException;
use Slim\Exception\HttpNotFoundException;
use Slim\Interfaces\CallableResolverInterface;
use Slim\Interfaces\ErrorHandlerInterface;
use Slim\Psr7\Factory\ServerRequestFactory;
use Slim\Psr7\Factory\StreamFactory;
use Slim\Psr7\Response;

class ErrorMiddlewareTest extends TestCase
{
    use MockeryPHPUnitIntegration;

    public function testProcessHttpException(): void
    {
        $request = (new ServerRequestFactory())->createServerRequest('GET', '/metrics');
        $exception = new HttpNotFoundException($request);
        $response = new ErrorResponse(new Response(), new StreamFactory());

        /** @var ErrorHandlerInterface&MockInterface $errorHandler */
        $errorHandler = m::mock(ErrorHandlerInterface::class);
        $errorHandler->shouldReceive('__invoke')
                     ->withArgs([$request, $exception, false, false, false])
                     ->andReturn($response);

        /** @var CallableResolverInterface&MockInterface $callableResolver */
        $callableResolver = m::mock(CallableResolverInterface::class);
        $callableResolver->shouldReceive('resolve')
                         ->withArgs([$errorHandler])
                         ->andReturn($errorHandler);

        /** @var MockInterface&ResponseFactoryInterface $responseFactory */
        $responseFactory = m::mock(ResponseFactoryInterface::class);

        /** @var MockInterface&RequestHandlerInterface $handler */
        $handler = m::mock(RequestHandlerInterface::class);
        $handler->shouldReceive('handle')
                ->withArgs([$request])
                ->andThrow($exception);

        $middleware = new ErrorMiddleware($callableResolver, $responseFactory);
        $middleware->setDefaultErrorHandler($errorHandler);
        $actual = $middleware->process($request, $handler);

        $this->assertEquals($response, $actual);
    }

    public function testProcessException(): void
    {
        $request = (new ServerRequestFactory())->createServerRequest('GET', '/metrics');
        $response = new ErrorResponse(new Response(), new StreamFactory());
        $exception = new RuntimeException();

        /** @var ErrorHandlerInterface&MockInterface $errorHandler */
        $errorHandler = m::mock(ErrorHandlerInterface::class);
        $errorHandler->shouldReceive('__invoke')
                     ->withArgs([$request, $exception, false, false, false])
                     ->andReturn($response);

        /** @var CallableResolverInterface&MockInterface $callableResolver */
        $callableResolver = m::mock(CallableResolverInterface::class);
        $callableResolver->shouldReceive('resolve')
                         ->withArgs([$errorHandler])
                         ->andReturn($errorHandler);

        /** @var MockInterface&ResponseFactoryInterface $responseFactory */
        $responseFactory = m::mock(ResponseFactoryInterface::class);

        /** @var MockInterface&RequestHandlerInterface $handler */
        $handler = m::mock(RequestHandlerInterface::class);
        $handler->shouldReceive('handle')
                ->withArgs([$request])
                ->andThrow($exception);

        $middleware = new ErrorMiddleware($callableResolver, $responseFactory);
        $middleware->setDefaultErrorHandler($errorHandler);
        $actual = $middleware->process($request, $handler);
        $expected = $response->withException($exception);

        $this->assertEquals($expected, $actual);
    }
}


text:
var Wreqr = require('backbone.wreqr');

module.exports = Wreqr.radio;


text:
<TITLE>Review for Shuang long hui (1992)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Shuang long hui (1992)

reviewed by
Christopher E. Meadows

Twin Dragons (1992)

Review by Chris Meadows
Review Rating: 8 out of 10

Directed by Tsui Hark & Ringo Lam
Produced by Teddy Robin Kwan

Starring Jackie Chan, Maggie Cheung, Teddy Robin Kwan, Nina Chi Li,
    Philip Chan, etc.

MPAA: Unrated

Many people laud Jackie Chan's kung-fu fighting and stunt-performing
abilities without realizing the true secret of his cinematic success.
Martial artists and stuntmen are a dime a dozen, but what really sets
Jackie Chan above the rest is his wonderful knack for physical comedy.
He has few equals in that field, at least among those working
today--Bruce Campbell and Jim Carrey are the only other names that
come immediately to mind.  And it is comedy, rather than fighting,
that makes "Twin Dragons" worth watching.

The premise of "Twin Dragons" is that Jackie Chan plays both halves of
a pair of twins who were accidentally separated at birth, grew up into
entirely different people, and eventually run into and get confused
for each other in Hong Kong.  Sound familiar?  The same basic idea was
done by Van Damme in "Double Impact," which was also set in Hong Kong
and made the year before...but whereas in "Double Impact" the point
was to have two Van Dammes to show twice as much beefcake and kick
twice as much butt at once, "Twin Dragons" plays up the comedy aspect
of mistaken identities--in fact, one of the Jackie Chans can't fight
at all.

After the opening, in which the twins are split, they grow up
separately--the one who was lost becomes Boomer, a tough auto
mechanic, road racer, and street hustler, while John Ma, the one who
went with his parents to America, grows up to be a virtuoso piano
player and orchestra conductor.

As the film begins, Boomer's friend Tyson (played by Teddy Robin Kwan,
also the film's producer) falls for a karaoke singer named Barbara
(Maggie Cheung).  In pursuit of her, Boomer and Tyson bust up a party
for a Triad (mob) figure, Brother Wing (Alfred Cheung).  In lieu of
breaking Boomer's leg, Wing challenges Boomer to a road race, with
stakes of three hundred thousand Hong Kong dollars (about $33,000 US).
When the twosome attempts to flee Hong Kong, they get into a boat
chase with Wing's men which ends up critically injuring Wing.

Meanwhile, John Ma has come to Hong Kong for the first time since his
family left, to conduct a concert, and is set up with a rather
attractive female nurse, Tammy (Nina Li Chi), by Tammy's father, an
old family friend.  As fate would have it, the Ma twins _almost_ meet
several times, confusing all those with whom they come into contact
(including Tyson, a waiter, Tammy, Barbara, Tammy's ex-boyfriend
Rocky, and each other), accidentally get switched with each other,
meet, switch back and forth two more times, and get stuck in each
other's roles when it comes time to conduct the concert and the
mobsters have a job they need Boomer to do.  In the end, they join
forces to save Tyson from the mob brothers in a climactic kung-fu
comedy battle.

Chan fans expecting the sort of back-to-back fighting action seen in
"Double Impact" may be disappointed.  This movie has only one fighting
Chan in it, that being Boomer--when the thugs come after John Ma, he
has to run away or get beaten up.  However, the fight scenes where
Boomer does his thing are everything we've come to expect from Jackie
at his prime--constant motion, use of handy props as improvised
weapons, and fast and furious action.

Chan fans shouldn't fret too much, though, because there _are_ two
_comedic_ Chans in "Twin Dragons."  As might be expected, each Jackie
Chans is constantly being mistaken for the "other" Jackie, and neither
one quite realizes what's going on at first.  The funniest scene of
the movie comes in John Ma's hotel suite, when Tammy unknowingly
corners the two Jackie Chans in the bathroom and they have to convince
her that there's only one of them...while taking a bath together.
There is physical comedy, too: being twins, the brothers share sort of
a psychic link.  When John Ma is playing the piano, Boomer's hand
twitches as though he were playing the piano, too.  When Boomer is
racing a speedboat, attempting to escape from Brother Wing's thugs,
John Ma is jerked this way and that (disrupting their dinner in a fine
restaurant) as Boomer tries to keep his balance.

The version of "Twin Dragons" that I saw was dubbed and
pan-and-scanned, bought from Best Buy for under $5.  While I
personally prefer subtitled and letterboxed films, this one was
nonetheless well worth the money.  The voice acting was quite good,
and Cam Clarke, one of my favorite voice actors, did a fine job of
differentiating the two different Jackie Chans.

All in all, this very entertaining film gets a rating of 8 out of 10
from this reviewer.

An interesting side note: "Twin Dragons" was made as a charity project
by the Hong Kong Director's Guild, and features cameo appearances by
many reknowned Hong Kong directors.  Most notably, John Woo is the
priest on the left at the wedding, Tsui Hark and Ringo Lam (the
directors of "Twin Dragons") are two of the card-playing mechanics in
the Mitsubishi testing facility, and Philip Chan (who played the
police superintendent in Woo's "Hard-Boiled," and who, interestingly
enough, also had a role in Van Damme's "Double Impact") is the hotel
manager.  Other Hong Kong directors, who will probably not be
recognized by non-Hong Kong-cinemaphiles on this side of the Pacific,
fill many of the film's other minor roles.

(This review is copyright 1998 by Christopher E. Meadows.  Permission
granted for Usenet distribution and associated archival, including the
Internet Movie Database, but other distribution rights reserved to the
author.)
--
Chris Meadows aka  | Co-moderator, rec.toys.transformers.moderated
Robotech_Master    | Homepage: <URL:">http://www.eyrie.org/~robotech/>
robotech@eyrie.org | PGP: <URL:">http://www.eyrie.org/~robotech/rm.key.txt>
robotech@jurai.net | ICQ UIN: 5477383

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
package uk.ac.open.kmi.iserve.rest.sal.test;

import com.gargoylesoftware.htmlunit.CookieManager;
import com.gargoylesoftware.htmlunit.ElementNotFoundException;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlCheckBoxInput;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.jayway.restassured.RestAssured;
import org.apache.commons.httpclient.Cookie;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.open.kmi.iserve.sal.exception.SalException;
import uk.ac.open.kmi.iserve.sal.manager.RegistryManager;
import uk.ac.open.kmi.iserve.sal.manager.impl.RegistryManagementModule;
import uk.ac.open.kmi.msm4j.io.MediaType;
import uk.ac.open.kmi.msm4j.io.Syntax;
import uk.ac.open.kmi.msm4j.io.util.FilenameFilterBySyntax;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.URI;
import java.util.Iterator;
import java.util.Set;

import static com.jayway.restassured.RestAssured.given;

/**
 * Based on the tests from Shiro samples-web
 */
public class ServiceResourceTest extends AbstractContainerTest {

    private static final Logger log = LoggerFactory.getLogger(ServiceResourceTest.class);

    // Limit the number of documents to upload to the registry
    private static final int MAX_DOCS = 25;

    private static final String HOST = "http://localhost";
    private static final int PORT = 9090;
    //            private static final int PORT = 10000;
    private static final String BASE_CONTEXT = "/iserve";
    private static final String REGISTRY_SERVICES_PATH = "/id/services";
    private static final String SERVICES_PATH = BASE_CONTEXT + REGISTRY_SERVICES_PATH;
    private static final String WEB_APP_URI = HOST + ":" + PORT + BASE_CONTEXT;
    private static final String HOME_PAGE_URI = WEB_APP_URI + "/jsp/home.jsp";
    private static final String SERVICES_URI = WEB_APP_URI + REGISTRY_SERVICES_PATH;

    private static final String OWLS_TC_SERVICES = "/OWLS-TC3-MSM";

    // Ensure that these are the ones listed in shiro.ini
    private static final String ROOT_USER = "root";
    private static final String ROOT_PASSWD = "secret";
    // For HTML testing (logging via forms, etc)
    private static final WebClient webClient = new WebClient();
    private static URI testFolder;
    private static File[] msmTtlTcFiles;
    private static RegistryManager manager;

    /**
     * @throws Exception
     */
    @BeforeClass
    public static void setUp() throws Exception {

        testFolder = ServiceResourceTest.class.getResource(OWLS_TC_SERVICES).toURI();
        FilenameFilter ttlFilter = new FilenameFilterBySyntax(Syntax.TTL);
        File dir = new File(testFolder);
        msmTtlTcFiles = dir.listFiles(ttlFilter);
        int numServices = msmTtlTcFiles.length;

        // Set default values for rest assured
        RestAssured.baseURI = HOST;
        RestAssured.port = PORT;
        RestAssured.basePath = BASE_CONTEXT;

        // Setup Web client
        webClient.setThrowExceptionOnFailingStatusCode(true);
        webClient.setJavaScriptEnabled(true);
        webClient.setJavaScriptTimeout(300);
        CookieManager cookieMan = new CookieManager();
        cookieMan = webClient.getCookieManager();
        cookieMan.setCookiesEnabled(true);

        // Logout
        logOut();

        Injector injector = Guice.createInjector(new RegistryManagementModule());
        manager = injector.getInstance(RegistryManager.class);

    }

    private static void logOut() throws IOException {
        // Make sure we are logged out
        final HtmlPage homePage = webClient.getPage(HOME_PAGE_URI);
        try {
            homePage.getAnchorByHref("logout.jsp").click();
        } catch (ElementNotFoundException e) {
            //Ignore
        }
    }

    @Test
    public void logIn() throws FailingHttpStatusCodeException, IOException, InterruptedException {

        HtmlPage page = performLogin(false);
        // This'll throw an expection if not logged in  -- FIXME
//        page.getAnchorByHref("logout.jsp");

    }

    private HtmlPage performLogin(boolean rememberMe) throws IOException {
        HtmlPage page = webClient.getPage(WEB_APP_URI + "/jsp/login.jsp");
        HtmlForm form = page.getFormByName("loginform");
        form.getInputByName("username").setValueAttribute(ROOT_USER);
        form.getInputByName("password").setValueAttribute(ROOT_PASSWD);
        if (rememberMe) {
            HtmlCheckBoxInput checkbox = form.getInputByName("rememberMe");
            checkbox.setChecked(true);
        }
        return form.getInputByName("submit").click();
    }

    /**
     * Test method for AddService.
     */
    @Test
    public final void testAddService() throws IOException {
        // Clean the whole thing before testing
        try {
            manager.clearRegistry();
        } catch (SalException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        // Add all the test collections
        log.info("Uploading services");
        log.info("Test collection: " + testFolder);

        log.info("Trying without logging in");
        given().log().all().                                                                // Log requests
                redirects().follow(true).                                                       // Follow redirects introduced by Shiro
                multiPart("file", msmTtlTcFiles[0], MediaType.TEXT_TURTLE.getMediaType()).      // Submit file
                expect().log().all().                                                           // Log responses
                response().statusCode(302).                                                     // We should get a 302 that takes us to the login page
                when().post(REGISTRY_SERVICES_PATH);

        log.info("Correctly redirected");

        // Now log into Shiro and try again
        log.info("Now logging in");
        performLogin(false);
        Cookie cookie = webClient.getCookieManager().getCookie("JSESSIONID");
        log.info("Cookie data: " + cookie.toString());

        // Test oriented towards individuals.
        // To be updated with application oriented logging.

        log.info("Uploading services");
        for (int i = 0; i < MAX_DOCS && i < msmTtlTcFiles.length; i++) {
            // rest assured
            given().log().all().                                                // Log requests
                    sessionId(cookie.getValue()).                                   // Keep the session along
                    redirects().follow(true).                                       // Follow redirects introduced by Shiro
                    multiPart("file", msmTtlTcFiles[i], MediaType.TEXT_TURTLE.getMediaType()).  // Submit file
                    expect().log().all().                                           // Log responses
                    response().statusCode(201).                                     // We should get a 201 created (if we have the rights)
                    when().post(REGISTRY_SERVICES_PATH);
        }
    }

    @Test
    public void testDeleteService() throws Exception {

        String relativeUri;
        Set<URI> existingServices = manager.getServiceManager().listServices();

        log.info("Trying to delete prior to logging");
        URI testUri = existingServices.iterator().next();
        relativeUri = URI.create(SERVICES_URI).relativize(testUri).toASCIIString();
        log.info("Trying to delete service id: " + testUri);
        given().log().all().
                expect().response().statusCode(405).
                when().delete(REGISTRY_SERVICES_PATH + relativeUri);

        // Delete all without logging
        log.info("Deleting services");
        // Try to delete endpoint
        given().log().all().
                redirects().follow(true).
                expect().log().all().
                response().statusCode(302).
                when().delete(REGISTRY_SERVICES_PATH);

        // Now login and run the rest of the tests
        log.info("Now logging in");
        performLogin(false);
        Cookie cookie = webClient.getCookieManager().getCookie("JSESSIONID");
        log.info("Cookie data: " + cookie.toString());

        // Try to delete non existing svcs (directly at the graph level)
        for (int i = 0; i < 10; i++) {
            given().log().all().
                    sessionId(cookie.getValue()).
                    redirects().follow(true).
                    expect().log().all().
                    response().statusCode(404).
                    when().delete(REGISTRY_SERVICES_PATH + i);
        }

        // Try to delete non existing svcs
        for (int i = 0; i < 10; i++) {
            given().log().all().
                    sessionId(cookie.getValue()).
                    redirects().follow(true).
                    expect().log().all().
                    response().statusCode(404).
                    when().delete(REGISTRY_SERVICES_PATH + i + "/serviceName");
        }

        // Try to delete 10 services using their entire URIs
        Iterator<URI> iter = existingServices.iterator();
        for (int i = 0; i < 10 && iter.hasNext(); i++) {
            URI uri = iter.next();
            relativeUri = URI.create(SERVICES_URI).relativize(uri).toASCIIString();
            log.info("Deleting service id: " + uri);
            given().log().all().
                    sessionId(cookie.getValue()).
                    redirects().follow(true).
                    expect().log().all().
                    response().statusCode(200).
                    when().delete(REGISTRY_SERVICES_PATH + relativeUri);
        }

        // Now try to delete the whole endpoint (i.e., clear)
        given().log().all().
                sessionId(cookie.getValue()).
                redirects().follow(true).
                expect().log().all().
                response().statusCode(200).
                when().delete(REGISTRY_SERVICES_PATH);

    }
}


text:
module Connect
  class UserInfoController < Connect::ApplicationController
    before_filter :require_user_access_token

    def show
      acct = current_token.account

      keys = []
      keys += [:name, :given_name, :family_name, :preferred_username] if current_token.accessible? Scope::PROFILE
      keys += [:email] if current_token.accessible? Scope::EMAIL

      attrs = Config.account_attributes.call(acct, keys, current_token.scopes)
      attrs['sub'] = SubjectIdentifier.new(current_token.client, acct).identifier

      render json: attrs
    end

    private

    def required_scopes
      Scope::OPENID
    end
  end
end


text:
import kindred

def test_sentence_noDependencyInfo(capfd):
	text = 'mutations cause dangerous cancer'
	tokens = [ kindred.Token(w,None,None,0,0) for w in text.split() ]

	s = kindred.Sentence(text,tokens,dependencies=[])

	nodes,edges = s.extractMinSubgraphContainingNodes([0,2])
	out, err = capfd.readouterr()
	assert err.strip() == 'WARNING. 2 node(s) not found in dependency graph!'
	assert nodes == set()
	assert edges == set()

def test_sentence_brokenDependencyPath(capfd):
	text = 'mutations cause dangerous cancer'
	tokens = [ kindred.Token(w,None,None,0,0) for w in text.split() ]

	s = kindred.Sentence(text,tokens,dependencies=[(0,1,'a'),(2,3,'b')])

	nodes,edges = s.extractMinSubgraphContainingNodes([0,2])
	out, err = capfd.readouterr()
	assert err.strip() == 'WARNING. No path found between nodes 0 and 2!'
	assert nodes == set()
	assert edges == set()

def test_sentence_workingDependencyPath(capfd):
	text = 'lots of mutations cause dangerous cancer'
	tokens = [ kindred.Token(w,None,None,0,0) for w in text.split() ]

	s = kindred.Sentence(text,tokens,dependencies=[(2,3,'a'),(3,5,'b'),(4,5,'c')])

	nodes,edges = s.extractMinSubgraphContainingNodes([2,5])
	assert nodes == set([2,3,5])
	assert edges == set([(2, 3, 'a'), (3, 5, 'b')])

def test_sentence_entityAnnotations(capfd):
	text = 'lots of mutations cause dangerous cancer'
	tokens = [ kindred.Token(w,None,None,0,0) for w in text.split() ]

	e1 = kindred.Entity('thingA','mutations',[(0,1)])
	e2 = kindred.Entity('thingB','cancer',[(0,1)])

	s = kindred.Sentence(text,tokens,dependencies=[(2,3,'a'),(3,5,'b'),(4,5,'c')])

	s.addEntityAnnotation(e1,[2])
	s.addEntityAnnotation(e2,[5])

	assert s.entityAnnotations == [ (e1,[2]), (e2,[5]) ]

def test_sentence_str(capfd):
	text = 'lots of mutations cause dangerous cancer'
	tokens = [ kindred.Token(w,None,None,0,0) for w in text.split() ]

	e1 = kindred.Entity('thingA','mutations',[(0,1)])
	e2 = kindred.Entity('thingB','cancer',[(0,1)])

	s = kindred.Sentence(text,tokens,dependencies=[(2,3,'a'),(3,5,'b'),(4,5,'c')])

	s.addEntityAnnotation(e1,[2])
	s.addEntityAnnotation(e2,[5])

	assert s.__repr__() == "lots of mutations cause dangerous cancer"

def test_sentence_addEntityWithLocations(capfd):
	text = 'lots of mutations cause dangerous cancer'
	tokens = [ kindred.Token(w,None,None,0,0) for w in text.split() ]

	s = kindred.Sentence(text,tokens,dependencies=[(2,3,'a'),(3,5,'b'),(4,5,'c')])

	e1 = kindred.Entity('thingA','mutations',[(0,1)])
	e2 = kindred.Entity('thingB','cancer',[(0,1)])

	s.addEntityAnnotation(e1,[2])
	s.addEntityAnnotation(e2,[5])

	assert s.entityAnnotations == [ (e1,[2]), (e2,[5]) ]


text:
package com.octo.android.robospice.command;

import com.octo.android.robospice.SpiceManager;
import com.octo.android.robospice.SpiceService;

public class RemoveAllDataFromCacheCommand extends SpiceManager.SpiceManagerCommand<Void> {

    public RemoveAllDataFromCacheCommand(SpiceManager spiceManager) {
        super(spiceManager);
    }

    @Override
    protected Void executeWhenBound(SpiceService spiceService) {
        spiceService.removeAllDataFromCache();
        return null;
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: jonasse
 * Date: 28.09.14
 * Time: 13:22
 */

namespace Tixi\App\AppBundle\Export;

use Symfony\Component\DependencyInjection\ContainerAware;

class DrivingConfigPoolDBAL extends ContainerAware
{/*
  * Generic class for retrieving the persisted driving pools and orders
  * from the database. These can be current or past driving orders,
  * the isDeleted attributes are not regarded.
  * The scope (of the report) is one shift only.
  */

    private $query_part1;       // select ...
    private $query_part2;       // from ...
    private $query_part3;       // where ...
    private $query_part4;       // order by ...

    private function setQuery()
    {/**
     * DQL associations are predefined by the following ORM (example)
     *
     * (at)ORM\ManyToOne(targetEntity="Tixi\CoreDomain\Driver", inversedBy="drivingAssertions")
     * (at)ORM\JoinColumn(name="driver_id", referencedColumnName="id")
     * (at)var $driver Driver
     *
     * The key object is DrivingPool, all other objects/properties are derived
     * through JOINS (mandatory) and LEFT JOINS (optional) ...
     */

        $this->query_part1 =
            'SELECT '.
            'DrivingPool, DrivingMission, DrivingOrder, '.
            'Zone, Vehicle, '.
            'Shift, ShiftType, WorkingDay, '.
            'DrivingAssertion, Driver, '.
            'Passenger, Route, StartAdr, StartPOI, TargetAdr, TargetPOI ';

        $this->query_part2 =
            'FROM Tixi\CoreDomain\Dispo\DrivingPool DrivingPool '.
            'JOIN DrivingPool.drivingMissions DrivingMission '.
            'JOIN DrivingMission.drivingOrders DrivingOrder '.
            'LEFT JOIN DrivingOrder.zone Zone '.
            'LEFT JOIN DrivingPool.vehicle Vehicle '.
            'JOIN DrivingPool.shift Shift '.
            'JOIN Shift.shiftType ShiftType '.
            'JOIN Shift.workingDay WorkingDay '.
            'LEFT JOIN DrivingPool.drivingAssertion DrivingAssertion '.
            'LEFT JOIN DrivingAssertion.driver Driver '.
            'JOIN DrivingOrder.passenger Passenger '.
            'JOIN DrivingOrder.route Route '.
            'JOIN Route.startAddress StartAdr '.
            'LEFT JOIN StartAdr.pois StartPOI '.
            'JOIN Route.targetAddress TargetAdr '.
            'LEFT JOIN TargetAdr.pois TargetPOI ';

        $this->query_part3 =
            'WHERE substring(WorkingDay.date, 1, 10) = substring(?3, 1, 10) '.
            'AND ShiftType.id = ?4 ';

        $this->query_part4 =
            'ORDER BY ShiftType.name ASC, '.
            'Vehicle.name ASC, DrivingOrder.pickUpTime ASC ';
    }

    /**
     * @param \DateTime $dayTime
     * @param int $shiftTypeId
     * @return array
     */
    public function getDrivingPool(\DateTime $dayTime, $shiftTypeId)
    {/*
      * get an array of doctrine2 objects based upon the query and
      * calling arguments (date and shift)
      */
        $this->setQuery();

        $dt = $dayTime->format('Y-m-d');
        $where_clause = str_replace('?3', "'".$dt."'", $this->query_part3);
        $where_clause = str_replace('?4', $shiftTypeId, $where_clause);
        $dql = $this->query_part1.' '.
            $this->query_part2.' '.
            $where_clause.' '.
            $this->query_part4;

        /** @var \Doctrine\ORM\EntityManager $em */
        $em = $this->container->get('entity_manager');
        $query = $em->createQuery($dql);
        $result = $query->getResult(); // objects, regular join
        return $result;
    }
}


text:
<?php

namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler;

use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\SessionHandlerFactory;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\StrictSessionHandler;

/**
 * Test class for SessionHandlerFactory.
 *
 * @author Simon <simon.chrzanowski@quentic.com>
 *
 * @runTestsInSeparateProcesses
 * @preserveGlobalState disabled
 */
class SessionHandlerFactoryTest extends TestCase
{
    /**
     * @dataProvider provideConnectionDSN
     */
    public function testCreateHandler(string $connectionDSN, string $expectedPath, string $expectedHandlerType)
    {
        $handler = SessionHandlerFactory::createHandler($connectionDSN);

        $this->assertInstanceOf($expectedHandlerType, $handler);
        $this->assertEquals($expectedPath, ini_get('session.save_path'));
    }

    public function provideConnectionDSN(): array
    {
        $base = sys_get_temp_dir();

        return [
            'native file handler using save_path from php.ini' => ['connectionDSN' => 'file://', 'expectedPath' => ini_get('session.save_path'), 'expectedHandlerType' => StrictSessionHandler::class],
            'native file handler using provided save_path' => ['connectionDSN' => 'file://'.$base.'/session/storage', 'expectedPath' => $base.'/session/storage', 'expectedHandlerType' => StrictSessionHandler::class],
        ];
    }
}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">

    <item
        android:id="@+id/action_write_comment"
        android:icon="@drawable/ic_action_add_comment"
        android:title="@string/action_add_comment" />

    <item
        android:id="@+id/action_write_tag"
        android:icon="@drawable/ic_action_add_tag"
        android:title="@string/action_add_tags" />

    <item
        android:id="@+id/action_collapse_all"
        android:icon="@drawable/ic_collapse_all"
        android:title="@string/action_collapse_comments" />

    <item
        android:id="@+id/action_scroll_to_top"
        android:icon="@drawable/ic_arrow_up"
        android:title="@string/action_scroll_to_top" />

</menu>


text:
namespace device_orientation {

// Provides an easy-to-use interface to retrieve data
// from the MacBook family accelerometer.
class AccelerometerMac : public DataFetcher {
 public:
  static DataFetcher* Create();

  // Implement DataFetcher.
  virtual bool GetOrientation(Orientation* orientation);

  virtual ~AccelerometerMac();

 private:
  AccelerometerMac();
  bool Init();

  // Extend the sign of an integer of size bytes to a 32-bit one.
  static int ExtendSign(int value, size_t size);

  struct GenericMacbookSensor;
  struct SensorDescriptor;
  struct AxisData;

  // Generic sensor data and list of supported sensors.
  static const GenericMacbookSensor kGenericSensor;
  static const SensorDescriptor kSupportedSensors[];

  // Local sensor if supported, else NULL.
  const SensorDescriptor* sensor_;

  // IOKit connection to the local sensor.
  io_connect_t io_connection_;

  // Input memory used for sensor I/O.
  std::vector<char> input_record_;

  // Output memory used for sensor I/O.
  std::vector<char> output_record_;
};

}  // namespace device_orientation

#endif  // CONTENT_BROWSER_DEVICE_ORIENTATION_ACCELEROMETER_MAC_H_


text:
<!DOCTYPE html>
<!--
Copyright 2017 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<link rel="import" href="/tracing/base/base.html">

<script>
'use strict';

/**
 * @fileoverview This file contains helper functions to identify
 * FrameLoader::updateForSameDocumentNavigation events on all renderer
 * processes and find their preceding navigation start events.
 *_______________________________________________________________
 * browser:     InputLatency/NavigationControllerImpl::GoToIndex |
 *----------------------------------------
 * renderer:       LatencyInfo.Flow
 *                  WebViewImpl::handleInputEvent
 *                          FrameLoader::updateForSameDocumentNavigation
 *----------------------------------------------------
 * FrameLoader::updateForSameDocumentNavigation is called when SPA
 * in-app navigation occurs.
 * For details about how SPA in-app navigation is defined and
 * how it is found based on FrameLoader::updateForSameDocumentNavigation,
 * read the doc: https://goo.gl/1I3tqd.
 */
tr.exportTo('tr.metrics', function() {
  const HANDLE_INPUT_EVENT_TITLE = 'WebViewImpl::handleInputEvent';

  /**
   * @returns {Map.<tr.model.Slice, tr.model.Slice>} A map of the
   * elements in eventsB which immediately precede events in eventsA.
   * For instance:
   * eventsA:     A1   A2   A3   A4
   * eventsB: B1 B2  B3   B4   B5
   *  output: {A1: B2, A2: B3, A3: B4, A4: B5}
   * or
   * eventsA:     A1   A2   A3   A4
   * eventsB: B1
   *  output: {A1: B1, A2: B1, A3: B1, A4: B1}
   */
  function findPrecedingEvents_(eventsA, eventsB) {
    let events = new Map();
    let eventsBIndex = 0;
    for (let eventA of eventsA) {
      for (; eventsBIndex < eventsB.length; eventsBIndex++) {
        if (eventsB[eventsBIndex].start > eventA.start) break;
      }
      // If statement prevents the situation when eventsB is empty.
      if (eventsBIndex > 0) {
        events.set(eventA, eventsB[eventsBIndex - 1]);
      }
    }
    return events;
  }

  /**
   * @returns {Map.<tr.model.Slice, tr.model.Slice>} A map of
   * the elements in eventsB which immediately follow events
   * in eventsA.
   * For instance:
   * eventsA:  A1   A2   A3   A4
   * eventsB: B1  B2   B3  B4   B5
   *  output: {A1:B2, A2:B3, A3:B4, A4:B5}
   * or
   * eventsA:  A1   A2   A3   A4
   * eventsB:                B1
   *  output: {A1:B1, A2:B1, A3:B1}
   */
  function findFollowingEvents_(eventsA, eventsB) {
    let events = new Map();
    let eventsBIndex = 0;
    for (let eventA of eventsA) {
      for (; eventsBIndex < eventsB.length; eventsBIndex++) {
        if (eventsB[eventsBIndex].start >= eventA.start) break;
      }
      // If statement prevents the situation when eventsB is empty
      // and when it reaches the end of loop.
      if (eventsBIndex >= 0 && eventsBIndex < eventsB.length) {
        events.set(eventA, eventsB[eventsBIndex]);
      }
    }
    return events;
  }

  /**
   * @return {Array.<tr.model.Slice>} An array of events that may
   * be qualified as a SPA navigation start candidate such as
   * WebViewImpl::handleInputEvent and NavigationControllerImpl::GoToIndex.
   */
  function getSpaNavigationStartCandidates_(rendererHelper, browserHelper) {
    let isNavStartEvent = e => {
      if (e.title === HANDLE_INPUT_EVENT_TITLE && e.args.type === 'MouseUp') {
        return true;
      }
      return e.title === 'NavigationControllerImpl::GoToIndex';
    };

    return [
      ...rendererHelper.mainThread.sliceGroup.getDescendantEvents(),
      ...browserHelper.mainThread.sliceGroup.getDescendantEvents()
    ].filter(isNavStartEvent);
  }

  /**
   * @return {Array.<tr.model.Slice>} An array of SPA navigation events.
   * A SPA navigation event indicates the happening of a SPA navigation.
   */
  function getSpaNavigationEvents_(rendererHelper) {
    let isNavEvent = e => e.category === 'blink' &&
        e.title === 'FrameLoader::updateForSameDocumentNavigation';

    return [...rendererHelper.mainThread.sliceGroup.getDescendantEvents()]
        .filter(isNavEvent);
  }

  /**
   * @return {Array.<tr.model.AsyncSlice>} An array of InputLatency events from
   * the browser main thread.
   */
  function getInputLatencyEvents_(browserHelper) {
    let isInputLatencyEvent = e => e.title === 'InputLatency::MouseUp';

    return browserHelper.getAllAsyncSlicesMatching(isInputLatencyEvent);
  }

  /**
   * @return {Map.<number, tr.model.Slice>} A mapping of trace_id value
   * in each InputLatency event to the respective InputLatency event itself.
   */
  function getInputLatencyEventByBindIdMap_(browserHelper) {
    let inputLatencyEventByBindIdMap = new Map();
    for (let event of getInputLatencyEvents_(browserHelper)) {
      inputLatencyEventByBindIdMap.set(event.args.data.trace_id, event);
    }
    return inputLatencyEventByBindIdMap;
  }

  /**
   * @returns {Map.<tr.model.Slice, tr.model.AsyncSlice>} A mapping
   * from a FrameLoader update navigation slice to its respective
   * navigation start event, which can be an InputLatency async
   * slice or a NavigationControllerImpl::GoToIndex slice.
   */
  function getSpaNavigationEventToNavigationStartMap_(
      rendererHelper, browserHelper) {
    let mainThread = rendererHelper.mainThread;
    let spaNavEvents = getSpaNavigationEvents_(rendererHelper);
    let navStartCandidates = getSpaNavigationStartCandidates_(
        rendererHelper, browserHelper).sort(tr.importer.compareEvents);
    let spaNavEventToNavStartCandidateMap =
        findPrecedingEvents_(spaNavEvents, navStartCandidates);

    let inputLatencyEventByBindIdMap =
        getInputLatencyEventByBindIdMap_(browserHelper);
    let spaNavEventToNavStartEventMap = new Map();
    for (let [spaNavEvent, navStartCandidate] of
        spaNavEventToNavStartCandidateMap) {
      if (navStartCandidate.title === HANDLE_INPUT_EVENT_TITLE) {
        let inputLatencySlice = inputLatencyEventByBindIdMap.get(
            Number(navStartCandidate.parentSlice.bindId));
        if (inputLatencySlice) {
          spaNavEventToNavStartEventMap.set(spaNavEvent, inputLatencySlice);
        }
      } else {
        spaNavEventToNavStartEventMap.set(spaNavEvent, navStartCandidate);
      }
    }
    return spaNavEventToNavStartEventMap;
  }

  /**
   * @return {Array.<tr.model.Slice>} An array of first paint events.
   */
  function getFirstPaintEvents_(rendererHelper) {
    let isFirstPaintEvent = e => e.category === 'blink' &&
        e.title === 'PaintLayerCompositor::updateIfNeededRecursive';

    return [...rendererHelper.mainThread.sliceGroup.getDescendantEvents()]
        .filter(isFirstPaintEvent);
  }

  /**
   * @returns {Map.<tr.model.Slice, tr.model.Slice>} A mapping
   * from a FrameLoader update navigation slice to its respective
   * first paint slice.
   */
  function getSpaNavigationEventToFirstPaintEventMap_(rendererHelper) {
    let spaNavEvents = getSpaNavigationEvents_(
        rendererHelper).sort(tr.importer.compareEvents);
    let firstPaintEvents = getFirstPaintEvents_(
        rendererHelper).sort(tr.importer.compareEvents);

    return findFollowingEvents_(spaNavEvents, firstPaintEvents);
  }

  /**
   * @typedef {NavStartCandidates}
   * @property {tr.model.AsyncSlice} inputLatencyAsyncSlice
   * @property {tr.model.Slice} goToIndexSlice
   */

  /**
   * @typedef {SpaNavObject}
   * @property {NavStartCandidates} navStartCandidates
   * @property {tr.model.Slice} firstPaintEvent
   * @property {string} url
   */

  /**
   * @returns {Array.<SpaNavObject>}
   */
  function findSpaNavigationsOnRenderer(rendererHelper, browserHelper) {
    let spaNavEventToNavStartMap =
        getSpaNavigationEventToNavigationStartMap_(
            rendererHelper, browserHelper);
    let spaNavEventToFirstPaintEventMap =
        getSpaNavigationEventToFirstPaintEventMap_(rendererHelper);
    let spaNavigations = [];
    for (let [spaNavEvent, navStartEvent] of
        spaNavEventToNavStartMap) {
      if (spaNavEventToFirstPaintEventMap.has(spaNavEvent)) {
        let firstPaintEvent =
            spaNavEventToFirstPaintEventMap.get(spaNavEvent);
        let isNavStartAsyncSlice = navStartEvent instanceof tr.model.AsyncSlice;
        spaNavigations.push({
          navStartCandidates: {
            inputLatencyAsyncSlice:
                isNavStartAsyncSlice ? navStartEvent : undefined,
            goToIndexSlice: isNavStartAsyncSlice ? undefined : navStartEvent
          },
          firstPaintEvent: firstPaintEvent,
          url: spaNavEvent.args.url
        });
      }
    }
    return spaNavigations;
  }

  return {
    findSpaNavigationsOnRenderer,
  };
});
</script>


text:
package net.liftweb.example.comet

import _root_.net.liftweb.http._
import S._
import _root_.javax.servlet.http.{HttpServlet, HttpServletRequest , HttpServletResponse, HttpSession}
import _root_.net.liftweb.example.model._

class WebServices (val request: Req) {
  def all_users: XmlResponse = {
    XmlResponse(<all_users>{
      User.findAll.map{u => u.toXml}
    }</all_users>)
  }

  def add_user: XmlResponse = {
    var success = false
    for (firstname <- param("firstname");
         lastname <- param("lastname");
         email <- param("email")) {
      val u = new User
      u.firstName(firstname).lastName(lastname).email(email)
      param("textarea").map{v => u.textArea(v)}
      param("password").map{v => u.password(v)}
      success = u.save
    }

    XmlResponse(<add_user success={success.toString}/>)
  }
}


text:
echo "#### Running yum update"
yum update -y

echo "#### Installing the EPEL repo"
yum install epel-release -y

echo "#### Installing development tooling"
yum groupinstall 'Development Tools' -y

echo "#### Installing java8, git, ansible, etc"
yum install java-1.8.0-openjdk-devel git ansible gcc-c++ cmake strace wget psmisc lsof -y

echo "#### Adding JAVA_HOME to profile"
# Determine JAVA_HOME
WHICH_JAVA=$(which java)
if [ $? -ne 0 ]; then
  echo "ERROR: Could not find java, is it installed?"
  exit 1
fi
ALTERNATIVES_JAVA=$(readlink $WHICH_JAVA)
JAVA_HOME=$(readlink $ALTERNATIVES_JAVA | sed 's|jre/bin/java||g')
echo "export JAVA_HOME=$JAVA_HOME" >>/etc/profile

#
# Install Maven
#
echo -e "\n#### Installing Maven"
cd /tmp
wget -N http://apache.cs.utah.edu/maven/maven-3/3.5.0/binaries/apache-maven-3.5.0-bin.tar.gz
tar -xzvf apache-maven-3.5.0-bin.tar.gz -C /usr/local/bin
export M2_HOME=/usr/local/bin/apache-maven-3.5.0/
export M2=$M2_HOME/bin
export JAVA_HOME=$JAVA_HOME
export PATH=$PATH:$M2:$JAVA_HOME/bin
echo "export PATH=$PATH:$M2:$JAVA_HOME/bin" >>/etc/profile
. /etc/profile
mvn --version

#
# Docker setup
#
echo "#### Install the docker repo"
tee /etc/yum.repos.d/docker.repo <<-'EOF'
[dockerrepo]
name=Docker Repository
baseurl=https://yum.dockerproject.org/repo/main/centos/$releasever/
enabled=1
gpgcheck=1
gpgkey=https://yum.dockerproject.org/gpg
EOF

echo "#### Installing docker"
yum install docker-engine-1.12.5-1.el7.centos -y

echo "#### Configuring docker"
mkdir -p /etc/docker
cp /vagrant/files/daemon.json /etc/docker

echo "#### Starting docker"
systemctl start docker.service

#
# Maven setup
#
echo "#### Configuring maven settings"
mkdir -p /root/.m2/
cp /vagrant/files/settings.xml /root/.m2/

#
# Ansible setup
#
echo "#### Creating SSH key for ansible"
ssh-keygen -f /root/.ssh/ansible -N ''

echo "#### Adding ssh key to authorized_keys"
cat /root/.ssh/ansible.pub >> /root/.ssh/authorized_keys

echo "#### Adding ansible.cfg to avoid host key checking"
cp /vagrant/files/.ansible.cfg /root/

echo "#### Run vi mode"
echo "set -o vi" >> /root/.bashrc

exit 0


text:
class ManageIQ::Providers::Redhat::NetworkManager::MetricsCollectorWorker < ::MiqEmsMetricsCollectorWorker
  require_nested :Runner

  self.default_queue_name = "redhat_network"

  def friendly_name
    @friendly_name ||= "C&U Metrics Collector for Redhat Network"
  end

  def self.ems_class
    ManageIQ::Providers::Redhat::NetworkManager
  end

  def self.settings_name
    :ems_metrics_collector_worker_redhat_network
  end
end


text:
<?php namespace Bot;

class Message {
	/**
	 * @var string
	 */
	public $user;

	/**
	 * @var string
	 */
	private $text;

	/**
	 * @var int
	 */
	private $id;

	public function __construct($messageXml){
		$this->user = $messageXml->username->__toString();
		$this->text = $messageXml->text->__toString();
		$this->id = $messageXml['id']->__toString();
	}

	public function match($regex, &$matches = null){
		return preg_match("/{$regex}/i", $this->getText(), $matches);
	}

	/**
	 * @return string
	 */
	public function getText()
	{
		return $this->text;
	}

	/**
	 * @return string
	 */
	public function getUser()
	{
		return $this->user;
	}

	/**
	 * @return int
	 */
	public function getId()
	{
		return $this->id;
	}

	public function writtenBy($user){
		return $this->getUser() == $user;
	}
}


text:
using AutoMapper;
using GloboTicket.TicketManagement.Application.Contracts.Persistence;
using GloboTicket.TicketManagement.Application.Exceptions;
using GloboTicket.TicketManagement.Domain.Entities;
using MediatR;
using System.Threading;
using System.Threading.Tasks;

namespace GloboTicket.TicketManagement.Application.Features.Events.Commands.DeleteEvent
{
    public class DeleteEventCommandHandler : IRequestHandler<DeleteEventCommand>
    {
        private readonly IAsyncRepository<Event> _eventRepository;
        private readonly IMapper _mapper;

        public DeleteEventCommandHandler(IMapper mapper, IAsyncRepository<Event> eventRepository)
        {
            _mapper = mapper;
            _eventRepository = eventRepository;
        }

        public async Task<Unit> Handle(DeleteEventCommand request, CancellationToken cancellationToken)
        {
            var eventToDelete = await _eventRepository.GetByIdAsync(request.EventId);

            if (eventToDelete == null)
            {
                throw new NotFoundException(nameof(Event), request.EventId);
            }

            await _eventRepository.DeleteAsync(eventToDelete);

            return Unit.Value;
        }
    }
}


text:
using System;
using System.Collections.Generic;
using CompulsiveSkinPicking.Constrains;
using System.Linq;

namespace CompulsiveSkinPicking {
	class SolutionState: IBacktrackable<SolutionState> {
		public SolutionState(Problem problem) {
			Assignment = problem.CreateEmptyAssignment();
			Unsolved = problem.AllConstrains();

			// TODO: variable choice heuristic...
			VariableChoice = problem.EnumerateVariables();

			//Supports = new Dictionary<Tuple<IConstrain, Variable, int>, IVariableAssignment>(),
			//ChangedSinceLastArcCheck = new HashSet<Variable>(initial.Assignment.Variables);

			history = new Stack<History>();
		}

		private SolutionState() {
		}

		private void Log(string fmt, params object[] args) {
			Debug.WriteLine("[Asg] {0}", string.Format(fmt, args));
		}

		//public ISet<Variable> ChangedSinceLastArcCheck;
		//public Dictionary<Tuple<IConstrain, Variable, int>, IVariableAssignment> Supports;

		public IVariableAssignment Assignment;
		// TODO: generalize?
		public IExternalEnumerator<int> ValueChoice;
		public IExternalEnumerator<Variable> VariableChoice;

		public SolutionState DeepDuplicate() {
			return new SolutionState() {
				VariableChoice = VariableChoice,
				ValueChoice = ValueChoice,
				Unsolved = Unsolved.ToList(),
				Assignment = Assignment.DeepDuplicate(),
				history = new Stack<History>()
			};
		}

		private struct History {
			public IExternalEnumerator<int> ValueChoice;
			public IExternalEnumerator<Variable> VariableChoice;
			public List<IConstrain> Unsolved;
		}

		private Stack<History> history;

		public bool CanRollbackToSavepoint {
			get {
				return history.Count > 0;
			}
		}

		public void RollbackToSavepoint() {
			VariableChoice = history.Peek().VariableChoice;
			ValueChoice = history.Peek().ValueChoice;
			Unsolved = history.Peek().Unsolved;
			Assignment.RollbackToSavepoint();

			history.Pop();
		}

		public void AddSavepoint() {
			history.Push(new History() {
				ValueChoice = ValueChoice,
				VariableChoice = VariableChoice,
				Unsolved = Unsolved.ToList() // XXX slow
			});
			Assignment.AddSavepoint();
		}

		// Store a list of constrains that remain to be satisfied
		public List<IConstrain> Unsolved;

		public void MarkConstrainSolved(Constrains.IConstrain constrain) {
			Unsolved.Remove(constrain);
		}

		public bool Success { get { return Unsolved.Count == 0; } }

		private bool ResolveFullyInstantiatedConstrains() {
			// TODO: for every *just solved* constrain
			List<IConstrain> solved = new List<IConstrain>();
			foreach (var constrain in Unsolved) {
				if (constrain.Dependencies.All(v => Assignment[v].Ground)) {
					if (constrain.Satisfied(Assignment)) {
						solved.Add(constrain);
					} else {
						return false;
					}
				}
			}
			foreach (var constrain in solved) {
				MarkConstrainSolved(constrain);
			}
			return true;
		}

		public bool PropagateInitial() {
			if (!PropagateTriggers(
				    from v in Assignment.Variables
				where Assignment[v].Ground
				select PropagationTrigger.Assign(v, Assignment[v].Value)
			    )) {
				return false;
			}
			return true;
		}

		public void SetValueChoice() {
			ValueChoice = Assignment[VariableChoice.Value].EnumeratePossibleValues();
		}

		private IEnumerable<IConstrain> AffectedConstrainsOfTriggers(IEnumerable<PropagationTrigger> triggers) {
			var affectedVariables = triggers.Select(trigger => trigger.variable);
			return Unsolved.Where(constrain => constrain.Dependencies.Any(dep => affectedVariables.Contains(dep)));
		}

		private bool PropagateTriggers(IEnumerable<PropagationTrigger> inputTriggers) {
			List<PropagationTrigger> triggers = inputTriggers.ToList(); // XXX HACK
			List<PropagationTrigger> nextTriggers = new List<PropagationTrigger>();

			int round = 0;

			// TODO: kdyz se nejaka promenna ostrihala na jenom 1 prvek, tak to taky chci zpropagovat jako Assign
			while (triggers.Count > 0) {
				if (!ResolveFullyInstantiatedConstrains())
					return false;

				if (round++ > 100) {
					Debug.doDebug = true;
					Log("Round >100!");
					foreach (var trigger in triggers) {
						Log(trigger.ToString());
					}
				}

				List<Constrains.IConstrain> solved = new List<Constrains.IConstrain>();

				foreach (var constrain in AffectedConstrainsOfTriggers(triggers)) {
					Log("Propagate through {0}", constrain);
					// TODO: for the triggers that affect the constrain
					foreach (ConstrainResult result in constrain.Propagate(Assignment, triggers)) {
						Log("==> {0}", result);
						switch (result.type) {
						case ConstrainResult.Type.Failure:
							Log("Constrain {0} failed.", constrain);
							return false;
						case ConstrainResult.Type.Success:
							solved.Add(constrain);
							break;
						// TODO: constrain type "intersect"
						case ConstrainResult.Type.Restrict:
							if (Assignment[result.variable].CanBe(result.value)) {
								nextTriggers.Add(PropagationTrigger.Restrict(result.variable, result.value));
								Restrict(result.variable, result.value);

								if (!Assignment[result.variable].HasPossibleValues) {
									Log("Constrain {0} caused {1} to have empty value set", constrain, result.variable.Identifier);
									return false;
								}

								if (Assignment[result.variable].Ground) {
									nextTriggers.Add(PropagationTrigger.Assign(result.variable, Assignment[result.variable].Value));
								}
							}
							break;
						case ConstrainResult.Type.Assign:
							if (Assignment[result.variable].CanBe(result.value)) {
								nextTriggers.Add(PropagationTrigger.Assign(result.variable, result.value));
								Assign(result.variable, result.value);
								break;
							} else {
								Log("Constrain {0} assigns {1} to {2}, but that's not a possible value.", constrain, result.value, result.variable.Identifier);
								return false;
							}
						default:
							throw new Exception("Unknown constrain result"); // TODO
						}
					}
				}

				foreach (var constrain in solved) {
					Log("Constrain {0} is now solved", constrain);
					MarkConstrainSolved(constrain);
				}

				triggers = nextTriggers;
				nextTriggers = new List<PropagationTrigger>();
			}
			return true;
		}

		public void Assign(Variable variable, int value) {
			Assignment[variable].Value = value;
			/*
			if (ChangedSinceLastArcCheck != null && !ChangedSinceLastArcCheck.Contains(variable)) {
				ChangedSinceLastArcCheck.Add(variable);
			}
			*/
		}

		public void Restrict(Variable variable, int value) {
			Assignment[variable].Restrict(value);
			/*
			if (ChangedSinceLastArcCheck != null && !ChangedSinceLastArcCheck.Contains(variable)) {
				ChangedSinceLastArcCheck.Add(variable);
			}
			*/
		}

		/*
		public void Dump() {
			Console.WriteLine("Step:");
			if (VariableChoice != null && ValueChoice != null) {
				Console.WriteLine("\tWill try to assign {0} to {1}", ValueChoice.Value, VariableChoice.Value);
			}
			Console.WriteLine("\tAssignment:");
			Assignment.Dump();
		}
		*/

		public bool NextValueChoice() {
			// Skip values that are already pruned.
			do {
				bool result = ValueChoice.TryProgress(out ValueChoice);
				if (result) {
					Log("Progressed to value {0} into variable {1}.", ValueChoice.Value, VariableChoice.Value.Identifier);
				} else {
					Log("Nothing else to assign into {0}.", VariableChoice.Value.Identifier);
					return false;
				}
			} while (!Assignment[VariableChoice.Value].CanBe(ValueChoice.Value));
			return true;
		}

		public bool Progress() {
			Log("Starting progress");
			Variable variable = VariableChoice.Value;
			Log("Reading value choice");
			int value = ValueChoice.Value;

			Log("Assign: {0} <- {1}", variable, value);

			Assign(variable, value);

			Log("Assigned, propagating");
			if (!PropagateTriggers(new [] { PropagationTrigger.Assign(variable, value) })) {
				Log("Propagating assignment failed.");
				return false;
			}
			if (!ResolveFullyInstantiatedConstrains())
				return false;

			//if (!MakeArcConsistent(next)) {
			//	Log("Failed to make next step arc-consistent.");
			//	return false;
			//}

			if (VariableChoice.TryProgress(out VariableChoice)) {
				ValueChoice = Assignment[VariableChoice.Value].EnumeratePossibleValues();
			} else {
				ValueChoice = null;
			}

			return true;
		}

		public void Dump() {
			Console.WriteLine("SolutionState:");
			Assignment.Dump();
			Console.WriteLine("\tOutstanding constrains:");
			foreach (var c in Unsolved)
				Console.WriteLine("\t\t{0}", c);
		}
	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>projection — VCS 2.4.1 documentation</title>

    <link rel="stylesheet" href="../../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="../../_static/globe.png"/>
    <link rel="top" title="VCS 2.4.1 documentation" href="../../index.html" />
    <link rel="up" title="Miscellaneous Modules" href="misc.html" />
    <link rel="next" title="colormap" href="colormap.html" />
    <link rel="prev" title="animate_helper" href="animate_helper.html" />

Navigation

          index

          modules |

          next |

          previous |

VCS 2.4.1 documentation »

VCS »

Miscellaneous Modules »

projection¶

# Projection (Proj) module

class vcs.projection.Proj(Proj_name=None, Proj_name_src='default')[source]¶

The projection secondary method (Proj) is used when plotting 2D data, and define
how to project from lon/lat coord to another mapping system (lambert, mercator, mollweide, etc...)

This class is used to define a projection table entry used in VCS, or it
can be used to change some or all of the attributes in an existing
projection table entry.

Projection Transformation Package Projection Parameters

<colgroup>
<col width="32%" />
<col width="8%" />
<col width="8%" />
<col width="8%" />
<col width="8%" />
<col width="10%" />
<col width="13%" />
<col width="3%" />
<col width="3%" />
<col width="7%" />
</colgroup>

Array Element

Code & Projection Id
1
2
3
4
5
6
7
8
9

0 Geographic

1 U T M
Lon/Z
Lat/Z

2 State Plane

3 Albers Equal Area
SMajor
SMinor
STDPR1
STDPR2
CentMer
OriginLat
FE
FN

4 Lambert Conformal C
SMajor
SMinor
STDPR1
STDPR2
CentMer
OriginLat
FE
FN

5 Mercator
SMajor
SMinor

CentMer
TrueScale
FE
FN

6 Polar Stereographic
SMajor
SMinor

LongPol
TrueScale
FE
FN

7 Polyconic
SMajor
SMinor

CentMer
OriginLat
FE
FN

8 Equid. Conic A
SMajor
SMinor
STDPAR

CentMer
OriginLat
FE
FN
zero

Equid. Conic B
SMajor
SMinor
STDPR1
STDPR2
CentMer
OriginLat
FE
FN
one

9 Transverse Mercator
SMajor
SMinor
Factor

CentMer
OriginLat
FE
FN

10 Stereographic
Sphere

CentLon
CenterLat
FE
FN

11 Lambert Azimuthal
Sphere

CentLon
CenterLat
FE
FN

12 Azimuthal
Sphere

CentLon
CenterLat
FE
FN

13 Gnomonic
Sphere

CentLon
CenterLat
FE
FN

14 Orthographic
Sphere

CentLon
CenterLat
FE
FN

15 Gen. Vert. Near Per
Sphere

Height

CentLon
CenterLat
FE
FN

16 Sinusoidal
Sphere

CentMer

FE
FN

17 Equirectangular
Sphere

CentMer
TrueScale
FE
FN

18 Miller Cylindrical
Sphere

CentMer

FE
FN

19 Van der Grinten
Sphere

CentMer
OriginLat
FE
FN

20 Hotin Oblique Merc A
SMajor
SMinor
Factor

OriginLat
FE
FN
Long1

Hotin Oblique Merc B
SMajor
SMinor
Factor
AziAng
AzmthPt
OriginLat
FE
FN

21 Robinson
Sphere

CentMer

FE
FN

22 Space Oblique Merc A
SMajor
SMinor

IncAng
AscLong

FE
FN
PSRev

Space Oblique Merc B
SMajor
SMinor
Satnum
Path

FE
FN

23 Alaska Conformal
SMajor
SMinor

FE
FN

24 Interrupted Goode
Sphere

25 Mollweide
Sphere

CentMer

FE
FN

26 Interrupt Mollweide
Sphere

27 Hammer
Sphere

CentMer

FE
FN

28 Wagner IV
Sphere

CentMer

FE
FN

29 Wagner VII
Sphere

CentMer

FE
FN

30 Oblated Equal Area
Sphere

Shapem
Shapen
CentLon
CenterLat
FE
FN
Angle

<colgroup>
<col width="53%" />
<col width="12%" />
<col width="12%" />
<col width="12%" />
<col width="12%" />
</colgroup>

Array Element

Code & Projection Id
10
11
12
13

20 Hotin Oblique Merc A
Lat1
Long2
Lat2
zero

Hotin Oblique Merc B

one

22 Space Oblique Merc A
LRat
PFlag

zero

Space Oblique Merc B

one

Note

All other projections are blank (containing 0) for elements 10-13

Lon/Z

Longitude of any point in the UTM zone or zero.  If zero,
a zone code must be specified.

Lat/Z

Latitude of any point in the UTM zone or zero.  If zero, a
zone code must be specified.

SMajor

Semi-major axis of ellipsoid.  If zero, Clarke 1866 in meters
is assumed.

SMinor

Eccentricity squared of the ellipsoid if less than zero,
if zero, a spherical form is assumed, or if greater than
zero, the semi-minor axis of ellipsoid.

Sphere

Radius of reference sphere.  If zero, 6370997 meters is used.

STDPAR

Latitude of the standard parallel

STDPR1

Latitude of the first standard parallel

STDPR2

Latitude of the second standard parallel

CentMer

Longitude of the central meridian

OriginLat

Latitude of the projection origin

FE

False easting in the same units as the semi-major axis

FN

False northing in the same units as the semi-major axis

TrueScale

Latitude of true scale

LongPol

Longitude down below pole of map

Factor

Scale factor at central meridian (Transverse Mercator) or
center of projection (Hotine Oblique Mercator)

CentLon

Longitude of center of projection

CenterLat

Latitude of center of projection

Height

Height of perspective point

Long1

Longitude of first point on center line (Hotine Oblique
Mercator, format A)

Long2

Longitude of second point on center line (Hotine Oblique
Mercator, format A)

Lat1

Latitude of first point on center line (Hotine Oblique
Mercator, format A)

Lat2

Latitude of second point on center line (Hotine Oblique
Mercator, format A)

AziAng

Azimuth angle east of north of center line (Hotine Oblique
Mercator, format B)

AzmthPt

Longitude of point on central meridian where azimuth occurs
(Hotine Oblique Mercator, format B)

IncAng

Inclination of orbit at ascending node, counter-clockwise
from equator (SOM, format A)

AscLong

Longitude of ascending orbit at equator (SOM, format A)

PSRev

Period of satellite revolution in minutes (SOM, format A)

LRat

Landsat ratio to compensate for confusion at northern end
of orbit (SOM, format A – use 0.5201613)

PFlag

End of path flag for Landsat:  0 = start of path,
1 = end of path (SOM, format A)

Satnum

Landsat Satellite Number (SOM, format B)

Path

Landsat Path Number (Use WRS-1 for Landsat 1, 2 and 3 and
WRS-2 for Landsat 4, 5 and 6.)  (SOM, format B)

Shapem

Oblated Equal Area oval shape parameter m

Shapen

Oblated Equal Area oval shape parameter n

Angle

Oblated Equal Area oval rotation angle

Array Elements:

Array elements 14 and 15 are set to zero

All array elements with blank fields are set to zero

All angles (latitudes, longitudes, azimuths, etc.) are entered in packed

degrees/ minutes/ seconds (DDDMMMSSS.SS) format

Space Oblique Mercator A projection:

A portion of Landsat rows 1 and 2 may also be seen as parts of rows

246 or 247.  To place these locations at rows 246 or 247, set the end of
path flag (parameter 11) to 1–end of path.  This flag defaults to zero.

When Landsat-1,2,3 orbits are being used, use the following values

for the specified parameters:

Parameter 4   099005031.2

Parameter 5   128.87 degrees - (360/251 * path number) in packed DMS format

Parameter 9   103.2669323

Parameter 10  0.5201613

When Landsat-4,5 orbits are being used, use the following values

for the specified parameters:

Parameter 4   098012000.0

Parameter 5   129.30 degrees - (360/233 * path number) in packed DMS format

Parameter 9   98.884119

Parameter 10  0.5201613

Note

In vcs angles can be entered either in DDDMMMSSS or regular angle format.

Useful Functions:

# VCS Canvas Constructor
a=vcs.init()
# Show predefined projection secondary methods
a.show('projection')

Create a Canvas object to work with:

a=vcs.init()

Create a new instance of projection:

# Copies content of 'quick' to 'new'
p=a.createprojection('new','quick')
# Copies content of 'default' to 'new'
p=a.createprojection('new')

Modify an existing projection:

p=a.getprojection('lambert')
# List all the projection attribute values
p.list()
p.type='lambert'
# Fill a list with projection parameter values
params= []
for _ in range(0,14):
   params.append(1.e20)
# params now a list with 1.e20, 15 times
p.parameters= params
iso=x.createisoline('new')
iso.projection=p
# or
iso.projection='lambert'

script(script_filename=None, mode=None)[source]¶

Saves out a copy of the projection graphics method in JSON, or Python format to a designated file.

Note

If the the filename has a ‘.py’ at the end, it will produce a
Python script. If no extension is given, then by default a
.json file containing a JSON serialization of the object’s
data will be produced.

Warning

VCS Scripts Deprecated.
SCR script files are no longer generated by this function.

<col class="field-name" />
<col class="field-body" />

Example:

>>> a=vcs.init() # Make a Canvas object to work with
>>> ex=a.getprojection() # Get default projection
>>> ex.script('filename.py') # Append to a Python script named 'filename.py'
>>> ex.script('filename','w') # Create or overwrite a JSON file 'filename.json'.

Parameters:

script_filename (str) – Output name of the script file. If no extension is specified, a .json object is created.

mode (str) – Either ‘w’ for replace, or ‘a’ for append. Defaults to ‘a’, if not specified.

Previous topic

animate_helper

Next topic

colormap

This Page

Show Source

Quick search

    <form class="search" action="../../search.html" method="get">

<input type="text" name="q" />

<input type="submit" value="Go" />

      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

Navigation

          index

          modules |

          next |

          previous |

VCS 2.4.1 documentation »

VCS »

Miscellaneous Modules »

        © Copyright 2016, LLNL.
      Created using Sphinx 1.4.6.


text:
@interface musicRandomizer ()

@property NSArray* musicNames;

@property NSMutableArray* musicArray;

@property OALAudioTrack* previousTrack;

-(OALAudioTrack*)getRandomTrack;

@end

@implementation musicRandomizer

-(id)init{
    self = [super init];
    self.musicArray = [NSMutableArray arrayWithCapacity:10];
    self.musicNames = [NSArray arrayWithObjects:@"Party.mp3", @"Dieseldotogg.mp3", nil];
    for (NSString* musicTitle in self.musicNames){
        OALAudioTrack* tempTrack = [[OALAudioTrack alloc] init];
        [tempTrack preloadFileAsync:musicTitle target:nil selector:nil];
        [self.musicArray addObject:tempTrack];
    }
    return self;
}

-(void)update:(CCTime)delta{
    if (self.previousTrack.playing == false || self.previousTrack == nil){
        self.previousTrack = [self getRandomTrack];
        [self.previousTrack play];

    }
}

-(OALAudioTrack*)getRandomTrack{
    return [self.musicArray objectAtIndex:arc4random_uniform((unsigned int)self.musicArray.count)];
}

-(void)dealloc{
    [self.previousTrack stop];
}

@end


text:
import {
  BotState, SourceFwConfig,
  ControlPanelState, Axis, ShouldDisplay, SourceFbosConfig,
} from "../../devices/interfaces";
import { McuParamName, McuParams, FirmwareHardware, Xyz } from "farmbot";
import { IntegerSize } from "../../util";
import { FirmwareConfig } from "farmbot/dist/resources/configs/firmware";
import { ResourceIndex } from "../../resources/interfaces";
import { DeviceSetting } from "../../constants";
import { GetWebAppConfigValue } from "../../config_storage/actions";

export interface ZeroRowProps {
  botDisconnected: boolean;
}

export interface AxisSettingsProps {
  dispatch: Function;
  bot: BotState;
  controlPanelState: ControlPanelState;
  sourceFwConfig: SourceFwConfig;
  sourceFbosConfig: SourceFbosConfig;
  firmwareConfig: FirmwareConfig | undefined;
  botOnline: boolean;
  firmwareHardware: FirmwareHardware | undefined;
  shouldDisplay: ShouldDisplay;
}

export interface BooleanMCUInputGroupProps {
  sourceFwConfig: SourceFwConfig;
  firmwareHardware: FirmwareHardware | undefined;
  dispatch: Function;
  tooltip: string;
  label: DeviceSetting;
  x: McuParamName;
  y: McuParamName;
  z: McuParamName;
  disable?: Record<Xyz, boolean>;
  grayscale?: Record<Xyz, boolean>;
  caution?: boolean | undefined;
  displayAlert?: string | undefined;
  disabled?: boolean;
  disabledBy?: string;
}

export interface CalibrationRowProps {
  type: "find_home" | "calibrate" | "zero";
  mcuParams: McuParams;
  arduinoBusy: boolean;
  botOnline: boolean;
  action(axis: Axis): void;
  toolTip: string;
  title: DeviceSetting;
  axisTitle: string;
  stallUseDisabled?: boolean;
}

export interface NumericMCUInputGroupProps {
  sourceFwConfig: SourceFwConfig;
  firmwareHardware: FirmwareHardware | undefined;
  dispatch: Function;
  tooltip: string;
  label: DeviceSetting;
  x: McuParamName;
  xScale?: number;
  y: McuParamName;
  yScale?: number;
  z: McuParamName;
  zScale?: number;
  float?: boolean;
  intSize?: IntegerSize;
  gray?: Record<Xyz, boolean>;
  min?: number;
  max?: number;
  disabled?: boolean;
  disabledBy?: string;
}

export interface PinGuardMCUInputGroupProps {
  sourceFwConfig: SourceFwConfig;
  firmwareHardware: FirmwareHardware | undefined;
  dispatch: Function;
  label: DeviceSetting;
  pinNumKey: McuParamName;
  timeoutKey: McuParamName;
  activeStateKey: McuParamName;
  resources: ResourceIndex;
  disabled: boolean;
}

export interface PinGuardProps {
  dispatch: Function;
  controlPanelState: ControlPanelState;
  sourceFwConfig: SourceFwConfig;
  firmwareHardware: FirmwareHardware | undefined;
  resources: ResourceIndex;
  arduinoBusy: boolean;
}

export interface MotorsProps {
  dispatch: Function;
  controlPanelState: ControlPanelState;
  sourceFwConfig: SourceFwConfig;
  firmwareHardware: FirmwareHardware | undefined;
  arduinoBusy: boolean;
  shouldDisplay: ShouldDisplay;
}

export interface EncodersOrStallDetectionProps {
  dispatch: Function;
  controlPanelState: ControlPanelState;
  sourceFwConfig: SourceFwConfig;
  firmwareHardware: FirmwareHardware | undefined;
  shouldDisplay: ShouldDisplay;
  arduinoBusy: boolean;
}

export interface LimitSwitchesProps {
  dispatch: Function;
  controlPanelState: ControlPanelState;
  sourceFwConfig: SourceFwConfig;
  firmwareHardware: FirmwareHardware | undefined;
  arduinoBusy: boolean;
}

export interface ErrorHandlingProps {
  dispatch: Function;
  controlPanelState: ControlPanelState;
  sourceFwConfig: SourceFwConfig;
  firmwareHardware: FirmwareHardware | undefined;
  arduinoBusy: boolean;
}

export interface ParameterManagementProps {
  dispatch: Function;
  controlPanelState: ControlPanelState;
  onReset(): void;
  sourceFwConfig: SourceFwConfig;
  firmwareConfig: FirmwareConfig | undefined;
  firmwareHardware: FirmwareHardware | undefined;
  getConfigValue: GetWebAppConfigValue;
  botOnline: boolean;
  arduinoBusy: boolean;
  shouldDisplay: ShouldDisplay;
}


text:
package rest

import "reflect"

func PayloadMember(i interface{}) interface{} {
	if i == nil {
		return nil
	}

	v := reflect.ValueOf(i).Elem()
	if !v.IsValid() {
		return nil
	}
	if field, ok := v.Type().FieldByName("SDKShapeTraits"); ok {
		if payloadName := field.Tag.Get("payload"); payloadName != "" {
			field, _ := v.Type().FieldByName(payloadName)
			if field.Tag.Get("type") != "structure" {
				return nil
			}

			payload := v.FieldByName(payloadName)
			if payload.IsValid() || (payload.Kind() == reflect.Ptr && !payload.IsNil()) {
				return payload.Interface()
			}
		}
	}
	return nil
}

func PayloadType(i interface{}) string {
	v := reflect.Indirect(reflect.ValueOf(i))
	if !v.IsValid() {
		return ""
	}
	if field, ok := v.Type().FieldByName("SDKShapeTraits"); ok {
		if payloadName := field.Tag.Get("payload"); payloadName != "" {
			if member, ok := v.Type().FieldByName(payloadName); ok {
				return member.Tag.Get("type")
			}
		}
	}
	return ""
}


text:
# Laravel 4 Notification
======

A basic starting point for a flexible user notification system in Laravel 4.

It is easily extendable with new notification types and leaves rendering completely up to you.

This package only provides an extendable notification system without any controllers or views
since they are often very use case specific.

I'm open to ideas for extending this package.

## Fork
This fork allows for:
* Notifications which can be read by any user with a specific role or permission
* Different namespaces for specific notification implementations
* Array or object as attached data

## Installation

### 1. Install with Composer

Add the following to your `composer.json` and run **composer update**

```json
	"require": {
		//...
		"tricki/laravel-notification": "dev-master"
	},
	"repositories": [
        {
            "type": "vcs",
            "url": "https://github.com/Feijs/laravel-notification"
        }
    ],
```

### 2. Add to Providers in `config/app.php`

```php
    'providers' => [
        // ...
        'Tricki\Notification\NotificationServiceProvider',
    ],
```

This registers the package with Laravel and automatically creates an alias called
`Notification`.

### 3. Publishing config

You may specify whether your project uses `Role` and `Permission` classes as defined in `Zizaco\Entrust`. This is on by default.
If your project does not, or you want to use only users as observers, you need to change this in the config.

Publish the package configuration using Artisan:

```bash
php artisan config:publish tricki/laravel-notification
```

Set the `entrust` property of the newly created `app/config/packages/tricki/laravel-notification/config.php`
to false

### 4. Executing migration

```bash
php artisan migrate --package="tricki/laravel-notification"
```

This will create the tables **notifications** and **notification_observer**

## Usage

### 1. Define notification models

The class `Models\Notification` may be extended for application specific functionality.
Some examples would be `PostLikedNotification` or `CommentPostedNotification`.

These models define the unique behavior of each notification type, such as it's actions
and rendering.

A minimal notification model looks like this:

```php
<?php namespace MyApp;

class PostLikedNotification extends \Tricki\Notification\Models\Notification
{
	protected $isSuperType = false;
    protected $isSubType = true;
	public static $type = 'MyApp\PostLikedNotification';
}
```

The type variable is used to differentiate the various notification types while retaining a single database table
(single-table inheritance). The class name **must** be the namespaced class.

### 2. Create a notification

Notifications can be created using `Notification::create`.

The function takes 5 parameters:

 * **$type** string
   The notification type (see [Define notification models](#1-define-notification-models))
 * **$observers** array | Collection
   Any users, roles and permissions which may read this notification
 * **$sender** Model | Null
   An object that initiated the notification (a user, a group, a web service etc.)
 * **$object** Model | Null
   An object that was changed (a post that has been liked).
 * **$data** mixed | Null
   Any additional data you want to attach. This will be serialized into the database.

### 3. Get an instance of `Model\Notification`

You will need one to fetch or update notifications

```php
use \Tricki\Notification\Models\Notification as NotificationModel;
public function __construct(NotificationModel $notification)
{
	 $this->notification = $notification;
}

// Or

$this->notification = App::make('Tricki\Notification\Model\Notification');

//Or

use \Tricki\Notification\Model\Notification as NotificationModel;

$this->notification = new NotificationModel;
```

### 4. Retrieving notifications

To get a collection of notifications a user may read:

```php
$user = User::find($id);

$read 	= $this->notification->fetch($user, true);
$unread = $this->notification->fetch($user, false);
```

This will return any notifications the user may read, based on itself and it's attached roles and permissions.

### 5. Mark as read

A notification may be marked as read with the `markRead` method.

```php
	$instance = $this->notification->find($notification_id);
	if(!is_null($instance)) {
		$instance->markRead($user->id);
	}
```

It will only be marked as read for this specific user. If attached to a role or permission,
other users with this role or permission will still see this notification as unread.

## Example:

```php
<?php namespace MyApp;

class PostLikedNotification extends \Tricki\Notification\Models\Notification
{
	public static $type = 'MyApp\PostLikedNotification';

	/**
     * Return the main title for this message
     * @return string
     */
    public function getTitleAttribute()
    {
    	return isset($this->data['title']) ? $this->data['title'] : "Post liked";
    }

    /**
     * Return the url for a corresponding action
     * @return string
     */
    public function getActionUrl()
    {
    	return app()['url']->to('posts/' . $this->object->id);
    }
}

```


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Beyond the End</title>
  <meta name="description" content="He is shamelessly happyto take out the trash.He descends the spiral staircaseand follows the stone pathlaid out to the can. Well, no longer a can-more like g...">

    <link href='//fonts.googleapis.com/css?family=Lato:400,400italic' rel='stylesheet' type='text/css'>

  <link rel="stylesheet" type="text/css" href="/css/tufte.css">

  <link rel="canonical" href="/february2016/2016/02/15/1.html">

  <link rel="alternate" type="application/rss+xml" title="Alien Mouth" href="/feed.xml" />

		about
		books
		connect
		submit

Beyond the End

by Janelle Rainerz on February 15, 2016

He is shamelessly happy

to take out the trash.

He descends the spiral staircase

and follows the stone path

laid out to the can.

Well, no longer a can-

more like giant Tupperware

with wheels. Late October,

winter on the way.

He has a smoke in the alley.

The neighborhood is dying-

everyone is moving closer

to downtown, closer

to the ache of the city.

He doesn't mind-

popularity is unusable.

This row of Victorians

used to be elegant, similar

to the photograph of an actress

long dead, or almost there.

Only a matter of time before

the block is bought up

and leveled for something

monstrous and profitable.

We must be brave when everything

is taken away. He exhales

and looks up to where

the moon should be, but is not.

His beard is more white

than gray, his eyes

more closed than open.

    Beyond the End - February 15, 2016 -


text:
package main

import (
	"bytes"
	"fmt"
	"github.com/garyburd/redigo/redis"
	"strings"
	"time"
)

//Channel...
//represents an irc channel
type Channel struct {
	name      string
	epoch     time.Time
	userlist  map[int]*User
	usermodes map[*User]string
	banlist   map[int]*Ban
	cmodes    string
	topic     string
	topichost string
	topictime int64
}

func (channel *Channel) SetTopic(newtopic string, hostmask string) {
	channel.topic = newtopic
	channel.topichost = hostmask
	channel.topictime = time.Now().Unix()
	channel.SendLinef(":%s TOPIC %s :%s", hostmask, channel.name, newtopic)
}

func NewChannel(newname string) *Channel {
	chann := &Channel{name: newname, epoch: time.Now()}
	chann.userlist = make(map[int]*User)
	chann.usermodes = make(map[*User]string)
	chann.banlist = make(map[int]*Ban)
	chanlist[strings.ToLower(chann.name)] = chann
	chann.cmodes = config.DefaultCmode
	log.Printf("Channel %s created", chann.name)
	return chann
}

func (channel *Channel) len() int {
	k := len(channel.userlist)
	var check bool
	for _, k := range config.LogChannels {
		if channel == GetChannelByName(k) {
			check = true
			break
		}
	}
	if channel.HasUser(SystemUser) && !check {
		k--
	}
	return k
}

func (channel *Channel) JoinUser(user *User) {
	channel.userlist[user.id] = user
	if channel.len() == 1 {
		channel.usermodes[user] = "o"
		if config.SystemJoinChannels {
			SystemUser.JoinHandler([]string{"JOIN", channel.name})
		}
	}
	channel.SendLinef(":%s JOIN %s", user.GetHostMask(), channel.name)
	if len(channel.topic) > 0 {
		channel.FireTopic(user)
	}
	channel.FireNames(user)
}

func (channel *Channel) GetUserPrefix(user *User) string {
	if strings.Contains(channel.usermodes[user], "o") {
		return "@"
	}
	if strings.Contains(channel.usermodes[user], "v") {
		return "+"
	}
	return ""
}

func (channel *Channel) FireTopic(user *User) {
	if len(channel.topic) > 0 {
		user.FireNumeric(RPL_TOPIC, channel.name, channel.topic)
		user.FireNumeric(RPL_TOPICWHOTIME, channel.name, channel.topichost, channel.topictime)
	} else {
		user.FireNumeric(RPL_NOTOPIC, channel.name)
	}
}

func (channel *Channel) FireNames(user *User) {
	var buffer bytes.Buffer
	for _, k := range channel.userlist {
		if buffer.Len()+len(channel.GetUserPrefix(k))+len(user.nick) > 500 {
			user.FireNumeric(RPL_NAMEPLY, channel.name, strings.TrimSpace(buffer.String()))
			buffer.Reset()
		}
		buffer.WriteString(channel.GetUserPrefix(k))
		buffer.WriteString(k.nick)
		buffer.WriteString(" ")
	}
	if buffer.Len() > 1 {
		resp := strings.TrimSpace(buffer.String())
		user.FireNumeric(RPL_NAMEPLY, channel.name, resp)
	}
	user.FireNumeric(RPL_ENDOFNAMES, channel.name)
}

func (channel *Channel) GetUserList() []*User {
	list := []*User{}
	for _, k := range channel.userlist {
		list = append(list, k)
	}
	return list
}

func (channel *Channel) GetUserPriv(user *User) int {
	score := 0
	if strings.Contains(channel.usermodes[user], "o") {
		score += 100
	}
	if strings.Contains(channel.usermodes[user], "v") {
		score += 10
	}
	if user.oper {
		score += 1000
	}
	return score
}

func (channel *Channel) ShouldIDie() {
	if channel.len() < 1 {
		if channel.HasUser(SystemUser) {
			SystemUser.PartHandler([]string{"PART", channel.name})
		}
		delete(chanlist, strings.ToLower(channel.name))
		log.Printf("Channel %s has no users, destroying\n", channel.name)
	}
}

func (channel *Channel) FireModes(user *User) {
	user.FireNumeric(RPL_CHANNELMODEIS, channel.name, channel.cmodes)
	user.FireNumeric(RPL_CREATIONTIME, channel.name, channel.epoch.Unix())
}

func (channel *Channel) HasMode(mode string) bool {
	if strings.Contains(channel.cmodes, mode) {
		return true
	} else {
		return false
	}
}

func (channel *Channel) SetUmode(user *User, changing *User, mode string) {
	if channel.CheckYourPrivlege(changing) {
		return
	}
	if !strings.Contains(channel.usermodes[user], mode) {
		channel.usermodes[user] = channel.usermodes[user] + mode
		channel.SendLinef(":%s MODE %s +%s %s", changing.GetHostMask(), channel.name, mode, user.nick)
	}
}

func (channel *Channel) UnsetUmode(user *User, changing *User, mode string) {
	if channel.CheckYourPrivlege(changing) {
		return
	}
	if strings.Contains(channel.usermodes[user], mode) {
		channel.usermodes[user] = strings.Replace(channel.usermodes[user], mode, "", 1)
		channel.SendLinef(":%s MODE %s -%s %s", changing.GetHostMask(), channel.name, mode, user.nick)
	}
}

func (channel *Channel) SetMode(mode string, changing *User) {
	if channel.CheckYourPrivlege(changing) {
		return
	}
	if !strings.Contains(channel.cmodes, mode) {
		channel.cmodes = channel.cmodes + mode
		channel.SendLinef(":%s MODE %s +%s", changing.GetHostMask(), channel.name, mode)
	}
}

func (channel *Channel) UnsetMode(mode string, changing *User) {
	if channel.CheckYourPrivlege(changing) {
		return
	}
	if strings.Contains(channel.cmodes, mode) {
		channel.cmodes = strings.Replace(channel.cmodes, mode, "", 1)
		channel.SendLinef(":%s MODE %s -%s", changing.GetHostMask(), channel.name, mode)
	}
}

func (channel *Channel) HasUser(user *User) bool {
	if channel.userlist[user.id] == user {
		return true
	} else {
		return false
	}
}

func (channel *Channel) SendLinef(msg string, args ...interface{}) {
	for _, k := range channel.userlist {
		k.SendLine(fmt.Sprintf(msg, args...))
	}
}

func (channel *Channel) CheckYourPrivlege(user *User) bool {
	if channel.GetUserPriv(user) < 100 {
		//SHITLORD!
		user.FireNumeric(ERR_CHANOPRIVSNEEDED, channel.name)
		return true //privlege successfully checked.
	} else {
		return false
	}
}

func (channel *Channel) SetBan(m string, user *User) {
	if channel.CheckYourPrivlege(user) {
		return
	}
	if GetBanByMask(channel, m) != nil {
		return
	}
	hm := user.GetHostMask()
	b := NewBan(m, hm)
	channel.banlist[b.id] = b
	channel.SendLinef(":%s MODE %s +b %s", hm, channel.name, m)
}

func (channel *Channel) UnsetBan(m string, user *User) {
	if channel.CheckYourPrivlege(user) {
		return
	}
	ban := GetBanByMask(channel, m)
	if ban != nil {
		delete(channel.banlist, ban.id)
		channel.SendLinef(":%s MODE %s -b %s", user.GetHostMask(), channel.name, ban.mask)
	}
}

func (channel *Channel) IsUserBanned(user *User) bool {
	hm := user.GetHostMask()
	for _, k := range channel.banlist {
		if WildcardMatch(hm, k.mask) {
			return true
		}
	}
	return false
}

func (channel *Channel) FireBanlist(user *User) {
	for _, b := range channel.banlist {
		user.FireNumeric(RPL_BANLIST, channel.name, b.mask, b.whoset, b.ts.Unix())
	}
	user.FireNumeric(RPL_ENDOFBANLIST, channel.name)
}

func (channel *Channel) IsLogChan() bool {
	me := strings.ToLower(channel.name)
	for _, k := range config.LogChannels {
		if me == strings.ToLower(k) {
			return true
		}
	}
	return false
}

func (channel *Channel) GetCount() (int64, error) {
	p := RedisPool.Get()
	c, err := redis.Int64(p.Do("INCR", fmt.Sprintf("echochat:counter:%s", channel.name)))
	if err != nil {
		return 0, err
	} else {
		return c, nil
	}
}