text:
package com.github.dnvriend.fp

import com.github.dnvriend.TestSpec

import scalaz._
import Scalaz._

class CollectionsTest extends TestSpec {

  /* scala has the following collection hierarchy
   see: http://stackoverflow.com/questions/1722137/scala-2-8-collections-design-tutorial

                     Traversable
                         |
                         |
                      Iterable
                         |
      +------------------+---------------------------+
     Map                Set                         Seq
      |                  |                           |
      |             +----+----+         +-----------------------+
    Sorted Map  SortedSet   BitSet   IndexedSeq              LineairSeq
                               (Vector, Range, String)  (List, Stream, Queue, Stack)
   */

  "IndexedSeq (Vector)" should "have map, flatMap and Filter" in {
    // IndexedSeq collections are optimized for contant-time or near constant-time access
    // and length computations. It provides random access and updates in constant time, as
    // well as very fast append and prepend.
    val xs: Vector[Int] = Vector(1, 2, 3, 4, 5)
    xs.head shouldBe 1
    xs.headOption shouldBe Some(1)
    xs.tail shouldBe Vector(2, 3, 4, 5)
    xs.last shouldBe 5
    xs.count(_ == 2) == 1
    xs.diff(Vector(2, 3, 4)) shouldBe Vector(1, 5)
    xs.exists(_ > 3) shouldBe true
    xs.intersect(Vector(2, 3)) shouldBe Vector(2, 3)
    xs.union(Vector(2, 3)) shouldBe Vector(1, 2, 3, 4, 5, 2, 3)
    xs.union(Vector(2, 3)).distinct shouldBe Vector(1, 2, 3, 4, 5)
    xs.drop(1) shouldBe Vector(2, 3, 4, 5)
    xs.drop(1).dropRight(1) shouldBe Vector(2, 3, 4)
    xs.dropWhile(_ <= 2) shouldBe Vector(3, 4, 5)
    xs.filter(_ % 2 == 0) shouldBe Vector(2, 4)
    xs.filterNot(_ % 2 == 0) shouldBe Vector(1, 3, 5)
    xs.map(_ * 2).find(_ == 5) shouldBe None
    xs.map(_ * 2).find(_ == 10) shouldBe Some(10)

    // do *all* the elements conform to the predicate?
    xs.forall(_ < 10) shouldBe true

    xs.foldLeft(1)(_ + _)
    xs.sum shouldBe 1 + 2 + 3 + 4 + 5

    val xx = for (x <- xs) yield x * 2
    xx shouldBe Vector(2, 4, 6, 8, 10)

    // the Vector can also be created like this
    val xy = for (x <- 1 to 5) yield x * 2
    xy shouldBe Vector(2, 4, 6, 8, 10)

    val xz = for (x <- 1 to 5 if x > 2) yield x
    xz shouldBe Vector(3, 4, 5)

    xs.foldLeft(1)(_ * _) shouldBe 120
    xs.product shouldBe 120

    // reduceLeft is a special case of foldLeft, in which the type of the
    // resulting value is the same type or a supertype of the collection's type.
    // with foldLeft the result type doesn't even *have to be related to* the collection type,
    // it could be a String // see: http://stackoverflow.com/questions/7764197/difference-between-foldleft-and-reduceleft-in-scala
    xs.reduceLeft(_ + _) shouldBe 15

    Vector(1, 2) ++ Vector(3, 4) shouldBe Vector(1, 2, 3, 4)

    Vector(1, 2, 3) zip Vector(4, 5, 6) shouldBe Vector((1, 4), (2, 5), (3, 6))

    //    Vector(1, 2, 1, 3, 3, 4, 5, 5).groupBy(identity) should contain allOf (
    //      5 → Vector(5, 5), 1 → Vector(1, 1), 2 → Vector(2), 3 → Vector(3, 3), 4 → Vector(4)
    //    )

    xs.mkString(", ") shouldBe "1, 2, 3, 4, 5"
    xs.partition(_ < 2) shouldBe (Vector(1), Vector(2, 3, 4, 5))
    xs.slice(2, 4) shouldBe Vector(3, 4)
    xs.zip(Vector(5, 6, 7)) shouldBe Vector((1, 5), (2, 6), (3, 7))
    Vector(5, 6, 7).zipWithIndex shouldBe Vector((5, 0), (6, 1), (7, 2))
  }

  "Lineair Seq (List)" should "have map, flatMap and Filter" in {
    // Lists are optimized for Sequential Scan (it is a LineairSeq)
    val xs: List[Int] = List(1, 2, 3, 4, 5)
    xs.head shouldBe 1
    xs.last shouldBe 5
    xs.drop(1) shouldBe List(2, 3, 4, 5)
    xs.drop(1).dropRight(1) shouldBe List(2, 3, 4)
    xs.filter(_ % 2 == 0) shouldBe List(2, 4)
    xs.filterNot(_ % 2 == 0) shouldBe List(1, 3, 5)
    xs.map(_ * 2).find(_ == 5) shouldBe None
    xs.map(_ * 2).find(_ == 10) shouldBe Some(10)

    xs.sum shouldBe 1 + 2 + 3 + 4 + 5

    val xx = for (x <- xs) yield x * 2
    xx shouldBe List(2, 4, 6, 8, 10)

    val xz = for (x <- 1 to 5 if x > 2) yield x
    xz shouldBe List(3, 4, 5)

    xs.foldLeft(1) { _ * _ } shouldBe 120
  }

  "Arrays (mutable)" should "have map, flatMap and Filter" in {
    // an Array is a *mutable* indexed collection of values, and is 100%
    // compatible with Java's Array, the T[]
    val xs: Array[Int] = Array(1, 2, 3, 4, 5)
    xs.head shouldBe 1
    xs.last shouldBe 5
    xs.drop(1) shouldBe Array(2, 3, 4, 5)
    xs.drop(1).dropRight(1) shouldBe Array(2, 3, 4)
    xs.filter(_ % 2 == 0) shouldBe Array(2, 4)
    xs.filterNot(_ % 2 == 0) shouldBe Array(1, 3, 5)
    xs.map(_ * 2).find(_ == 5) shouldBe None
    xs.map(_ * 2).find(_ == 10) shouldBe Some(10)

    xs.sum shouldBe 1 + 2 + 3 + 4 + 5

    val xx = for (x <- xs) yield x * 2
    xx shouldBe Array(2, 4, 6, 8, 10)

    val xz = for (x <- 1 to 5 if x > 2) yield x
    xz shouldBe Array(3, 4, 5)

    xs.foldLeft(1) { _ * _ } shouldBe 120
  }

  // manual map, flatMap and filter

  def filter[A](seq: Seq[A])(p: A => Boolean): Seq[A] = {
    def helper(src: Seq[A], xs: Seq[A]): Seq[A] = src match {
      case Nil          => xs
      case head +: tail => if (p(head)) helper(tail, xs :+ head) else helper(tail, xs)
    }
    helper(seq, Nil)
  }

  def map[A, B](seq: Seq[A])(f: A => B): Seq[B] = {
    def helper(src: Seq[A], xs: Seq[B]): Seq[B] = src match {
      case Nil          => xs
      case head +: tail => helper(tail, xs :+ f(head))
    }
    helper(seq, Nil)
  }

  def flatMap[A, B](seq: Seq[A])(f: A => Seq[B]): Seq[B] = {
    def helper(src: Seq[A], xs: Seq[B]): Seq[B] = src match {
      case Nil          => xs
      case head +: tail => helper(tail, xs ++ f(head))
    }
    helper(seq, Nil)
  }

  "manual map" should "evaluate correctly" in {
    map(Seq(1, 2, 3)) { _.toDouble } shouldBe Seq(1, 2, 3).map(_.toDouble)
  }

  "manual flatMap" should "evaluate correctly" in {
    flatMap(Seq(1, 2, 3)) { _ => Seq(1, 2, 3) } shouldBe Seq(1, 2, 3).flatMap(_ => Seq(1, 2, 3))
  }

  "manual filter" should "evaluate correctly" in {
    filter(Seq(1, 2, 3)) { _ % 2 == 0 } shouldBe Seq(1, 2, 3).filter(_ % 2 == 0)
  }

  /**
   * see: http://www.47deg.com/blog/adventures-with-scala-collections
   *
   * Seq, List or Vector, that is the question
   *
   * In most projects, we have to deal with sequences of objects (User from the database, Shop Products, etc.).
   * However, sometimes as developers, we don't think about which one is a better fit for the topology of our algorithms,
   * so we don't see this question arise before development begins. We'd like to change that by putting the various options
   * on the table to motivate people to discuss which option is the best course early on.
   *
   * Let's figure out whether Seq, List or Vector better match our needs, based on these four main points:
   *
   * - Mutability
   * - Performance
   * - Usability (Pattern matching)
   * - Law Abiding
   */

  /**
   * Seq: A base trait for sequences. There isn't a lot that needs to be said so, let's discuss our key points.
   *
   * Seq - Mutability:
   * The first thing to realize is that the default version you'll be using if you don't import anything special
   * will be the Seq trait located on scala.collections.Seq. In fact, if you look at the code within the scala package
   * object, we can find:
   *
   * type Seq[+A] = scala.collection.Seq[A]
   * val Seq = scala.collection.Seq
   *
   * Keeping this in mind, let's put together an example where we're designing our API and have a method that is
   * receiving a Seq parameter:
   *
   * def proccessSequence(coll: Seq[Int]) = ???
   *
   * As you can imagine, our proccessSequence function can receive both Seq versions, the immutable one,
   * scala.collection.immutable.Seq and also the mutable one, scala.collection.mutable.Seq.
   *
   * Therefore, if we assume we're defining an API that's trying to preserve the immutability principle,
   * we'd be incorrect because we'll need to add the import scala.collection.immutable.Seq along all the Scala
   * files to guarantee this immutability principle. I know, this looks like a boilerplate. That's why we often
   * assume that Seq is mutable by default.
   *
   * In my humble opinion, that's not a good thing. Even I would suggest skipping this section and going on to the next one.
   * I'm kidding! This is an imperative feature, and you need to be aware of the default behavior. The responsibility lies
   * on our shoulders as developers, and the import should be completed if we want to use the immutable version.
   *
   * The reason for this behavior is explained in detail in the Effective Scala Docs:
   *
   * "The default Traversable, Iterable and Seq types in scope – defined in scala.package – are the scala.collection versions,
   * as opposed to Map and Set – defined in Predef.scala – which are the scala.collection.immutable versions. This means that,
   * for example, the default Seq type can be both the immutable and mutable implementations. Thus, if your method relies on a
   * collection parameter being immutable, and you are using Traversable, Iterable or Seq, you must specifically require/import
   * the immutable variant, otherwise someone may pass you the mutable version."
   *
   * Seq - Performance:
   * In general, we can say that Seq is inefficient by nature because it is considered as an infinite collection,
   * and, added with O(n) time complexity, most operations won't terminate. In other words, the use of Seq is not
   * safe in every case because it's not lazy like Stream is for example.
   *
   * Also, it's important to mention that, Seq has a few limitations which make it an inadequate collection
   * for parallel programming.
   *
   * Seq - Usability:
   * Seq is usable in pattern matching.
   *
   * Seq - Law Abiding
   * If we're thinking in purely functional programming terms, it's important to mention that Seq doesn't obey every
   * algebraic law. We might assume that the Seq is mutable, and in that case, it's impossible to define lawful typeclass
   * instances for mutable structures because reference identity matters. Scala functional libraries such as Scalaz and Cats,
   * don't have any instances for the Seq collections since they have so many inference problems, and algebraic laws are unmet.
   *
   * In addition, I would like to add one of Rob Morris' statements from this discussion, which fits in perfectly here:
   *
   * Even if you stick with collection.immutable you find that implementations are very unconstrained; some may obey a given
   * typeclass's laws and others may not. For instance you could define Functor[immutable.Iterable], but it wouldn't be lawful
   * for Set or Map. I think this is a general problem with defining instances for non-final data types. Now, you might want
   * to argue that any sensible immutable.Iterable/Seq will end up being an okay Foldable since this typeclass has very weak
   * constraints.
   *
   * Seq - Conclusions
   * As I'm sure you've figured out, Seq is mutable by default and due to the inefficient and significant features,
   * it's enough to lose trust in Seq.
   */

  /**
   * List
   * A List is a class used for linked lists representing ordered collections of elements of a specific type.
   * List is an abstract class (recall Seq is a trait), subtype of LinearSeq, as you can see in the previous images.
   *
   * List - Mutability
   * Scala List is immutable by default; that's the main difference in respect to Scala Seq. If we, once again, look at
   * the code within the scala package object, we can see that the default definition is the immutable version:
   *
   * type List[+A] = scala.collection.immutable.List[A]
   * val List = scala.collection.immutable.List
   *
   * For those of you coming from Java, ArrayList is not the equivalent implementation of Scala List,
   * though it might be easy to think that. As we've pointed out previously, Java doesn't have indistinguishable
   * immutable collections. Therefore, the better match for ArrayList would be the scala.collection.mutable.ArrayBuffer.
   * With that in mind, the Java LinkedList can be considered as the equivalent (and mutable version) of the Scala List collection.
   *
   * List - Law Abiding
   * In both, Cats and Scalaz, we can find instances for the List collection. Both instances are lawful and meet the laws
   * for Traverse, Monoidal, Monad and CoflatMap type classes.
   *
   * List - Conclusions
   * Use List if all you need are fast prepends and the List will be used properly (see the pitfalls section).
   */

  /**
   * Vector
   * Vector is a general-purpose, immutable data structure. It provides random access and updates in effectively constant time,
   * as well as very fast append and prepend. Because vectors strike a good balance between fast random selections and fast random
   * functional updates, they are currently the default implementation of immutable indexed sequences. It is backed by a
   * little endian bit-mapped vector trie with a branching factor of 32. Locality is very good, but not contiguous, which
   * is good for very large sequences.
   *
   * Vector - Law Abiding
   * As with List in the previous section, Vector collection has instances for both Cats and Scalaz libraries. Therefore,
   * both instances in their functional libraries are lawful and meet the laws for Traverse, Monoidal, Monad and CoflatMap type classes.
   *
   * Vector - Conclusions
   * It's probably obvious that all of these arguments are pointing to a definite recommendation of breaking the habit
   * of using List, and starting to use the Vector collection, as it's a better choice in most cases.
   */

  /**
   * Alternatives
   * Scanning the Scala Standard Library, we can find a few alternatives that can be helpful depending on our needs.
   * Here is a reference from the Scalaz library:
   * - IList: safe, invariant alternative to stdlib List. Most methods on List have a sensible equivalent here,
   *          either on the IList interface itself or via typeclass instances (which are the same as those defined for stdlib List).
   *          All methods are total and stack-safe.
   * - DList: difference lists, a data structure for O(1) append on lists. Based on Data.DList, a Haskell library by Don Stewart.
   *          A difference list is a function that given a list, returns the original contents of the difference list prepended
   *          at the given list. This structure supports O(1) append and snoc operations on lists, making it very useful for
   *          append-heavy uses, such as logging and pretty printing.
   * - NonEmptyList: A singly-linked list that is guaranteed to be non-empty.
   * - ListT: ListT monad transformer, useful because Monads do not compose.
   */

  "NonEmptyList (immutable)" should "have map, flatMap and Filter" in {
    val nel: NonEmptyList[Int] = NonEmptyList(1, 2, 3, 4, 5)
    nel.head shouldBe 1
    nel.last shouldBe 5
    val xs: Vector[Int] = nel.toVector
    val ys: List[Int] = nel.toList
  }

  /**
   * Conclusion
   * To safeguard your code, you should make your variables and collection immutable, preventing uncontrolled side effects.
   *
   * All things considered, utilizing Vector is the best choice unless you have specific needs where another solution is apparent.
   * Business logic dictates that you should generally, return the most specific immutable types you can (List or Vector),
   * this would be the same rule to consider for typeclasses. In addition to this, avoid both Seq and Iterable because it's assumed
   * that they're both mutable (avoid all the interfaces if you will).
   */
}


text:
+++
title = "Thank you for subscribing to Docker weekly"
description = "We've sent you a welcome email with links to previous newsletters."
keywords = ["Docker, documentation, manual, guide, reference, api"]
+++

# Thank you for subscribing to Docker weekly

We've sent you a welcome email with links to previous newsletters.
Please check your inbox to confirm you received it.

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Fannan\MembersModule\Test\Unit\Withdraw;

class WithdrawRouterTest extends \TestCase
{

}


text:
using System;
using System.Xml;
using System.Data;

namespace fyiReporting.OracleSp
{
	/// <summary>
	/// BaseDataParameter is the base class for handling parameters
	/// </summary>
	public class DataParameter : IDbDataParameter
	{
		string _Name;			// parameter name
		object _Value;			// parameter value

		public DataParameter()
		{
		}

		#region IDbDataParameter Members

		public byte Precision
		{
			get
			{
				return 0;
			}
			set
			{
				throw new NotImplementedException("Precision setting is not implemented");
			}
		}

		public byte Scale
		{
			get
			{
				return 0;
			}
			set
			{
				throw new NotImplementedException("Scale setting is not implemented");
			}
		}

		public int Size
		{
			get
			{
				return 0;
			}
			set
			{
				throw new NotImplementedException("Size setting is not implemented");
			}
		}

		#endregion

		#region IDataParameter Members

		public System.Data.ParameterDirection Direction
		{
			get
			{
				return System.Data.ParameterDirection.Input;	// only support input parameter
			}
			set
			{
				if (value != ParameterDirection.Input)
					throw new Exception("Parameter Direction must be Input");
			}
		}

		public System.Data.DbType DbType
		{
			get
			{
				return DbType.String;
			}
			set
			{
				if (value != DbType.String)
					throw new Exception("DbType must always be String");
			}
		}

		public object Value
		{
			get {return _Value;}
            set { _Value = value; }
		}

		public bool IsNullable
		{
			get
			{
				return false;
			}
		}

		public System.Data.DataRowVersion SourceVersion
		{
			get
			{
				return DataRowVersion.Current;
			}
			set
			{
				throw new NotImplementedException("Setting DataRowVersion is not implemented.");
			}
		}

		public string ParameterName
		{
			get {return _Name;}
			set {_Name = value;}
		}

		public string SourceColumn
		{
			get
			{
				return null;
			}
			set
			{
				throw new NotImplementedException("Setting SourceColumn is not implemented.");
			}
		}

		#endregion
	}
}


text:
package io.confluent.examples.connectandstreams.jdbcjson;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.Serde;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.Grouped;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.Printed;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Properties;

import io.confluent.examples.connectandstreams.jdbcjson.model.LocationJSON;
import io.confluent.examples.connectandstreams.jdbcjson.serde.JsonDeserializer;
import io.confluent.examples.connectandstreams.jdbcjson.serde.JsonSerializer;

public class StreamsIngest {

  private static final Logger LOGGER = LoggerFactory.getLogger(StreamsIngest.class);
  private static final String INPUT_TOPIC = "jdbcjson-locations";
  private static final String DEFAULT_BOOTSTRAP_SERVERS = "localhost:9092";

  public static void main(final String[] args) {

    if (args.length > 2) {
      throw new IllegalArgumentException("usage: ... " +
                                         "[<bootstrap.servers> (optional, default: " + DEFAULT_BOOTSTRAP_SERVERS
                                         + ")] ");
    }

    final String bootstrapServers = args.length > 0 ? args[0] : DEFAULT_BOOTSTRAP_SERVERS;

    LOGGER.info("Connecting to Kafka cluster via bootstrap servers " + bootstrapServers);

    final StreamsBuilder builder = new StreamsBuilder();

    final Properties streamsConfiguration = new Properties();
    streamsConfiguration.put(StreamsConfig.APPLICATION_ID_CONFIG, "jdbcjson");
    streamsConfiguration.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
    streamsConfiguration.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 0);
    streamsConfiguration.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

    final Serde<LocationJSON> locationSerde = Serdes.serdeFrom(new JsonSerializer<>(),
                                                               new JsonDeserializer<>(LocationJSON.class));
    final KStream<Long, LocationJSON>
        locationsJSON =
        builder.stream(INPUT_TOPIC, Consumed.with(Serdes.Long(), locationSerde));
    locationsJSON.print(Printed.toSysOut());

    final KStream<Long, Long> sales = locationsJSON.mapValues(v -> v.getSale());

    // Count occurrences of each key
    final KStream<Long, Long> countKeys = sales.groupByKey(Grouped.with(Serdes.Long(), Serdes.Long()))
        .count()
        .toStream();
    countKeys.print(Printed.toSysOut());

    // Aggregate values by key
    final KStream<Long, Long> salesAgg = sales.groupByKey(Grouped.with(Serdes.Long(), Serdes.Long()))
        .reduce(Long::sum)
        .toStream();
    salesAgg.print(Printed.toSysOut());

    final KafkaStreams streams = new KafkaStreams(builder.build(), streamsConfiguration);
    streams.start();

    // Add shutdown hook to respond to SIGTERM and gracefully close Kafka Streams
    Runtime.getRuntime().addShutdownHook(new Thread(streams::close));

  }

}


text:
了解我们期望在下一个 TypeORM 版本中获得的惊人新功能。

## 关于 1.0.0 版本的说明

我们计划在 2018 年秋季的某个时间点发布一个最终稳定的`1.0.0`版本。
但是,TypeORM 已经在许多大型生产系统中得到了积极的应用。
主 API 已经非常稳定。
TypeORM 遵循语义版本控制,直到`1.0.0`,重大更改可能出现在`0.x.x`版本中。
但是,由于 API 已经相当稳定,我们预计不会有太多的重大变化。

## 如何安装最新的开发版本?

要安装最新的开发版本,请使用以下命令:

```
npm i typeorm@next
```

## 0.3.0

- [ ] research `@Select` and `@Where` decorators
- [ ] add `addSelectAndMap` functionality to `QueryBuilder`
- [ ] research internationalization features
- [ ] research ability to create one-to-many relations without inverse sides
- [ ] research ability to create a single relation with multiple entities at once
- [ ] more tree repository functionality
- [ ] cli: create database backup command
- [ ] extend `query` method functionality
- [ ] better internal ORM logging
- [ ] better error handling and user-friendly messages
- [ ] better JavaScript support - more docs and test coverage
- [ ] research NativeScript support
- [ ] finish naming strategy implementation
- [ ] implement soft deletion

## 0.2.0

- [x] add more tree-table features: nested set and materialized path; more repository methods
- [x] fix Oracle driver issues and make oracle stable and ready for production use
- [x] implement migrations generator for all drivers
- [x] create example how to use TypeORM in Electron apps
- [x] finish subscribers and listeners implementation
- [x] refactor persistence mechanism
- [x] fix all issues with cascades and make stable functionality
- [x] implement API for manual migration creation
- [x] add sql.js driver
- [x] fix inheritance support issues


text:
<?php

class Project_Controller extends Base_Controller {

	public $layout = 'layouts.project';

	public function __construct()
	{
		parent::__construct();

		$this->filter('before', 'project');
		$this->filter('before', 'permission:project-modify')->only('edit');
	}

	/**
	 * Display activity for a project
	 * /project/(:num)
	 *
	 * @return View
	 */
	public function get_index()
	{
		return $this->layout->nest('content', 'project.index', array(
			'page' => View::make('project/index/activity', array(
				'project' => Project::current(),
				'activity' => Project::current()->activity(10)
			)),
			'active' => 'activity',
			'open_count' => Project::current()->issues()
				 ->where('status', '=', 1)
				 ->count(),
			'closed_count' => Project::current()->issues()
				 ->where('status', '=', 0)
				 ->count(),
			'assigned_count' => Project::current()->count_assigned_issues()
		));
	}

	/**
	 * Display issues for a project
	 * /project/(:num)
	 *
	 * @return View
	 */
	public function get_issues()
	{
		$status = Input::get('status', 1);
		return $this->layout->nest('content', 'project.index', array(
			'page' => View::make('project/index/issues', array(
                'active' => $status == 1 ? 'open' : 'closed',
				'issues' => Project::current()->issues()
				->where('status', '=', $status)
				->order_by('updated_at', 'DESC')
				->get(),
			)),
			'active' => $status == 1 ? 'open' : 'closed',
			'open_count' => Project::current()->issues()
				->where('status', '=', 1)
				->count(),
			'closed_count' => Project::current()->issues()
				->where('status', '=', 0)
				->count(),
			'assigned_count' => Project::current()->count_assigned_issues()
		));
	}

	/**
	 * Display issues assigned to current user for a project
	 * /project/(:num)
	 *
	 * @return View
	 */
	public function get_assigned()
	{
		$status = Input::get('status', 1);

		return $this->layout->nest('content', 'project.index', array(
			'page' => View::make('project/index/issues', array(
				'issues' => Project::current()->issues()
					->where('status', '=', $status)
					->where('assigned_to', '=', Auth::user()->id)
					->order_by('updated_at', 'DESC')
					->get(),
			)),
			'active' => 'assigned',
			'open_count' => Project::current()->issues()
				->where('status', '=', 1)
				->count(),
			'closed_count' => Project::current()->issues()
				->where('status', '=', 0)
				->count(),
			'assigned_count' => Project::current()->count_assigned_issues()
		));
	}

	/**
	 * Edit the project
	 * /project/(:num)/edit
	 *
	 * @return View
	 */
	public function get_edit()
	{
		return $this->layout->nest('content', 'project.edit', array(
			'project' => Project::current()
		));
	}
    public function  extensions($type){
        $temp = '';
        switch($type){
            case 'image/png': $temp = 'png';   break;
            case 'image/jpg': $temp = 'jpg';   break;
            case 'image/jpeg': $temp = 'jpeg';   break;
        }
        return $temp;
    }

	public function post_edit()
	{
		/* Delete the project */
		if(Input::get('delete'))
		{
			Project::delete_project(Project::current());

			return Redirect::to('projects')
				->with('notice', __('tinyissue.project_has_been_deleted'));
		}

        $image = '';
        if(\Laravel\Input::has_file('image')){
            $img = \Laravel\Input::file('image');
            if($img['size'] >100000 )
            {
                return Redirect::to(Project::current()->to('edit'))
                    ->with_input()
                    ->with('notice-error', __('tinyissue.file_sizes_errors'));
            }

            $arr_size = (getimagesize($img['tmp_name']));
            if($arr_size[0] > 200 && $arr_size[1] > 200 )
            {
                return Redirect::to(Project::current()->to('edit'))
                    ->with_input()
                    ->with('notice-error', __('tinyissue.file_size_errors'));
            }

            $destination = "../uploads/project/";
            $extensions = array('image/png','image/jpg','image/jpeg');
            if(in_array($img['type'],$extensions)){
                $name = md5($img['name'].(rand(11111,99999))).".".$this->extensions($img['type']);
                \Laravel\Input::upload('image',$destination, $name);
                $image = 'uploads/project/'.$name;
            }else{
                return Redirect::to(Project::current()->to('edit'))
                    ->with_input()
                    ->with('notice-error', __('tinyissue.file_type_errors'));
            }

        }

		/* Update the project */
		$update = Project::update_project(Input::all(), Project::current(),$image);

		if($update['success'])
		{
			return Redirect::to(Project::current()->to('edit'))
				->with('notice', __('tinyissue.project_has_been_updated'));
		}

		return Redirect::to(Project::current()->to('edit'))
			->with_errors($update['errors'])
			->with('notice-error', __('tinyissue.we_have_some_errors'));
	}
}


text:
/**
 * (c) raptor_MVK, 2015. All rights reserved.
 */
package ru.mvk.iluvatar.descriptor.column;

import org.jetbrains.annotations.NotNull;

import java.text.NumberFormat;
import java.util.Locale;

/* TODO: suffixes localization */
/* TODO: minutes accuracy? */
/* Descriptor for column, that contains duration measured in seconds. Duration is
represented in minutes or hours and minutes depends on its value. If duration is less,
than 1 hour, then duration is represented in minutes with a one-digit accuracy, otherwise
it is represented in hours and integer minutes.
 */
public class DurationColumnInfo extends PlainColumnInfo {
	private static final char MINUTE_SUFFIX = 'м';
	private static final char HOUR_SUFFIX = 'ч';
	private static final int SECONDS_IN_HOUR = 3600;
	private static final int SECONDS_IN_MINUTE = 60;
	@NotNull
	private static final NumberFormat numberFormat =
			NumberFormat.getNumberInstance(Locale.US);

	static {
		// one-digit accuracy
		numberFormat.setMaximumFractionDigits(1);
		// no grouping for integral part digits
		numberFormat.setGroupingUsed(false);
	}

	public DurationColumnInfo(@NotNull String name, int width) {
		super(name, width);
	}

	@NotNull
	@Override
	public ViewFormatter getViewFormatter() {
		return (value) -> {
			@NotNull String result = "";
			if (value instanceof Integer) {
				result = getTransformedValue((Integer) value);
			}
			return result;
		};
	}

	private String getTransformedValue(int value) {
		@NotNull StringBuilder result = new StringBuilder();
		if (value < SECONDS_IN_HOUR) {
			String normalizedValue = numberFormat.format((double) value / SECONDS_IN_MINUTE);
			result.append(normalizedValue).append(' ').append(MINUTE_SUFFIX);
		} else {
			result.append(value / SECONDS_IN_HOUR).append(' ').append(HOUR_SUFFIX);
			int minutes = value % SECONDS_IN_HOUR;
			if (minutes > 0) {
				result.append(' ').append(Math.round((double) minutes / SECONDS_IN_MINUTE))
						.append(' ').append(MINUTE_SUFFIX);
			}
		}
		return result.toString();
	}
}


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

    var validation = module.exports = (function () {
      var validate = {},

      function privateMethod() {
        /* code ... */
      }

      validate.moduleMethod = function () {
        /* code ... */
      };

      return validate;
    }());

}).call(this);


text:
"""Execute a volatility command on the client memory.

This module implements the volatility enabled client actions which enable
volatility to operate directly on the client.
"""

# Initialize the volatility plugins, so pylint: disable=unused-import
from volatility import addrspace
from volatility import obj
from volatility import plugins
from volatility import session
from volatility.plugins.addrspaces import standard
from volatility.ui import renderer
# pylint: enable=unused-import

from grr.client import actions
from grr.client import vfs
from grr.lib import rdfvalue
from grr.lib import utils

# pylint: disable=g-bad-name
class ProtobufRenderer(renderer.RendererBaseClass):
  """This stores all the data in a protobuf."""

  class Modes(object):
    TABLE = 1
    STRING = 2

  def __init__(self, **kwargs):
    super(ProtobufRenderer, self).__init__(**kwargs)

    self.response = rdfvalue.VolatilityResult()
    self.active_section = None
    self.mode = None

  def InitSection(self, mode=None):
    if self.mode != mode and self.active_section:
      self.response.sections.Append(self.active_section)
      self.active_section = None
    if not self.active_section:
      self.active_section = rdfvalue.VolatilitySection()
    self.mode = mode

  def end(self):
    self.response.sections.Append(self.active_section)

  def start(self, plugin_name=None, kwargs=None):
    _ = kwargs
    if plugin_name:
      self.response.plugin = plugin_name

  def write(self, data):
    self.format(data)

  def format(self, formatstring, *data):
    _ = formatstring, data

    self.InitSection(self.Modes.STRING)
    active_list = self.active_section.formatted_value_list
    formatted_value = active_list.formatted_values.Append()
    formatted_value.formatstring = formatstring
    values = formatted_value.data

    for d in data:
      self.AddValue(values, d)

  def section(self):
    self.response.sections.Append(self.active_section)
    self.active_section = None

  def flush(self):
    pass

  def table_header(self, title_format_list=None, suppress_headers=False,
                   name=None):
    _ = suppress_headers, name

    self.InitSection(self.Modes.TABLE)

    for (print_name, name, format_hint) in title_format_list:
      self.active_section.table.headers.Append(print_name=print_name,
                                               name=name,
                                               format_hint=format_hint)

  def AddValue(self, row, value):
    response = row.values.Append()
    if isinstance(value, obj.BaseObject):
      response.type = value.obj_type
      response.name = value.obj_name
      response.offset = value.obj_offset
      response.vm = utils.SmartStr(value.obj_vm)

      try:
        response.value = value.__int__()
      except (AttributeError, ValueError):
        pass

      try:
        string_value = value.__unicode__()
      except (AttributeError, ValueError):
        try:
          string_value = value.__str__()
        except (AttributeError, ValueError):
          pass

      if string_value:
        try:
          int_value = int(string_value)
          # If the string converts to an int but to a different one as the int
          # representation, we send it.
          if int_value != response.value:
            response.svalue = utils.SmartUnicode(string_value)
        except ValueError:
          # We also send if it doesn't convert back to an int.
          response.svalue = utils.SmartUnicode(string_value)

    elif isinstance(value, (bool)):
      response.svalue = utils.SmartUnicode(str(value))
    elif isinstance(value, (int, long)):
      response.value = value
    elif isinstance(value, (basestring)):
      response.svalue = utils.SmartUnicode(value)
    elif isinstance(value, obj.NoneObject):
      response.type = value.__class__.__name__
      response.reason = value.reason
    else:
      response.svalue = utils.SmartUnicode(repr(value))

  def table_row(self, *args):
    """Outputs a single row of a table."""

    self.InitSection(self.Modes.TABLE)

    row = self.active_section.table.rows.Append()
    for value in args:
      self.AddValue(row, value)

  def GetResponse(self):
    return self.response

  def RenderProgress(self, *args):
    self.session.progress(*args)

class UnicodeStringIO(object):
  """Just like StringIO but uses unicode strings."""

  def __init__(self):
    self.data = u""

  # Have to stick to an interface here so pylint: disable=g-bad-name
  def write(self, data):
    self.data += utils.SmartUnicode(data)

  def getvalue(self):
    return self.data

class CachingFDAddressSpace(addrspace.CachingAddressSpaceMixIn,
                            standard.FDAddressSpace):
  """A Caching version of the address space."""

class VolatilityAction(actions.ActionPlugin):
  """Runs a volatility command on live memory."""
  in_rdfvalue = rdfvalue.VolatilityRequest
  out_rdfvalue = rdfvalue.VolatilityResult

  def Run(self, request):
    """Run a volatility plugin and return the result."""

    def Progress(message=None, **_):
      """Allow volatility to heartbeat us so we do not die."""
      _ = message
      self.Progress()

    # Create a session and run all the plugins with it.
    with vfs.VFSOpen(request.device) as fhandle:
      session_args = request.session.ToDict()
      vol_session = session.Session(**session_args)

      # Make the physical address space by wrapping our VFS handler.
      vol_session.physical_address_space = CachingFDAddressSpace(
          fhandle=fhandle)

      # Set the progress method so the nanny is heartbeat.
      vol_session.progress = Progress
      vol_session.renderer = "ProtobufRenderer"

      # Get the dtb from the driver if possible,
      # it significantly speeds up detection.
      try:
        vol_session.dtb = fhandle.cr3
      except AttributeError:
        pass

      # Get the kdbg from the driver if possible,
      # it significantly speeds up detection.
      try:
        vol_session.kdbg = fhandle.kdbg
      except AttributeError:
        pass

      # Which profile should be used?
      if request.profile:
        vol_session.profile = request.profile
      else:
        vol_session.plugins.guess_profile().update_session()

      if not vol_session.profile:
        raise RuntimeError("Unable to autodetect profile")

      # Try to load the kernel address space now.
      if not vol_session.kernel_address_space:
        vol_session.plugins.load_as().GetVirtualAddressSpace()

      # Get the keyword args to this plugin.
      vol_args = request.args.ToDict()
      for plugin, plugin_args in vol_args.items():
        error = ""

        # Heartbeat the client to ensure we keep our nanny happy.
        vol_session.progress(message="Running plugin %s" % plugin)

        ui_renderer = ProtobufRenderer(session=vol_session)
        if plugin_args is None:
          plugin_args = {}
        else:
          plugin_args = plugin_args.ToDict()

        try:
          vol_session.vol(plugin, renderer=ui_renderer, **plugin_args)
        except Exception as e:  # pylint: disable=broad-except
          error = str(e)

        response = ui_renderer.GetResponse()
        if error:
          response.error = error

        # Send it back to the server.
        self.SendReply(response)


text:
package com.xfl.pingguopai.dao;

import com.xfl.pingguopai.common.Mapper;
import com.xfl.pingguopai.model.Authority;

public interface AuthorityMapper extends Mapper<Authority> {
}


text:
<meta charset="utf-8">
<title>{% if page.title %}{{ page.title }} – {% endif %}{{ site.title }}</title>
{% if page.excerpt %}<meta name="description" content="{{ page.excerpt | strip_html }}">{% endif %}
{% if page.tags %}<meta name="keywords" content="{{ page.tags | join: ', ' }}">{% endif %}
{% if page.author %}
  {% assign author = site.data.authors[page.author] %}{% else %}{% assign author = site.owner %}
{% endif %}

{% include open-graph.html %}

{% if site.owner.google.verify %}<!-- Webmaster Tools verfication -->
<meta name="google-site-verification" content="{{ site.owner.google.verify }}">{% endif %}
{% if site.owner.bing-verify %}<meta name="msvalidate.01" content="{{ site.owner.bing-verify }}">{% endif %}

{% capture canonical %}{{ site.url }}{% if site.permalink contains '.html' %}{{ page.url }}{% else %}{{ page.url | remove:'index.html' | strip_slash }}{% endif %}{% endcapture %}
<link rel="canonical" href="{{ canonical }}">
<link href="{{ site.url }}/feed.xml" type="application/atom+xml" rel="alternate" title="{{ site.title }} Feed">

<!-- https://t.co/dKP3o1e -->
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<!-- For all browsers -->
<link rel="stylesheet" href="{{ site.url }}/assets/css/main.css">
<!-- Webfonts -->
<link href="https://fonts.googleapis.com/css?family=EB+Garamond|Maven+Pro|PT+Mono" rel="stylesheet">

<meta http-equiv="cleartype" content="on">

<!-- HTML5 Shiv and Media Query Support -->
<!--[if lt IE 9]>
  <script src="{{ site.url }}/assets/js/vendor/html5shiv.min.js"></script>
  <script src="{{ site.url }}/assets/js/vendor/respond.min.js"></script>
<![endif]-->

<!-- Modernizr -->
<script src="{{ site.url }}/assets/js/vendor/modernizr-2.7.1.custom.min.js"></script>

{% if site.mathjax == true %}
<!-- MathJax -->
<script src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
{% endif %}

<!-- Icons -->
<link rel="apple-touch-icon" sizes="57x57" href="/images/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="/images/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="/images/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="/images/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="/images/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="/images/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="/images/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="/images/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/images/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192"  href="/images/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="/images/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="/images/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">


text:
package org.thingsboard.server.actors.tenant;

import lombok.extern.slf4j.Slf4j;
import org.thingsboard.server.actors.ActorSystemContext;
import org.thingsboard.server.actors.TbActor;
import org.thingsboard.server.actors.TbActorCtx;
import org.thingsboard.server.actors.TbActorException;
import org.thingsboard.server.actors.TbActorId;
import org.thingsboard.server.actors.TbActorNotRegisteredException;
import org.thingsboard.server.actors.TbActorRef;
import org.thingsboard.server.actors.TbEntityActorId;
import org.thingsboard.server.actors.TbEntityTypeActorIdPredicate;
import org.thingsboard.server.actors.device.DeviceActorCreator;
import org.thingsboard.server.actors.ruleChain.RuleChainManagerActor;
import org.thingsboard.server.actors.service.ContextBasedCreator;
import org.thingsboard.server.actors.service.DefaultActorService;
import org.thingsboard.server.common.data.ApiUsageState;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.Tenant;
import org.thingsboard.server.common.data.TenantProfile;
import org.thingsboard.server.common.data.edge.Edge;
import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.id.EdgeId;
import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.RuleChainId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.plugin.ComponentLifecycleEvent;
import org.thingsboard.server.common.data.rule.RuleChain;
import org.thingsboard.server.common.data.rule.RuleChainType;
import org.thingsboard.server.common.msg.MsgType;
import org.thingsboard.server.common.msg.TbActorMsg;
import org.thingsboard.server.common.msg.TbMsg;
import org.thingsboard.server.common.msg.aware.DeviceAwareMsg;
import org.thingsboard.server.common.msg.aware.RuleChainAwareMsg;
import org.thingsboard.server.common.msg.edge.EdgeSessionMsg;
import org.thingsboard.server.common.msg.plugin.ComponentLifecycleMsg;
import org.thingsboard.server.common.msg.queue.PartitionChangeMsg;
import org.thingsboard.server.common.msg.queue.QueueToRuleEngineMsg;
import org.thingsboard.server.common.msg.queue.RuleEngineException;
import org.thingsboard.server.common.msg.queue.ServiceType;
import org.thingsboard.server.service.edge.rpc.EdgeRpcService;
import org.thingsboard.server.service.transport.msg.TransportToDeviceActorMsgWrapper;

import java.util.List;

@Slf4j
public class TenantActor extends RuleChainManagerActor {

    private boolean isRuleEngine;
    private boolean isCore;
    private ApiUsageState apiUsageState;

    private TenantActor(ActorSystemContext systemContext, TenantId tenantId) {
        super(systemContext, tenantId);
    }

    boolean cantFindTenant = false;

    @Override
    public void init(TbActorCtx ctx) throws TbActorException {
        super.init(ctx);
        log.debug("[{}] Starting tenant actor.", tenantId);
        try {
            Tenant tenant = systemContext.getTenantService().findTenantById(tenantId);
            if (tenant == null) {
                cantFindTenant = true;
                log.info("[{}] Started tenant actor for missing tenant.", tenantId);
            } else {
                TenantProfile tenantProfile = systemContext.getTenantProfileCache().get(tenant.getTenantProfileId());

                isCore = systemContext.getServiceInfoProvider().isService(ServiceType.TB_CORE);
                isRuleEngine = systemContext.getServiceInfoProvider().isService(ServiceType.TB_RULE_ENGINE);
                if (isRuleEngine) {
                    try {
                        if (getApiUsageState().isReExecEnabled()) {
                            log.debug("[{}] Going to init rule chains", tenantId);
                            initRuleChains();
                        } else {
                            log.info("[{}] Skip init of the rule chains due to API limits", tenantId);
                        }
                    } catch (Exception e) {
                        cantFindTenant = true;
                    }
                }
                log.debug("[{}] Tenant actor started.", tenantId);
            }
        } catch (Exception e) {
            log.warn("[{}] Unknown failure", tenantId, e);
        }
    }

    @Override
    public void destroy() {
        log.info("[{}] Stopping tenant actor.", tenantId);
    }

    @Override
    protected boolean doProcess(TbActorMsg msg) {
        if (cantFindTenant) {
            log.info("[{}] Processing missing Tenant msg: {}", tenantId, msg);
            if (msg.getMsgType().equals(MsgType.QUEUE_TO_RULE_ENGINE_MSG)) {
                QueueToRuleEngineMsg queueMsg = (QueueToRuleEngineMsg) msg;
                queueMsg.getMsg().getCallback().onSuccess();
            } else if (msg.getMsgType().equals(MsgType.TRANSPORT_TO_DEVICE_ACTOR_MSG)) {
                TransportToDeviceActorMsgWrapper transportMsg = (TransportToDeviceActorMsgWrapper) msg;
                transportMsg.getCallback().onSuccess();
            }
            return true;
        }
        switch (msg.getMsgType()) {
            case PARTITION_CHANGE_MSG:
                PartitionChangeMsg partitionChangeMsg = (PartitionChangeMsg) msg;
                ServiceType serviceType = partitionChangeMsg.getServiceType();
                if (ServiceType.TB_RULE_ENGINE.equals(serviceType)) {
                    //To Rule Chain Actors
                    broadcast(msg);
                } else if (ServiceType.TB_CORE.equals(serviceType)) {
                    List<TbActorId> deviceActorIds = ctx.filterChildren(new TbEntityTypeActorIdPredicate(EntityType.DEVICE) {
                        @Override
                        protected boolean testEntityId(EntityId entityId) {
                            return super.testEntityId(entityId) && !isMyPartition(entityId);
                        }
                    });
                    deviceActorIds.forEach(id -> ctx.stop(id));
                }
                break;
            case COMPONENT_LIFE_CYCLE_MSG:
                onComponentLifecycleMsg((ComponentLifecycleMsg) msg);
                break;
            case QUEUE_TO_RULE_ENGINE_MSG:
                onQueueToRuleEngineMsg((QueueToRuleEngineMsg) msg);
                break;
            case TRANSPORT_TO_DEVICE_ACTOR_MSG:
                onToDeviceActorMsg((DeviceAwareMsg) msg, false);
                break;
            case DEVICE_ATTRIBUTES_UPDATE_TO_DEVICE_ACTOR_MSG:
            case DEVICE_CREDENTIALS_UPDATE_TO_DEVICE_ACTOR_MSG:
            case DEVICE_NAME_OR_TYPE_UPDATE_TO_DEVICE_ACTOR_MSG:
            case DEVICE_EDGE_UPDATE_TO_DEVICE_ACTOR_MSG:
            case DEVICE_RPC_REQUEST_TO_DEVICE_ACTOR_MSG:
            case DEVICE_RPC_RESPONSE_TO_DEVICE_ACTOR_MSG:
            case SERVER_RPC_RESPONSE_TO_DEVICE_ACTOR_MSG:
            case REMOVE_RPC_TO_DEVICE_ACTOR_MSG:
                onToDeviceActorMsg((DeviceAwareMsg) msg, true);
                break;
            case SESSION_TIMEOUT_MSG:
                ctx.broadcastToChildrenByType(msg, EntityType.DEVICE);
                break;
            case RULE_CHAIN_INPUT_MSG:
            case RULE_CHAIN_OUTPUT_MSG:
            case RULE_CHAIN_TO_RULE_CHAIN_MSG:
                onRuleChainMsg((RuleChainAwareMsg) msg);
                break;
            case EDGE_EVENT_UPDATE_TO_EDGE_SESSION_MSG:
            case EDGE_SYNC_REQUEST_TO_EDGE_SESSION_MSG:
            case EDGE_SYNC_RESPONSE_FROM_EDGE_SESSION_MSG:
                onToEdgeSessionMsg((EdgeSessionMsg) msg);
                break;
            default:
                return false;
        }
        return true;
    }

    private boolean isMyPartition(EntityId entityId) {
        return systemContext.resolve(ServiceType.TB_CORE, tenantId, entityId).isMyPartition();
    }

    private void onQueueToRuleEngineMsg(QueueToRuleEngineMsg msg) {
        if (!isRuleEngine) {
            log.warn("RECEIVED INVALID MESSAGE: {}", msg);
            return;
        }
        TbMsg tbMsg = msg.getMsg();
        if (getApiUsageState().isReExecEnabled()) {
            if (tbMsg.getRuleChainId() == null) {
                if (getRootChainActor() != null) {
                    getRootChainActor().tell(msg);
                } else {
                    tbMsg.getCallback().onFailure(new RuleEngineException("No Root Rule Chain available!"));
                    log.info("[{}] No Root Chain: {}", tenantId, msg);
                }
            } else {
                try {
                    ctx.tell(new TbEntityActorId(tbMsg.getRuleChainId()), msg);
                } catch (TbActorNotRegisteredException ex) {
                    log.trace("Received message for non-existing rule chain: [{}]", tbMsg.getRuleChainId());
                    //TODO: 3.1 Log it to dead letters queue;
                    tbMsg.getCallback().onSuccess();
                }
            }
        } else {
            log.trace("[{}] Ack message because Rule Engine is disabled", tenantId);
            tbMsg.getCallback().onSuccess();
        }
    }

    private void onRuleChainMsg(RuleChainAwareMsg msg) {
        if (getApiUsageState().isReExecEnabled()) {
            getOrCreateActor(msg.getRuleChainId()).tell(msg);
        }
    }

    private void onToDeviceActorMsg(DeviceAwareMsg msg, boolean priority) {
        if (!isCore) {
            log.warn("RECEIVED INVALID MESSAGE: {}", msg);
        }
        TbActorRef deviceActor = getOrCreateDeviceActor(msg.getDeviceId());
        if (priority) {
            deviceActor.tellWithHighPriority(msg);
        } else {
            deviceActor.tell(msg);
        }
    }

    private void onComponentLifecycleMsg(ComponentLifecycleMsg msg) {
        if (msg.getEntityId().getEntityType().equals(EntityType.API_USAGE_STATE)) {
            ApiUsageState old = getApiUsageState();
            apiUsageState = new ApiUsageState(systemContext.getApiUsageStateService().getApiUsageState(tenantId));
            if (old.isReExecEnabled() && !apiUsageState.isReExecEnabled()) {
                log.info("[{}] Received API state update. Going to DISABLE Rule Engine execution.", tenantId);
                destroyRuleChains();
            } else if (!old.isReExecEnabled() && apiUsageState.isReExecEnabled()) {
                log.info("[{}] Received API state update. Going to ENABLE Rule Engine execution.", tenantId);
                initRuleChains();
            }
        } else if (msg.getEntityId().getEntityType() == EntityType.EDGE) {
            EdgeId edgeId = new EdgeId(msg.getEntityId().getId());
            EdgeRpcService edgeRpcService = systemContext.getEdgeRpcService();
            if (msg.getEvent() == ComponentLifecycleEvent.DELETED) {
                edgeRpcService.deleteEdge(tenantId, edgeId);
            } else if (msg.getEvent() == ComponentLifecycleEvent.UPDATED) {
                Edge edge = systemContext.getEdgeService().findEdgeById(tenantId, edgeId);
                edgeRpcService.updateEdge(tenantId, edge);
            }
        } else if (isRuleEngine) {
            TbActorRef target = getEntityActorRef(msg.getEntityId());
            if (target != null) {
                if (msg.getEntityId().getEntityType() == EntityType.RULE_CHAIN) {
                    RuleChain ruleChain = systemContext.getRuleChainService().
                            findRuleChainById(tenantId, new RuleChainId(msg.getEntityId().getId()));
                    if (ruleChain != null && RuleChainType.CORE.equals(ruleChain.getType())) {
                        visit(ruleChain, target);
                    }
                }
                target.tellWithHighPriority(msg);
            } else {
                log.debug("[{}] Invalid component lifecycle msg: {}", tenantId, msg);
            }
        }
    }

    private TbActorRef getOrCreateDeviceActor(DeviceId deviceId) {
        return ctx.getOrCreateChildActor(new TbEntityActorId(deviceId),
                () -> DefaultActorService.DEVICE_DISPATCHER_NAME,
                () -> new DeviceActorCreator(systemContext, tenantId, deviceId));
    }

    private void onToEdgeSessionMsg(EdgeSessionMsg msg) {
        systemContext.getEdgeRpcService().onToEdgeSessionMsg(tenantId, msg);
    }

    private ApiUsageState getApiUsageState() {
        if (apiUsageState == null) {
            apiUsageState = new ApiUsageState(systemContext.getApiUsageStateService().getApiUsageState(tenantId));
        }
        return apiUsageState;
    }

    public static class ActorCreator extends ContextBasedCreator {

        private final TenantId tenantId;

        public ActorCreator(ActorSystemContext context, TenantId tenantId) {
            super(context);
            this.tenantId = tenantId;
        }

        @Override
        public TbActorId createActorId() {
            return new TbEntityActorId(tenantId);
        }

        @Override
        public TbActor createActor() {
            return new TenantActor(context, tenantId);
        }
    }

}


text:
/*****************************************************************************
*
* Filename:      ks959-sir.c
* Version:       0.1.2
* Description:   Irda KingSun KS-959 USB Dongle
* Status:        Experimental
* Author:        Alex Villacís Lasso <a_villacis@palosanto.com>
*         with help from Domen Puncer <domen@coderock.org>
*
*    Based on stir4200, mcs7780, kingsun-sir drivers.
*
*    This program is free software; you can redistribute it and/or modify
*    it under the terms of the GNU General Public License as published by
*    the Free Software Foundation; either version 2 of the License.
*
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU General Public License for more details.
*
*    You should have received a copy of the GNU General Public License
*    along with this program; if not, write to the Free Software
*    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*****************************************************************************/

/*
 * Following is my most current (2007-07-17) understanding of how the Kingsun
 * KS-959 dongle is supposed to work. This information was deduced by
 * reverse-engineering and examining the USB traffic captured with USBSnoopy
 * from the WinXP driver. Feel free to update here as more of the dongle is
 * known.
 *
 * My most sincere thanks must go to Domen Puncer <domen@coderock.org> for
 * invaluable help in cracking the obfuscation and padding required for this
 * dongle.
 *
 * General: This dongle exposes one interface with one interrupt IN endpoint.
 * However, the interrupt endpoint is NOT used at all for this dongle. Instead,
 * this dongle uses control transfers for everything, including sending and
 * receiving the IrDA frame data. Apparently the interrupt endpoint is just a
 * dummy to ensure the dongle has a valid interface to present to the PC.And I
 * thought the DonShine dongle was weird... In addition, this dongle uses
 * obfuscation (?!?!), applied at the USB level, to hide the traffic, both sent
 * and received, from the dongle. I call it obfuscation because the XOR keying
 * and padding required to produce an USB traffic acceptable for the dongle can
 * not be explained by any other technical requirement.
 *
 * Transmission: To transmit an IrDA frame, the driver must prepare a control
 * URB with the following as a setup packet:
 *    bRequestType    USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE
 *    bRequest        0x09
 *    wValue          <length of valid data before padding, little endian>
 *    wIndex          0x0000
 *    wLength         <length of padded data>
 * The payload packet must be manually wrapped and escaped (as in stir4200.c),
 * then padded and obfuscated before being sent. Both padding and obfuscation
 * are implemented in the procedure obfuscate_tx_buffer(). Suffice to say, the
 * designer/programmer of the dongle used his name as a source for the
 * obfuscation. WTF?!
 * Apparently the dongle cannot handle payloads larger than 256 bytes. The
 * driver has to perform fragmentation in order to send anything larger than
 * this limit.
 *
 * Reception: To receive data, the driver must poll the dongle regularly (like
 * kingsun-sir.c) with control URBs and the following as a setup packet:
 *    bRequestType    USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE
 *    bRequest        0x01
 *    wValue          0x0200
 *    wIndex          0x0000
 *    wLength         0x0800 (size of available buffer)
 * If there is data to be read, it will be returned as the response payload.
 * This data is (apparently) not padded, but it is obfuscated. To de-obfuscate
 * it, the driver must XOR every byte, in sequence, with a value that starts at
 * 1 and is incremented with each byte processed, and then with 0x55. The value
 * incremented with each byte processed overflows as an unsigned char. The
 * resulting bytes form a wrapped SIR frame that is unwrapped and unescaped
 * as in stir4200.c The incremented value is NOT reset with each frame, but is
 * kept across the entire session with the dongle. Also, the dongle inserts an
 * extra garbage byte with value 0x95 (after decoding) every 0xff bytes, which
 * must be skipped.
 *
 * Speed change: To change the speed of the dongle, the driver prepares a
 * control URB with the following as a setup packet:
 *    bRequestType    USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE
 *    bRequest        0x09
 *    wValue          0x0200
 *    wIndex          0x0001
 *    wLength         0x0008 (length of the payload)
 * The payload is a 8-byte record, apparently identical to the one used in
 * drivers/usb/serial/cypress_m8.c to change speed:
 *     __u32 baudSpeed;
 *    unsigned int dataBits : 2;    // 0 - 5 bits 3 - 8 bits
 *    unsigned int : 1;
 *    unsigned int stopBits : 1;
 *    unsigned int parityEnable : 1;
 *    unsigned int parityType : 1;
 *    unsigned int : 1;
 *    unsigned int reset : 1;
 *    unsigned char reserved[3];    // set to 0
 *
 * For now only SIR speeds have been observed with this dongle. Therefore,
 * nothing is known on what changes (if any) must be done to frame wrapping /
 * unwrapping for higher than SIR speeds. This driver assumes no change is
 * necessary and announces support for all the way to 57600 bps. Although the
 * package announces support for up to 4MBps, tests with a Sony Ericcson K300
 * phone show corruption when receiving large frames at 115200 bps, the highest
 * speed announced by the phone. However, transmission at 115200 bps is OK. Go
 * figure. Since I don't know whether the phone or the dongle is at fault, max
 * announced speed is 57600 bps until someone produces a device that can run
 * at higher speeds with this dongle.
 */

#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/usb.h>
#include <linux/device.h>
#include <linux/crc32.h>

#include <asm/unaligned.h>
#include <asm/byteorder.h>
#include <asm/uaccess.h>

#include <net/irda/irda.h>
#include <net/irda/wrapper.h>
#include <net/irda/crc.h>

#define KS959_VENDOR_ID 0x07d0
#define KS959_PRODUCT_ID 0x4959

/* These are the currently known USB ids */
static struct usb_device_id dongles[] = {
	/* KingSun Co,Ltd  IrDA/USB Bridge */
	{USB_DEVICE(KS959_VENDOR_ID, KS959_PRODUCT_ID)},
	{}
};

MODULE_DEVICE_TABLE(usb, dongles);

#define KINGSUN_MTT 0x07
#define KINGSUN_REQ_RECV 0x01
#define KINGSUN_REQ_SEND 0x09

#define KINGSUN_RCV_FIFO_SIZE    2048	/* Max length we can receive */
#define KINGSUN_SND_FIFO_SIZE    2048	/* Max packet we can send */
#define KINGSUN_SND_PACKET_SIZE    256	/* Max packet dongle can handle */

struct ks959_speedparams {
	__le32 baudrate;	/* baud rate, little endian */
	__u8 flags;
	__u8 reserved[3];
} __packed;

#define KS_DATA_5_BITS 0x00
#define KS_DATA_6_BITS 0x01
#define KS_DATA_7_BITS 0x02
#define KS_DATA_8_BITS 0x03

#define KS_STOP_BITS_1 0x00
#define KS_STOP_BITS_2 0x08

#define KS_PAR_DISABLE    0x00
#define KS_PAR_EVEN    0x10
#define KS_PAR_ODD    0x30
#define KS_RESET    0x80

struct ks959_cb {
	struct usb_device *usbdev;	/* init: probe_irda */
	struct net_device *netdev;	/* network layer */
	struct irlap_cb *irlap;	/* The link layer we are binded to */

	struct qos_info qos;

	struct usb_ctrlrequest *tx_setuprequest;
	struct urb *tx_urb;
	__u8 *tx_buf_clear;
	unsigned int tx_buf_clear_used;
	unsigned int tx_buf_clear_sent;
	__u8 *tx_buf_xored;

	struct usb_ctrlrequest *rx_setuprequest;
	struct urb *rx_urb;
	__u8 *rx_buf;
	__u8 rx_variable_xormask;
	iobuff_t rx_unwrap_buff;
	struct timeval rx_time;

	struct usb_ctrlrequest *speed_setuprequest;
	struct urb *speed_urb;
	struct ks959_speedparams speedparams;
	unsigned int new_speed;

	spinlock_t lock;
	int receiving;
};

/* Procedure to perform the obfuscation/padding expected by the dongle
 *
 * buf_cleartext    (IN) Cleartext version of the IrDA frame to transmit
 * len_cleartext    (IN) Length of the cleartext version of IrDA frame
 * buf_xoredtext    (OUT) Obfuscated version of frame built by proc
 * len_maxbuf        (OUT) Maximum space available at buf_xoredtext
 *
 * (return)         length of obfuscated frame with padding
 *
 * If not enough space (as indicated by len_maxbuf vs. required padding),
 * zero is returned
 *
 * The value of lookup_string is actually a required portion of the algorithm.
 * Seems the designer of the dongle wanted to state who exactly is responsible
 * for implementing obfuscation. Send your best (or other) wishes to him ]:-)
 */
static unsigned int obfuscate_tx_buffer(const __u8 * buf_cleartext,
					unsigned int len_cleartext,
					__u8 * buf_xoredtext,
					unsigned int len_maxbuf)
{
	unsigned int len_xoredtext;

	/* Calculate required length with padding, check for necessary space */
	len_xoredtext = ((len_cleartext + 7) & ~0x7) + 0x10;
	if (len_xoredtext <= len_maxbuf) {
		static const __u8 lookup_string[] = "wangshuofei19710";
		__u8 xor_mask;

		/* Unlike the WinXP driver, we *do* clear out the padding */
		memset(buf_xoredtext, 0, len_xoredtext);

		xor_mask = lookup_string[(len_cleartext & 0x0f) ^ 0x06] ^ 0x55;

		while (len_cleartext-- > 0) {
			*buf_xoredtext++ = *buf_cleartext++ ^ xor_mask;
		}
	} else {
		len_xoredtext = 0;
	}
	return len_xoredtext;
}

/* Callback transmission routine */
static void ks959_speed_irq(struct urb *urb)
{
	/* unlink, shutdown, unplug, other nasties */
	if (urb->status != 0) {
		dev_err(&urb->dev->dev,
			"ks959_speed_irq: urb asynchronously failed - %d\n",
			urb->status);
	}
}

/* Send a control request to change speed of the dongle */
static int ks959_change_speed(struct ks959_cb *kingsun, unsigned speed)
{
	static unsigned int supported_speeds[] = { 2400, 9600, 19200, 38400,
		57600, 115200, 576000, 1152000, 4000000, 0
	};
	int err;
	unsigned int i;

	if (kingsun->speed_setuprequest == NULL || kingsun->speed_urb == NULL)
		return -ENOMEM;

	/* Check that requested speed is among the supported ones */
	for (i = 0; supported_speeds[i] && supported_speeds[i] != speed; i++) ;
	if (supported_speeds[i] == 0)
		return -EOPNOTSUPP;

	memset(&(kingsun->speedparams), 0, sizeof(struct ks959_speedparams));
	kingsun->speedparams.baudrate = cpu_to_le32(speed);
	kingsun->speedparams.flags = KS_DATA_8_BITS;

	/* speed_setuprequest pre-filled in ks959_probe */
	usb_fill_control_urb(kingsun->speed_urb, kingsun->usbdev,
			     usb_sndctrlpipe(kingsun->usbdev, 0),
			     (unsigned char *)kingsun->speed_setuprequest,
			     &(kingsun->speedparams),
			     sizeof(struct ks959_speedparams), ks959_speed_irq,
			     kingsun);
	kingsun->speed_urb->status = 0;
	err = usb_submit_urb(kingsun->speed_urb, GFP_ATOMIC);

	return err;
}

/* Submit one fragment of an IrDA frame to the dongle */
static void ks959_send_irq(struct urb *urb);
static int ks959_submit_tx_fragment(struct ks959_cb *kingsun)
{
	unsigned int padlen;
	unsigned int wraplen;
	int ret;

	/* Check whether current plaintext can produce a padded buffer that fits
	   within the range handled by the dongle */
	wraplen = (KINGSUN_SND_PACKET_SIZE & ~0x7) - 0x10;
	if (wraplen > kingsun->tx_buf_clear_used)
		wraplen = kingsun->tx_buf_clear_used;

	/* Perform dongle obfuscation. Also remove the portion of the frame that
	   was just obfuscated and will now be sent to the dongle. */
	padlen = obfuscate_tx_buffer(kingsun->tx_buf_clear, wraplen,
				     kingsun->tx_buf_xored,
				     KINGSUN_SND_PACKET_SIZE);

	/* Calculate how much data can be transmitted in this urb */
	kingsun->tx_setuprequest->wValue = cpu_to_le16(wraplen);
	kingsun->tx_setuprequest->wLength = cpu_to_le16(padlen);
	/* Rest of the fields were filled in ks959_probe */
	usb_fill_control_urb(kingsun->tx_urb, kingsun->usbdev,
			     usb_sndctrlpipe(kingsun->usbdev, 0),
			     (unsigned char *)kingsun->tx_setuprequest,
			     kingsun->tx_buf_xored, padlen,
			     ks959_send_irq, kingsun);
	kingsun->tx_urb->status = 0;
	ret = usb_submit_urb(kingsun->tx_urb, GFP_ATOMIC);

	/* Remember how much data was sent, in order to update at callback */
	kingsun->tx_buf_clear_sent = (ret == 0) ? wraplen : 0;
	return ret;
}

/* Callback transmission routine */
static void ks959_send_irq(struct urb *urb)
{
	struct ks959_cb *kingsun = urb->context;
	struct net_device *netdev = kingsun->netdev;
	int ret = 0;

	/* in process of stopping, just drop data */
	if (!netif_running(kingsun->netdev)) {
		dev_err(&kingsun->usbdev->dev,
			"ks959_send_irq: Network not running!\n");
		return;
	}

	/* unlink, shutdown, unplug, other nasties */
	if (urb->status != 0) {
		dev_err(&kingsun->usbdev->dev,
			"ks959_send_irq: urb asynchronously failed - %d\n",
			urb->status);
		return;
	}

	if (kingsun->tx_buf_clear_used > 0) {
		/* Update data remaining to be sent */
		if (kingsun->tx_buf_clear_sent < kingsun->tx_buf_clear_used) {
			memmove(kingsun->tx_buf_clear,
				kingsun->tx_buf_clear +
				kingsun->tx_buf_clear_sent,
				kingsun->tx_buf_clear_used -
				kingsun->tx_buf_clear_sent);
		}
		kingsun->tx_buf_clear_used -= kingsun->tx_buf_clear_sent;
		kingsun->tx_buf_clear_sent = 0;

		if (kingsun->tx_buf_clear_used > 0) {
			/* There is more data to be sent */
			if ((ret = ks959_submit_tx_fragment(kingsun)) != 0) {
				dev_err(&kingsun->usbdev->dev,
					"ks959_send_irq: failed tx_urb submit: %d\n",
					ret);
				switch (ret) {
				case -ENODEV:
				case -EPIPE:
					break;
				default:
					netdev->stats.tx_errors++;
					netif_start_queue(netdev);
				}
			}
		} else {
			/* All data sent, send next speed && wake network queue */
			if (kingsun->new_speed != -1 &&
			    cpu_to_le32(kingsun->new_speed) !=
			    kingsun->speedparams.baudrate)
				ks959_change_speed(kingsun, kingsun->new_speed);

			netif_wake_queue(netdev);
		}
	}
}

/*
 * Called from net/core when new frame is available.
 */
static netdev_tx_t ks959_hard_xmit(struct sk_buff *skb,
					 struct net_device *netdev)
{
	struct ks959_cb *kingsun;
	unsigned int wraplen;
	int ret = 0;

	netif_stop_queue(netdev);

	/* the IRDA wrapping routines don't deal with non linear skb */
	SKB_LINEAR_ASSERT(skb);

	kingsun = netdev_priv(netdev);

	spin_lock(&kingsun->lock);
	kingsun->new_speed = irda_get_next_speed(skb);

	/* Append data to the end of whatever data remains to be transmitted */
	wraplen =
	    async_wrap_skb(skb, kingsun->tx_buf_clear, KINGSUN_SND_FIFO_SIZE);
	kingsun->tx_buf_clear_used = wraplen;

	if ((ret = ks959_submit_tx_fragment(kingsun)) != 0) {
		dev_err(&kingsun->usbdev->dev,
			"ks959_hard_xmit: failed tx_urb submit: %d\n", ret);
		switch (ret) {
		case -ENODEV:
		case -EPIPE:
			break;
		default:
			netdev->stats.tx_errors++;
			netif_start_queue(netdev);
		}
	} else {
		netdev->stats.tx_packets++;
		netdev->stats.tx_bytes += skb->len;

	}

	dev_kfree_skb(skb);
	spin_unlock(&kingsun->lock);

	return NETDEV_TX_OK;
}

/* Receive callback function */
static void ks959_rcv_irq(struct urb *urb)
{
	struct ks959_cb *kingsun = urb->context;
	int ret;

	/* in process of stopping, just drop data */
	if (!netif_running(kingsun->netdev)) {
		kingsun->receiving = 0;
		return;
	}

	/* unlink, shutdown, unplug, other nasties */
	if (urb->status != 0) {
		dev_err(&kingsun->usbdev->dev,
			"kingsun_rcv_irq: urb asynchronously failed - %d\n",
			urb->status);
		kingsun->receiving = 0;
		return;
	}

	if (urb->actual_length > 0) {
		__u8 *bytes = urb->transfer_buffer;
		unsigned int i;

		for (i = 0; i < urb->actual_length; i++) {
			/* De-obfuscation implemented here: variable portion of
			   xormask is incremented, and then used with the encoded
			   byte for the XOR. The result of the operation is used
			   to unwrap the SIR frame. */
			kingsun->rx_variable_xormask++;
			bytes[i] =
			    bytes[i] ^ kingsun->rx_variable_xormask ^ 0x55u;

			/* rx_variable_xormask doubles as an index counter so we
			   can skip the byte at 0xff (wrapped around to 0).
			 */
			if (kingsun->rx_variable_xormask != 0) {
				async_unwrap_char(kingsun->netdev,
						  &kingsun->netdev->stats,
						  &kingsun->rx_unwrap_buff,
						  bytes[i]);
			}
		}
		do_gettimeofday(&kingsun->rx_time);
		kingsun->receiving =
		    (kingsun->rx_unwrap_buff.state != OUTSIDE_FRAME) ? 1 : 0;
	}

	/* This urb has already been filled in kingsun_net_open. Setup
	   packet must be re-filled, but it is assumed that urb keeps the
	   pointer to the initial setup packet, as well as the payload buffer.
	   Setup packet is already pre-filled at ks959_probe.
	 */
	urb->status = 0;
	ret = usb_submit_urb(urb, GFP_ATOMIC);
}

/*
 * Function kingsun_net_open (dev)
 *
 *    Network device is taken up. Usually this is done by "ifconfig irda0 up"
 */
static int ks959_net_open(struct net_device *netdev)
{
	struct ks959_cb *kingsun = netdev_priv(netdev);
	int err = -ENOMEM;
	char hwname[16];

	/* At this point, urbs are NULL, and skb is NULL (see kingsun_probe) */
	kingsun->receiving = 0;

	/* Initialize for SIR to copy data directly into skb.  */
	kingsun->rx_unwrap_buff.in_frame = FALSE;
	kingsun->rx_unwrap_buff.state = OUTSIDE_FRAME;
	kingsun->rx_unwrap_buff.truesize = IRDA_SKB_MAX_MTU;
	kingsun->rx_unwrap_buff.skb = dev_alloc_skb(IRDA_SKB_MAX_MTU);
	if (!kingsun->rx_unwrap_buff.skb)
		goto free_mem;

	skb_reserve(kingsun->rx_unwrap_buff.skb, 1);
	kingsun->rx_unwrap_buff.head = kingsun->rx_unwrap_buff.skb->data;
	do_gettimeofday(&kingsun->rx_time);

	kingsun->rx_urb = usb_alloc_urb(0, GFP_KERNEL);
	if (!kingsun->rx_urb)
		goto free_mem;

	kingsun->tx_urb = usb_alloc_urb(0, GFP_KERNEL);
	if (!kingsun->tx_urb)
		goto free_mem;

	kingsun->speed_urb = usb_alloc_urb(0, GFP_KERNEL);
	if (!kingsun->speed_urb)
		goto free_mem;

	/* Initialize speed for dongle */
	kingsun->new_speed = 9600;
	err = ks959_change_speed(kingsun, 9600);
	if (err < 0)
		goto free_mem;

	/*
	 * Now that everything should be initialized properly,
	 * Open new IrLAP layer instance to take care of us...
	 */
	sprintf(hwname, "usb#%d", kingsun->usbdev->devnum);
	kingsun->irlap = irlap_open(netdev, &kingsun->qos, hwname);
	if (!kingsun->irlap) {
		err = -ENOMEM;
		dev_err(&kingsun->usbdev->dev, "irlap_open failed\n");
		goto free_mem;
	}

	/* Start reception. Setup request already pre-filled in ks959_probe */
	usb_fill_control_urb(kingsun->rx_urb, kingsun->usbdev,
			     usb_rcvctrlpipe(kingsun->usbdev, 0),
			     (unsigned char *)kingsun->rx_setuprequest,
			     kingsun->rx_buf, KINGSUN_RCV_FIFO_SIZE,
			     ks959_rcv_irq, kingsun);
	kingsun->rx_urb->status = 0;
	err = usb_submit_urb(kingsun->rx_urb, GFP_KERNEL);
	if (err) {
		dev_err(&kingsun->usbdev->dev,
			"first urb-submit failed: %d\n", err);
		goto close_irlap;
	}

	netif_start_queue(netdev);

	/* Situation at this point:
	   - all work buffers allocated
	   - urbs allocated and ready to fill
	   - max rx packet known (in max_rx)
	   - unwrap state machine initialized, in state outside of any frame
	   - receive request in progress
	   - IrLAP layer started, about to hand over packets to send
	 */

	return 0;

      close_irlap:
	irlap_close(kingsun->irlap);
      free_mem:
	usb_free_urb(kingsun->speed_urb);
	kingsun->speed_urb = NULL;
	usb_free_urb(kingsun->tx_urb);
	kingsun->tx_urb = NULL;
	usb_free_urb(kingsun->rx_urb);
	kingsun->rx_urb = NULL;
	if (kingsun->rx_unwrap_buff.skb) {
		kfree_skb(kingsun->rx_unwrap_buff.skb);
		kingsun->rx_unwrap_buff.skb = NULL;
		kingsun->rx_unwrap_buff.head = NULL;
	}
	return err;
}

/*
 * Function kingsun_net_close (kingsun)
 *
 *    Network device is taken down. Usually this is done by
 *    "ifconfig irda0 down"
 */
static int ks959_net_close(struct net_device *netdev)
{
	struct ks959_cb *kingsun = netdev_priv(netdev);

	/* Stop transmit processing */
	netif_stop_queue(netdev);

	/* Mop up receive && transmit urb's */
	usb_kill_urb(kingsun->tx_urb);
	usb_free_urb(kingsun->tx_urb);
	kingsun->tx_urb = NULL;

	usb_kill_urb(kingsun->speed_urb);
	usb_free_urb(kingsun->speed_urb);
	kingsun->speed_urb = NULL;

	usb_kill_urb(kingsun->rx_urb);
	usb_free_urb(kingsun->rx_urb);
	kingsun->rx_urb = NULL;

	kfree_skb(kingsun->rx_unwrap_buff.skb);
	kingsun->rx_unwrap_buff.skb = NULL;
	kingsun->rx_unwrap_buff.head = NULL;
	kingsun->rx_unwrap_buff.in_frame = FALSE;
	kingsun->rx_unwrap_buff.state = OUTSIDE_FRAME;
	kingsun->receiving = 0;

	/* Stop and remove instance of IrLAP */
	if (kingsun->irlap)
		irlap_close(kingsun->irlap);

	kingsun->irlap = NULL;

	return 0;
}

/*
 * IOCTLs : Extra out-of-band network commands...
 */
static int ks959_net_ioctl(struct net_device *netdev, struct ifreq *rq, int cmd)
{
	struct if_irda_req *irq = (struct if_irda_req *)rq;
	struct ks959_cb *kingsun = netdev_priv(netdev);
	int ret = 0;

	switch (cmd) {
	case SIOCSBANDWIDTH:	/* Set bandwidth */
		if (!capable(CAP_NET_ADMIN))
			return -EPERM;

		/* Check if the device is still there */
		if (netif_device_present(kingsun->netdev))
			return ks959_change_speed(kingsun, irq->ifr_baudrate);
		break;

	case SIOCSMEDIABUSY:	/* Set media busy */
		if (!capable(CAP_NET_ADMIN))
			return -EPERM;

		/* Check if the IrDA stack is still there */
		if (netif_running(kingsun->netdev))
			irda_device_set_media_busy(kingsun->netdev, TRUE);
		break;

	case SIOCGRECEIVING:
		/* Only approximately true */
		irq->ifr_receiving = kingsun->receiving;
		break;

	default:
		ret = -EOPNOTSUPP;
	}

	return ret;
}

static const struct net_device_ops ks959_ops = {
	.ndo_start_xmit	= ks959_hard_xmit,
	.ndo_open	= ks959_net_open,
	.ndo_stop	= ks959_net_close,
	.ndo_do_ioctl	= ks959_net_ioctl,
};
/*
 * This routine is called by the USB subsystem for each new device
 * in the system. We need to check if the device is ours, and in
 * this case start handling it.
 */
static int ks959_probe(struct usb_interface *intf,
		       const struct usb_device_id *id)
{
	struct usb_device *dev = interface_to_usbdev(intf);
	struct ks959_cb *kingsun = NULL;
	struct net_device *net = NULL;
	int ret = -ENOMEM;

	/* Allocate network device container. */
	net = alloc_irdadev(sizeof(*kingsun));
	if (!net)
		goto err_out1;

	SET_NETDEV_DEV(net, &intf->dev);
	kingsun = netdev_priv(net);
	kingsun->netdev = net;
	kingsun->usbdev = dev;
	kingsun->irlap = NULL;
	kingsun->tx_setuprequest = NULL;
	kingsun->tx_urb = NULL;
	kingsun->tx_buf_clear = NULL;
	kingsun->tx_buf_xored = NULL;
	kingsun->tx_buf_clear_used = 0;
	kingsun->tx_buf_clear_sent = 0;

	kingsun->rx_setuprequest = NULL;
	kingsun->rx_urb = NULL;
	kingsun->rx_buf = NULL;
	kingsun->rx_variable_xormask = 0;
	kingsun->rx_unwrap_buff.in_frame = FALSE;
	kingsun->rx_unwrap_buff.state = OUTSIDE_FRAME;
	kingsun->rx_unwrap_buff.skb = NULL;
	kingsun->receiving = 0;
	spin_lock_init(&kingsun->lock);

	kingsun->speed_setuprequest = NULL;
	kingsun->speed_urb = NULL;
	kingsun->speedparams.baudrate = 0;

	/* Allocate input buffer */
	kingsun->rx_buf = kmalloc(KINGSUN_RCV_FIFO_SIZE, GFP_KERNEL);
	if (!kingsun->rx_buf)
		goto free_mem;

	/* Allocate input setup packet */
	kingsun->rx_setuprequest =
	    kmalloc(sizeof(struct usb_ctrlrequest), GFP_KERNEL);
	if (!kingsun->rx_setuprequest)
		goto free_mem;
	kingsun->rx_setuprequest->bRequestType =
	    USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE;
	kingsun->rx_setuprequest->bRequest = KINGSUN_REQ_RECV;
	kingsun->rx_setuprequest->wValue = cpu_to_le16(0x0200);
	kingsun->rx_setuprequest->wIndex = 0;
	kingsun->rx_setuprequest->wLength = cpu_to_le16(KINGSUN_RCV_FIFO_SIZE);

	/* Allocate output buffer */
	kingsun->tx_buf_clear = kmalloc(KINGSUN_SND_FIFO_SIZE, GFP_KERNEL);
	if (!kingsun->tx_buf_clear)
		goto free_mem;
	kingsun->tx_buf_xored = kmalloc(KINGSUN_SND_PACKET_SIZE, GFP_KERNEL);
	if (!kingsun->tx_buf_xored)
		goto free_mem;

	/* Allocate and initialize output setup packet */
	kingsun->tx_setuprequest =
	    kmalloc(sizeof(struct usb_ctrlrequest), GFP_KERNEL);
	if (!kingsun->tx_setuprequest)
		goto free_mem;
	kingsun->tx_setuprequest->bRequestType =
	    USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE;
	kingsun->tx_setuprequest->bRequest = KINGSUN_REQ_SEND;
	kingsun->tx_setuprequest->wValue = 0;
	kingsun->tx_setuprequest->wIndex = 0;
	kingsun->tx_setuprequest->wLength = 0;

	/* Allocate and initialize speed setup packet */
	kingsun->speed_setuprequest =
	    kmalloc(sizeof(struct usb_ctrlrequest), GFP_KERNEL);
	if (!kingsun->speed_setuprequest)
		goto free_mem;
	kingsun->speed_setuprequest->bRequestType =
	    USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE;
	kingsun->speed_setuprequest->bRequest = KINGSUN_REQ_SEND;
	kingsun->speed_setuprequest->wValue = cpu_to_le16(0x0200);
	kingsun->speed_setuprequest->wIndex = cpu_to_le16(0x0001);
	kingsun->speed_setuprequest->wLength =
	    cpu_to_le16(sizeof(struct ks959_speedparams));

	printk(KERN_INFO "KingSun KS-959 IRDA/USB found at address %d, "
	       "Vendor: %x, Product: %x\n",
	       dev->devnum, le16_to_cpu(dev->descriptor.idVendor),
	       le16_to_cpu(dev->descriptor.idProduct));

	/* Initialize QoS for this device */
	irda_init_max_qos_capabilies(&kingsun->qos);

	/* Baud rates known to be supported. Please uncomment if devices (other
	   than a SonyEriccson K300 phone) can be shown to support higher speed
	   with this dongle.
	 */
	kingsun->qos.baud_rate.bits =
	    IR_2400 | IR_9600 | IR_19200 | IR_38400 | IR_57600;
	kingsun->qos.min_turn_time.bits &= KINGSUN_MTT;
	irda_qos_bits_to_value(&kingsun->qos);

	/* Override the network functions we need to use */
	net->netdev_ops = &ks959_ops;

	ret = register_netdev(net);
	if (ret != 0)
		goto free_mem;

	dev_info(&net->dev, "IrDA: Registered KingSun KS-959 device %s\n",
		 net->name);

	usb_set_intfdata(intf, kingsun);

	/* Situation at this point:
	   - all work buffers allocated
	   - setup requests pre-filled
	   - urbs not allocated, set to NULL
	   - max rx packet known (is KINGSUN_FIFO_SIZE)
	   - unwrap state machine (partially) initialized, but skb == NULL
	 */

	return 0;

      free_mem:
	kfree(kingsun->speed_setuprequest);
	kfree(kingsun->tx_setuprequest);
	kfree(kingsun->tx_buf_xored);
	kfree(kingsun->tx_buf_clear);
	kfree(kingsun->rx_setuprequest);
	kfree(kingsun->rx_buf);
	free_netdev(net);
      err_out1:
	return ret;
}

/*
 * The current device is removed, the USB layer tell us to shut it down...
 */
static void ks959_disconnect(struct usb_interface *intf)
{
	struct ks959_cb *kingsun = usb_get_intfdata(intf);

	if (!kingsun)
		return;

	unregister_netdev(kingsun->netdev);

	/* Mop up receive && transmit urb's */
	if (kingsun->speed_urb != NULL) {
		usb_kill_urb(kingsun->speed_urb);
		usb_free_urb(kingsun->speed_urb);
		kingsun->speed_urb = NULL;
	}
	if (kingsun->tx_urb != NULL) {
		usb_kill_urb(kingsun->tx_urb);
		usb_free_urb(kingsun->tx_urb);
		kingsun->tx_urb = NULL;
	}
	if (kingsun->rx_urb != NULL) {
		usb_kill_urb(kingsun->rx_urb);
		usb_free_urb(kingsun->rx_urb);
		kingsun->rx_urb = NULL;
	}

	kfree(kingsun->speed_setuprequest);
	kfree(kingsun->tx_setuprequest);
	kfree(kingsun->tx_buf_xored);
	kfree(kingsun->tx_buf_clear);
	kfree(kingsun->rx_setuprequest);
	kfree(kingsun->rx_buf);
	free_netdev(kingsun->netdev);

	usb_set_intfdata(intf, NULL);
}

#ifdef CONFIG_PM
/* USB suspend, so power off the transmitter/receiver */
static int ks959_suspend(struct usb_interface *intf, pm_message_t message)
{
	struct ks959_cb *kingsun = usb_get_intfdata(intf);

	netif_device_detach(kingsun->netdev);
	if (kingsun->speed_urb != NULL)
		usb_kill_urb(kingsun->speed_urb);
	if (kingsun->tx_urb != NULL)
		usb_kill_urb(kingsun->tx_urb);
	if (kingsun->rx_urb != NULL)
		usb_kill_urb(kingsun->rx_urb);
	return 0;
}

/* Coming out of suspend, so reset hardware */
static int ks959_resume(struct usb_interface *intf)
{
	struct ks959_cb *kingsun = usb_get_intfdata(intf);

	if (kingsun->rx_urb != NULL) {
		/* Setup request already filled in ks959_probe */
		usb_submit_urb(kingsun->rx_urb, GFP_KERNEL);
	}
	netif_device_attach(kingsun->netdev);

	return 0;
}
#endif

/*
 * USB device callbacks
 */
static struct usb_driver irda_driver = {
	.name = "ks959-sir",
	.probe = ks959_probe,
	.disconnect = ks959_disconnect,
	.id_table = dongles,
#ifdef CONFIG_PM
	.suspend = ks959_suspend,
	.resume = ks959_resume,
#endif
};

module_usb_driver(irda_driver);

MODULE_AUTHOR("Alex Villacís Lasso <a_villacis@palosanto.com>");
MODULE_DESCRIPTION("IrDA-USB Dongle Driver for KingSun KS-959");
MODULE_LICENSE("GPL");


text:
import string
from tt_generator import *

class HTMLPrettyPrinter:

    def __init__(self):
        self.course_colors = {}
        self.color_gen = color_generator()

    def color(self, course_name):
        if not course_name in self.course_colors.keys():
            self.course_colors[course_name] = self.color_gen.next()
        return self.course_colors[course_name]

    def print_timetables(self, timetables, total_combinations):
        table_id = 0
        print intro(len(timetables), total_combinations)
        for timetable in timetables:
            table_id += 1
            print self.format_timetable(timetable, table_id)
        print outro()

    def format_timetable(self, timetable, table_id):

        # initialize content for each cell
        content = [["class='period-empty-slot' > " \
                    for x in xrange(32)] \
                   for y in xrange(6)]

        # fill out the content according to the lesson slots
        for slot in timetable.lessons:
            day_i = slot.day
            start_i = time_index(slot.start)
            end_i = time_index(slot.end)

            content[day_i][start_i] = "class='period-first-slot' "
            content[day_i][end_i-1] = "class='period-last-slot' "
            for time_i in xrange(start_i+1, end_i-1):
                content[day_i][time_i] = "class='period-middle-slot' "

            for time_i in xrange(start_i, end_i):
                content[day_i][time_i] += "style='background-color: %s'  " \
                                          % (self.color(slot.course_name()))
                content[day_i][time_i] += "headers='weekday%i hour%i'  " \
                                          % (day_i, time_i)
                content[day_i][time_i] += "title='%s-%s'> " \
                                          % (slot.start, slot.end)

            content[day_i][start_i] += "%s  (%s) %s" \
                                       % (slot.course_name(), slot.lesson_category(), slot.room)

        # format the HTML for the timetable
        html_result = [table_intro(table_id)]
        for row in xrange(0,32):
            html_result.append("
\n")
            html_result.append("                %s-%s	\n" % (row, time_from_index(row), time_from_index(row+1)))
            for column in xrange(0,6):
                html_result.append("                <td  %s	\n" % (content[column][row]))
            html_result.append("
\n")
        html_result.append(table_outro())
        return string.join(html_result, '')

def time_index(time):
    return (time.minutes - 8*60) / 30

def time_from_index(index):
    return Time(index/2 + 8, (index%2) * 30)

def color_generator():
    pallete = [ "#A8FFFF", "#AFEEEE", "#00FFFF", "#87CEFA", "#A8D4FF", \
                "#B0C4DE", "#BAEDD3", "#7FFFD4", "#51FFA9", "#40E0D0", \
                "#D8BAED", "#ADFF2F", "#32CD32", "#00FF7F", "#F9A8FF", \
                "#FFBA51", "#FF9A00", "#FFA07A", "#F7AFB3", "#FFC0A8", \
                "#FFC0CB", "#FFD700", "#FFDEAD", "#FFECA8", "#F0E68C", \
                "#FFFFFF", "#F0FFF0", "#F0FFFF", "#F8F8FF", "#F5F5F5", \
                "#FFF5EE", "#F5F5DC", "#FFFFF0", "#FDF5E6", "#FAEBD7", \
                "#FFE4E1", "#FAF0E6"]
    for color in pallete:
        yield color

def intro(total_selected, total_combinations):
    return """\
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=cp1252">
    <title>Horários gerados</title>
    <link rel='stylesheet' type='text/css' media='screen' href='https://fenix.tecnico.ulisboa.pt/cursos/meic-a/static/css/publicPages.css' />
    <link rel='stylesheet' type='text/css' media='screen,print' href='http://fenix.ist.utl.pt/CSS/dotist_timetables.css' />

      (A mostrar os 100 horários mais compactos dum total de %i combinações)

""" % (total_selected, "" if (total_selected < total_combinations) else "display:none;", total_combinations)

def table_intro(id_number):
    return """\

                Horas/Dias
                Segunda
                Terça
                Quarta
                Quinta
                Sexta
                Sábado

""" % (id_number)

def table_outro():
    return """\

"""

def outro():
    return """\

"""


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=11"/>
<meta name="generator" content="Doxygen 1.9.3"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Kernel Tuning Toolkit: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

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

Kernel Tuning Toolkit 2.1

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

ktt::KernelProfilingData Member List

This is the complete list of members for ktt::KernelProfilingData, including all inherited members.

AddCounter(const KernelProfilingCounter &counter)	ktt::KernelProfilingData

DecreaseRemainingProfilingRuns()	ktt::KernelProfilingData

GetCounter(const std::string &name) const	ktt::KernelProfilingData

GetCounters() const	ktt::KernelProfilingData

GetRemainingProfilingRuns() const	ktt::KernelProfilingData

HasCounter(const std::string &name) const	ktt::KernelProfilingData

HasRemainingProfilingRuns() const	ktt::KernelProfilingData

IsValid() const	ktt::KernelProfilingData

KernelProfilingData()=default	ktt::KernelProfilingData

KernelProfilingData(const uint64_t remainingRuns)	ktt::KernelProfilingData	explicit

KernelProfilingData(const std::vector< KernelProfilingCounter > &counters)	ktt::KernelProfilingData	explicit

SetCounters(const std::vector< KernelProfilingCounter > &counters)	ktt::KernelProfilingData

Generated by  1.9.3


text:
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useAdaptivity = void 0;
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var React = _interopRequireWildcard(require("react"));
var _vkjs = require("@vkontakte/vkjs");
var _AdaptivityContext = require("../components/AdaptivityProvider/AdaptivityContext");
var _excluded = ["hasMouse"];
var useAdaptivity = function useAdaptivity() {
  var _React$useContext = React.useContext(_AdaptivityContext.AdaptivityContext),
    hasMouseContext = _React$useContext.hasMouse,
    adaptivity = (0, _objectWithoutProperties2.default)(_React$useContext, _excluded);
  var _React$useState = React.useState(hasMouseContext),
    _React$useState2 = (0, _slicedToArray2.default)(_React$useState, 2),
    hasMouse = _React$useState2[0],
    setHasMouse = _React$useState2[1];

  // определение hasMouse в @vkontakte/vkjs происходит через window.matchMedia
  // чтобы не было ошибок при гидрации определяем значение после первого рендера
  React.useEffect(function () {
    if (hasMouseContext !== undefined) {
      setHasMouse(hasMouseContext);
    } else {
      setHasMouse(_vkjs.hasMouse);
    }
  }, [hasMouseContext]);
  return (0, _objectSpread2.default)({
    hasMouse: hasMouse
  }, adaptivity);
};
exports.useAdaptivity = useAdaptivity;
//# sourceMappingURL=useAdaptivity.js.map


text:
{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
module React.Flux.Export where

#ifdef __GHCJS__

import Data.Typeable (Typeable)
import Unsafe.Coerce

import GHCJS.Types

newtype Export a = Export JSVal

foreign import javascript unsafe
    "hsreact$export($1)"
    js_export :: Double -> IO (Export a)

export :: Typeable a => a -> IO (Export a)
export = js_export . unsafeCoerce

foreign import javascript unsafe
    "hsreact$derefExport($1)"
    js_deref :: Export a -> IO Double

derefExport :: Typeable a => Export a -> IO (Maybe a)
derefExport e = (Just . unsafeCoerce) <$> js_deref e

parseExport :: Typeable a => Export a -> IO a
parseExport a = (unsafeCoerce <$> js_deref a)

foreign import javascript unsafe
    "$r = $1"
    js_unsafeExport :: Double -> IO (Export a)

-- | A variation on export which does not retain the value for garbage collection
unsafeExport :: Typeable a => a -> IO (Export a)
unsafeExport = js_unsafeExport . unsafeCoerce

foreign import javascript unsafe
    "$r = $1"
    js_unsafeDeref :: Export a -> IO Double

unsafeDerefExport :: Typeable a => Export a -> IO a
unsafeDerefExport e = unsafeCoerce <$> js_unsafeDeref e

#endif


text:
<?php

namespace spec\Aco\Domain\Aco;

use PhpSpec\ObjectBehavior;

class ContentExtractorSpec extends ObjectBehavior
{
    public function it_can_extract_content()
    {
        $sourceContent = '

no

content here

yes

no!

';
        $content = '
content here

yes
';
        $this::extractContent($sourceContent)->shouldReturn($content);
    }

    public function it_can_remove_styles()
    {
        $sourceContent = '

content

';
        $content = '
content
';
        $this::extractContent($sourceContent)->shouldReturn($content);
    }

    public function it_can_return_empty_content()
    {
        $sourceContent = '';
        $content = '';
        $this::extractContent($sourceContent)->shouldReturn($content);
    }
}


text:
use elmesque::Element;
use position::{Depth, Point};

pub use self::custom::Custom;
pub use self::custom::State as CustomState;

pub mod button;
pub mod custom;
pub mod drop_down_list;
pub mod envelope_editor;
pub mod label;
pub mod matrix;
pub mod number_dialer;
pub mod slider;
pub mod text_box;
pub mod toggle;
pub mod xy_pad;

/// A widget element for storage within the Ui's `widget_cache`.
#[derive(Clone, Debug)]
pub struct Widget<C=()> where C: Custom {
    pub kind: Kind<C>,
    pub xy: Point,
    pub depth: Depth,
    pub element: Element,
    pub set_since_last_drawn: bool,
}

impl<C> Widget<C> where C: Custom {

    /// Construct an empty Widget for a vacant widget position within the Ui.
    pub fn empty() -> Widget<C> {
        Widget {
            kind: Kind::NoWidget,
            xy: [0.0, 0.0],
            depth: 0.0,
            element: ::elmesque::element::empty(),
            set_since_last_drawn: false,
        }
    }

    /// Construct a Widget from a given kind.
    pub fn new(kind: Kind<C>) -> Widget<C> {
        Widget {
            kind: kind,
            xy: [0.0, 0.0],
            depth: 0.0,
            element: ::elmesque::element::empty(),
            set_since_last_drawn: false,
        }
    }

}

/// Algebraic widget type for storing in ui_context
/// and for ease of state-matching.
#[derive(Copy, Clone, Debug)]
pub enum Kind<C=()> where C: Custom {
    NoWidget,
    Button(button::State),
    DropDownList(drop_down_list::State),
    EnvelopeEditor(envelope_editor::State),
    Label,
    NumberDialer(number_dialer::State),
    Slider(slider::State),
    Spacer,
    TextBox(text_box::State),
    Toggle(toggle::State),
    XYPad(xy_pad::State),
    Custom(C::State),
}

impl<C> Kind<C>
    where
        C: Custom,
        C::State: CustomState,
{
    pub fn matches(&self, other: &Kind<C>) -> bool {
        match (self, other) {
            (&Kind::NoWidget, &Kind::NoWidget) => true,
            (&Kind::Button(_), &Kind::Button(_)) => true,
            (&Kind::DropDownList(_), &Kind::DropDownList(_)) => true,
            (&Kind::EnvelopeEditor(_), &Kind::EnvelopeEditor(_)) => true,
            (&Kind::Label, &Kind::Label) => true,
            (&Kind::NumberDialer(_), &Kind::NumberDialer(_)) => true,
            (&Kind::Slider(_), &Kind::Slider(_)) => true,
            (&Kind::Spacer, &Kind::Spacer) => true,
            (&Kind::TextBox(_), &Kind::TextBox(_)) => true,
            (&Kind::Toggle(_), &Kind::Toggle(_)) => true,
            (&Kind::XYPad(_), &Kind::XYPad(_)) => true,
            (&Kind::Custom(ref state_a), &Kind::Custom(ref state_b)) => state_a.matches(state_b),
            _ => false
        }
    }
}

/// An update to be returned by the widget after each pass.
pub struct Update<T> {
    /// The new state of the Widget.
    pub new_state: T,
    /// The position of the Widget given as [x, y] coordinates.
    pub xy: Point,
    /// The rendering depth for the Widget (the default is 0.0).
    pub depth: Depth,
    /// The element to be used for drawing.
    pub element: Element,
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
CellNumberPartHandler (POI API Documentation)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.poi.ss.format

Class CellNumberPartHandler

java.lang.Object
  org.apache.poi.ss.format.CellNumberPartHandler

@Internal
public class CellNumberPartHandler
extends java.lang.Object

Internal helper class for CellNumberFormatter

Constructor Summary

CellNumberPartHandler()

Method Summary

 org.apache.poi.ss.format.CellNumberFormatter.Special
getDecimalPoint()

 org.apache.poi.ss.format.CellNumberFormatter.Special
getExponent()

 org.apache.poi.ss.format.CellNumberFormatter.Special
getNumerator()

 double
getScale()

 org.apache.poi.ss.format.CellNumberFormatter.Special
getSlash()

 java.util.List<org.apache.poi.ss.format.CellNumberFormatter.Special>
getSpecials()

 java.lang.String
handlePart(java.util.regex.Matcher m,
           java.lang.String part,
           CellFormatType type,
           java.lang.StringBuffer descBuf)

 boolean
isImproperFraction()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

CellNumberPartHandler

public CellNumberPartHandler()

Method Detail

handlePart

public java.lang.String handlePart(java.util.regex.Matcher m,
                                   java.lang.String part,
                                   CellFormatType type,
                                   java.lang.StringBuffer descBuf)

getScale

public double getScale()

getDecimalPoint

public org.apache.poi.ss.format.CellNumberFormatter.Special getDecimalPoint()

getSlash

public org.apache.poi.ss.format.CellNumberFormatter.Special getSlash()

getExponent

public org.apache.poi.ss.format.CellNumberFormatter.Special getExponent()

getNumerator

public org.apache.poi.ss.format.CellNumberFormatter.Special getNumerator()

getSpecials

public java.util.List<org.apache.poi.ss.format.CellNumberFormatter.Special> getSpecials()

isImproperFraction

public boolean isImproperFraction()

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

                Copyright 2017 The Apache Software Foundation or
        its licensors, as applicable.


text:
package Server;

import java.io.Serializable;

public class Player implements Serializable{
	private static final long serialVersionUID = 7695261978618738318L;

	//// PLAYER PROPERTIES
	private String username;
	private String password;
	private String fname, lname;

	public Player(String username, String password, String firstName, String lastName){
		setUsername(username);
		setPassword(password);
		setFirstName(firstName);
		setLastName(lastName);
	}

	//// SETTERS AND GETTERS ////////
	public String getUsername() {
		return username;
	}

	private void setUsername(String username) {
		this.username = username;
	}

	protected String getPassword() {
		return password;
	}

	private void setPassword(String password) {
		this.password = password;
	}

	public String getLastName() {
		return lname;
	}

	private void setLastName(String lname) {
		this.lname = lname;
	}

	public String getFirstName() {
		return fname;
	}

	private void setFirstName(String fname) {
		this.fname = fname;
	}
}