text:
/**
 *   ____    __    ____  ____  ____,,___     ____  __  __  ____
 *  (  _ \  /__\  (_   )(_  _)( ___)/ __)   (  _ \(  )(  )(  _ \           Read
 *   )   / /(__)\  / /_  _)(_  )__) \__ \    )___/ )(__)(  ) _ <     README.txt
 *  (_)\_)(__)(__)(____)(____)(____)(___/   (__)  (______)(____/    LICENSE.txt
 */
package razie.diesel.dom

import com.razie.pub.comms.{CommRtException, Comms}
import java.net.{HttpURLConnection, URI}
import org.json.JSONObject
import razie.Snakk._
import razie.diesel.Diesel
import razie.diesel.dom.RDOM._
import razie.diesel.engine.nodes.EMsg
import razie.diesel.expr.ECtx
import razie.tconf.{DSpecInventory, FullSpecRef, SpecRef}
import razie.wiki.Sec
import razie.{Snakk, clog, js}
import scala.collection.mutable
import scala.util.Try

/** ODATA CRM domain plugin */
class DomInvOdataCRMPlugin(
  override val name: String = "d365odata",
  var props: Map[String, String] = Map.empty
) extends DomInventory {

  // annotation specific to these classes
  final val ODATA_NAME = "odata.name"

  override def conn = props.getOrElse("conn.name", "default")

  var realm: String = ""
  var env: String = ""
  var specInv: Option[DSpecInventory] = None
  var iprops: Map[String, String] = Map.empty

  /**
    * can this support the class? You can look at it's annotations etc
    */
  override def isDefinedFor(realm: String, c: C): Boolean = {
    c.props.find(_.name == ODATA_NAME).isDefined || super.isDefinedFor(realm, c)
  }

  /** if the ReactorMod is present and a connection, create it - just one conn */
  override def mkInstance(irealm: String, ienv: String, wi: DSpecInventory, newName: String, dprops: Map[String,
      String] = Map.empty)
  : List[DomInventory] = {
    this.iprops = dprops
    realm = irealm
    env = ienv
    specInv = Some(wi)
    reset(iprops, newName)
  }

  private def reset(iprops: Map[String, String], newName: String): List[DomInventory] = {
    val pspec = SpecRef(realm, realm + ".ReactorMod:ODataCrmDomainPlugin", "ODataCrmDomainPlugin")
    val props = SpecRef(realm, realm + ".Form:ODataCrmDomainProps", "ODataCrmDomainProps")

    specInv
        .flatMap(_.findSpec(pspec))
        .flatMap(x => specInv.flatMap(_.findSpec(props)))
        .toList
        .map { wprops =>
          val ret = new DomInvOdataCRMPlugin(newName, iprops ++ wprops.allProps)
          ret.realm = realm
          ret.specInv = this.specInv
          ret.iprops = this.iprops
          ret.env = this.env
          ret
        }

    // todo add observer when form changes and not reset all the time
    // todo design mechanism for wiki changes propagating and objects changing state
  }

  def configuredAccessToken = props.getOrElse("odata.accessToken", "")

  def authUrl = props.getOrElse("odata.authUrl", "")

  def authClient = props.getOrElse("odata.authClient", "")

  def authSecret = props.getOrElse("odata.authSecret", "")

  def URL = props.getOrElse("odata.url", "")

  def accessToken = iAccessToken.getOrElse {
    if (configuredAccessToken.length > 10) {
      iAccessToken = Some(configuredAccessToken)
    } else {
      val j = Snakk.json(
        url(
          authUrl,
          Map("Content-type" -> "application/x-www-form-urlencoded")
        ).form(
          Map(
            "grant_type" -> "client_credentials",
            "client_id" -> authClient,
            "client_secret" -> (authSecret),
            "resource" -> URL
          ) ++ {
            // todo ugliest hack - when using backend, put the sud/iss sequence as authClient
            if (authClient.contains("iss=Omniware"))
              authClient.split("&").filter(_.contains("=")).map { a =>
                val x = a.split("=")
                (x(0), Sec.decUrl(x(1)))
              }.toList.toMap
            else
              Map.empty[String, String]
          }
        )
      )

      clog << "oauth reply: " + j
      iAccessToken = Some(j \@ "access_token")
    }
    iAccessToken.get
  }

  var iAccessToken: Option[String] = None

  def classOname(c: C): String =
    c.props.find(_.name == ODATA_NAME).map(_.calculatedValue(ECtx.empty)).getOrElse(c.name)

  // reset during calls
  var completeUri: String = ""

  /** html for the supported actions */
  def htmlActions(elem: DE): String = {
    elem match {
      case c: C => {
        val oname = classOname(c)

        def mkMetA = s"""attrs"""
        def mkMet = s"""def"""
        def mkSample = s"""sample"""
        def mkListAll = s"""listAll"""

        s"$mkMet | $mkMetA | $mkSample | $mkListAll"
      }

      case _ => "?"
    }
  }

  /**
    * do an action on some domain entity (explore, browse etc)
    *
    * @param dom         the domain
    * @param action      the action to execute
    * @param completeUri the entire URL called (use it to get host/port etc)
    * @param epath       id of the entity
    * @return
    */
  def doAction(dom: RDomain, conn:String, action: String, completeUri: String, epath: String): String = {
    try {
      // todo for now to force reloading the attributes
      reset(iprops, name)

      this.completeUri = completeUri
      val ref = new FullSpecRef(this.name, conn, epath, "", "", realm)

      action match {
        case "testConnection" => DomInventories.resolve(false, ref, testConnection(dom, epath)).currentStringValue
        case "findByRef" => findByRefs(dom, epath)
        case "findByQuery" => findByQuerys(dom, epath)
        case "listAll" => xlistAll(dom, epath)

        case "accessToken" => accessToken
        case "attrs" => getEntityAttrs(dom, action, epath)
        case "sample" => redirectToSample(dom, action, epath)
        case "listClasses" => listClasses(dom, epath)
        case "metaClass" => metaClass(dom, epath)
        case "metaAttrs" => metaAttrs(dom, epath)
        case "makeClass" => makeClass(dom, epath, loadClasses(dom))
        case "makeAllClasses" => makeAllClasses(dom, action, epath)
        case _ => throw new NotImplementedError(s"doAction $action - $completeUri - $epath")
      }
    } catch {
      case e: Throwable =>
        resetOnError(e)
        throw e
    }
  }

  /** reset oauth tokens etc on error */
  override def resetOnError(error: Throwable) = {
    // protection against stale tokens
    this.iAccessToken = None
  }

  /** html for the supported actions */
  override def testConnection(dom: RDomain, epath: String): Either[P, EMsg] = {
    val s =
      s"""testing auth...\n
         |
         |authUrl=$authUrl\n
         |authClient=$authClient\n
         |authSecret=$authSecret\n
         |\n
         |accessToken=${accessToken}\n
         |\n
         |listClasses=${listClasses(dom, epath).split(",").size}\n
         |
     """.stripMargin
    Left(P.of(Diesel.PAYLOAD, s))
  }

  override def connect(dom: RDomain, env: String): Either[P, EMsg] =
    Left(P.of(Diesel.PAYLOAD, "ok"))

  /** html for the supported actions */
  private def getEntityAttrs(dom: RDomain, action: String, epath: String): String = {
    dom.classes.get(epath) match {
      case Some(c) => {
        val oname = classOname(c)

        getEntityAttrsFor(dom, oname, loadClasses(dom))
      }

      case _ => "eh?"
    }
  }

  val filterAttrs =("owningteam,modifiedby,owninguser,owneridname,createdonbehalfby,utcconversiontimezonecode,"+
    "importsequencenumber,createdbyyominame,owningbusinessunit,modifiedbyname,"+
    "owningteam,modifiedby,modifiedbyyominame,createdby,timezoneruleversionnumber,owneridtype,owneridyominame,"+
    "modifiedon,modifiedonbehalfbyyominame,createdbyname,createdon,createdonbehalfbyname,modifiedonbehalfbyname,"+
    "versionnumber,modifiedonbehalfby,ownerid,overriddencreatedon,createdonbehalfbyyominame").split(",")

  /** html for the supported actions */
  private def getEntityAttrsFor (dom: RDomain, epath: String, classNames:Map[String,String], collectRefs : Option[mutable.HashMap[String,String]] = None): String = {
    val host = new URI(completeUri).getHost

    def mkMetA = URL + s"/api/data/v8.2/EntityDefinitions(LogicalName='${epath}')/Attributes"

    val b = Snakk.body(Snakk.url(
      mkMetA,
      Map("Authorization" -> accessToken)
    ))

        val jj = Snakk.jsonParsed(b)

        val m = js.fromObject(jj)

        val buf =
          m("value")
            .asInstanceOf[List[Map[String, Any]]]
            .filter(_.get("AttributeType").exists(_ != "Virtual"))
            .filter(x=> !filterAttrs.contains(x.get("LogicalName").mkString))
            .map { a =>

              val n = a.get("LogicalName").mkString

              var s = s"  $n"

              if (a.get("AttributeType").exists(_ == "Lookup")) {
                val t = a("Targets").asInstanceOf[List[Any]].head.toString

                val d = a("DisplayName")
                  .asInstanceOf[Map[String, Any]]("UserLocalizedLabel")
                  .asInstanceOf[Map[String, Any]]("Label")
                  .toString.replaceAll("[ ()]", "")

                val cn = classNames.getOrElse(t, t)
                s = s"  $n : <> $cn"

                collectRefs.map (_.put(t.toString, cn)) // collect all the refs
              }
              s
            }.mkString(",\n")

        buf
  }

  private def getValueFromResp(url: String): List[Map[String, Any]] = {
    val jj = Snakk.jsonParsed(Snakk.body(Snakk.url(url)))
    val m = js.fromObject(jj)

    m("value")
      .asInstanceOf[List[Map[String, Any]]]
  }

  private def getValueFromBody(b: String): List[Map[String, Any]] = {
    val jj = Snakk.jsonParsed(b)
    val m = js.fromObject(jj)

    m("value")
      .asInstanceOf[List[Map[String, Any]]]
  }

  /** query for the first sample of this class */
  private def redirectToSample(dom: RDomain, action: String, epath: String): String = {
    dom.classes.get(epath) match {
      case Some(c: C) => {
        val oname = classOname(c)

        def mkSample = s"""sample"""

        val j = Snakk.jsonParsed(mkSample)

        j.toString(2)
      }

      case _ => "?"
    }
  }

  /** list classes */
  private def loadClasses(dom: RDomain): Map[String,String] = {
    val host = new URI(completeUri).getHost

    val snak = crmJson(URL+s"/api/data/v8.2/EntityDefinitions?$$select=LogicalName,DisplayName")

    val v = snak \ "value"

    val buf = v.nodes.map(snak.wrap).map {v=>

      val n = v \@ "LogicalName"
      val ln = (v \ "DisplayName" \ "UserLocalizedLabel" \@@ "Label" OR "").toString.replaceAllLiterally(" ", "").replaceAllLiterally("/", "")
      (n,ln)
    }

    buf.toSeq.toMap
  }

  /** list classes */
  private def listClasses(dom: RDomain, epath: String): String = {
    val host = new URI(completeUri).getHost

    val classNames = loadClasses(dom)

    val buf =
      classNames.keySet
//        .filter(_.get("LogicalName").exists(_.toString startsWith "omni_"))
        .toList
        .sorted
        .map{t=>
          val d = classNames(t)
          s"""$t - $d |
             | met |
             | attrs |
             | make
           """.stripMargin

        }
        .mkString("
\n")

    "
" + buf
  }

  /**
    * find by entity/ref
    */
  private def findByRefs(dom:RDomain, epath: String, collectRefs:Option[mutable.HashMap[String,String]]=None): String = {
    val host = new URI(completeUri).getHost
    val PAT = """([^/]+)/(.+)""".r
    val PAT(cls, id) = epath

    dom.classes.get(cls).map { classDef=>
      val oname = classOname(classDef)
      val u = URL+s"/api/data/v8.2/${oname}s($id)"

      val b = crmJson(u)

      b.node.j.asInstanceOf[JSONObject].toString(2)
    } getOrElse
    "Class not found..."
  }

  /**
    * find by field value
    */
  private def findByQuerys(dom:RDomain, epath: String, collectRefs:Option[mutable.HashMap[String,String]]=None): String = {
    val host = new URI(completeUri).getHost
    val PAT = """([^/]+)/(.+)/(.+)""".r
    val PAT(cls, field, id) = epath
    val filter = Sec.encUrl(s"$field eq $id")

    doQuery(cls, dom, filter, collectRefs)
  }

  /**
    * list all
    */
  private def xlistAll(dom: RDomain, epath: String, collectRefs: Option[mutable.HashMap[String, String]] = None)
  : String = {
//    : Either[List[DieselAsset[_]], EMsg] = {
    doQuery(epath, dom, "", collectRefs)
  }

  /**
    * list all
    */
  private def doQuery (cls:String, dom:RDomain, filter: String, collectRefs:Option[mutable.HashMap[String,String]]=None): String = {
    val host = new URI(completeUri).getHost

    dom.classes.get(cls).map { classDef=>
      val oname = classOname(classDef)
      val u =
        if(filter.length > 0) URL + s"/api/data/v8.2/${oname}s?$$filter=" + filter
        else URL + s"/api/data/v8.2/${oname}s?$$top=100"

      val b1 = crmJson(u)

      val b = crmJson(u)

      return b1.node.j.asInstanceOf[JSONObject].toString(2)

      val v = b \ "value"

      v.nodes.headOption.map {n=>
        val jo = n.j.asInstanceOf[JSONObject]

        val o = oFromJ("x", jo, classDef)

        n.j.asInstanceOf[JSONObject].toString(2)
      } getOrElse
      "entity not found..."
    } getOrElse
      "Class not found..."
  }

  /** turn a json value into a nice object, merge with class def and mark refs etc */
  def oFromJ(key: String, j: JSONObject, c: C) = {
    // see DomInventories.oFromJ - but this one needs more filtering

    // move parms containing name/desc to the top of the list
    val parmNames = j.keySet
        .toArray
        .toList
        .map(_.toString)
        .filter(n => !n.startsWith("@"))
        .filter(n => !filterAttrs.contains(n))
    //      .sorted
    val a1 = parmNames.filter(n => n.contains("name") || n.contains("key"))
    val a2 = parmNames.filter(n => n.contains("description") || n.contains("code"))
    val b = parmNames.filterNot(n => n.contains("name") || n.contains("description") || n.contains("code"))

    val parms = (a1 ::: a2 ::: b)
        .map { k =>
          val value = j.get(k).toString
          val kn = k.toString
          val oname = classOname(c)

          c.parms.find(_.name == kn).map { cp =>
            cp.copy(dflt = value)// todo add PValue
          } getOrElse {
            // key refs
            if (kn.startsWith("_") && kn.endsWith(("_value"))) {
              val PAT = """_(.+)_value""".r
              val PAT(n) = kn

              c.parms.find(_.name == n).map { cpk =>
                cpk.copy(dflt = value) // todo add PValue
              } getOrElse {
                P.of(kn, value)
              }
            } else
              P.of(kn, value)
          }
        }

    O(key, c.name, parms)
  }

  def crmJson(url:String) = {
    clog << "Snakking: " + url
    try {
      val b = Snakk.body(Snakk.url(
        url,
        Map("Authorization" -> accessToken)
      ))

      Snakk.json(b)
    } catch {
      case cre:CommRtException if cre.uc != null => {
        val resCode = cre.uc.getHeaderField(0)
        val c = Comms.readStream(cre.uc.asInstanceOf[HttpURLConnection].getErrorStream)
        val msg = "Could not fetch data from url " + url + ", resCode=" + resCode + ", content=" + c
        clog << "SNAKK COMM ERR: " + (msg)

        val jc = if(c.startsWith("{") && c.endsWith("}")) c else s""""$c""""

        val jo = new JSONObject()
        jo.append("url", url)

        if(c.startsWith("{") && c.endsWith("}"))
          jo.append("error", c)
        else
        jo.append("error", c)

        // just in case it may have expired - reset the token
        iAccessToken=None

        Snakk.json(jo)
      }
    }
  }

  /**
    * find by entity/ref
    */
  override def findByRef(dom: RDomain, ref: FullSpecRef, collectRefs: Option[mutable.HashMap[String, String]] = None)
  : Either[Option[DieselAsset[_]], EMsg] = {
    val host = new URI(completeUri).getHost

    Left(dom.classes.get(ref.cls).map { classDef =>
      val oname = classOname(classDef)

      // the idiots use an englishly-correct plural
      val plural = if (oname endsWith "y") oname.take(oname.length - 1) + "ies" else oname + "s"

      val u = URL + s"/api/data/v8.2/$plural(${ref.key})"

      val b = crmJson(u)

//      b.node.j.asInstanceOf[JSONObject].toString(2)

      val o = oFromJ(ref.key, b.node.j.asInstanceOf[JSONObject], classDef)
      new DieselAsset[O](ref, o)
    })
  }

  /**
    * find by field value
    *
    * if the field and id is null, then no filter
    */
  override def findByQuery(dom: RDomain, ref: FullSpecRef, epath: Either[String, collection.Map[String, Any]],
                           from: Long = 0, size: Long = 100,
                           sort: Array[String],
                           countOnly: Boolean = false,
                           collectRefs: Option[mutable.HashMap[String, String]] = None):
  Either[DIQueryResult, EMsg] = {

    val host = new URI(completeUri).getHost
    val PAT = DomInventories.CLS_FIELD_VALUE
    // only support by path
    val PAT(cls, field, id) = epath.left.get

    Left(
      dom.classes.get(cls).map { classDef =>
        val oname = classOname(classDef)

        // the idiots use an englishly-correct plural
        val plural = if (oname endsWith "y") oname.take(oname.length - 1) + "ies" else oname + "s"

        val filter = {
          if (id == "" || id == "*" || id == "'*'")
            s"$$top=50"
          else
//            s"$$filter=" + Sec.encUrl(s"${field} eq $id")
            s"$$filter=" + Sec.encUrl(s"_${field}_value eq $id")
        }

        //        val u = URL + s"/api/data/v8.2/$plural?" + filter
        val u = URL + s"/api/data/v8.2/$plural?" + s"_${filter}_value"

        val b = crmJson(u)

        val v = b \ "value"

        DIQueryResult(v.nodes.size, v.nodes.toList.map { n =>
          val jo = n.j.asInstanceOf[JSONObject]
          val key = if (jo.has(oname + "id")) jo.get(oname + "id").toString else epath.left.get
          val o = oFromJ(key, jo, classDef)
          new DieselAsset[O](SpecRef.make(ref.realm, name, conn, classDef.name, key), o)
        })
      }.getOrElse(DIQueryResult(0))
    )
  }

  /**
    * compose a clas defn
    * @param epath CRM name like omni_invoice
    */
  private def metaClass(dom:RDomain, epath: String): String = {
    val host = new URI(completeUri).getHost

    val snak = crmJson(URL+s"/api/data/v8.2/EntityDefinitions?$$filter=" + Sec.encUrl(s"LogicalName eq '${epath}'"))

    snak.node.j.asInstanceOf[JSONObject].toString(2)
  }

  /**
    * compose a clas defn
    * @param epath CRM name like omni_invoice
    */
  private def metaAttrs(dom:RDomain, epath: String): String = {
    val host = new URI(completeUri).getHost

    def mkMetA = URL + s"/api/data/v8.2/EntityDefinitions(LogicalName='${epath}')/Attributes"
    val snak = crmJson(mkMetA)

    snak.node.j.asInstanceOf[JSONObject].toString(2)
  }

  /**
    * compose a clas defn
    * @param epath CRM name like omni_invoice
    */
  private def makeClass(dom:RDomain, epath: String, classNames:Map[String,String], collectRefs:Option[mutable.HashMap[String,String]]=None): String = {
    val host = new URI(completeUri).getHost

    val snak = crmJson(URL+s"/api/data/v8.2/EntityDefinitions?$$filter=" + Sec.encUrl(s"LogicalName eq '${epath}'"))

    val v = snak.wrap(snak \\\ "value")

    val n = v \@ "LogicalName"
    val ln = (v \ "DisplayName" \ "UserLocalizedLabel" \@@ "Label" OR "").toString.replaceAllLiterally(" ", "")

    var s = ""
    s += s"""$$anno (odata.name="$n")\n"""
    s += s"$$class $ln (\n"
    s += getEntityAttrsFor(dom,n, classNames, collectRefs)
    s += s"\n)\n"

    s
  }

  /** compose a clas defn */
  private def makeAllClasses(dom: RDomain, action: String, epath: String): String = {
    val classNames = loadClasses(dom)
    val refs = new mutable.HashMap[String,String]()

    val c = classNames.keys.toSeq.sorted.filter(_.startsWith("omni")).map {cn=>
      (cn, s"## ${classNames(cn)} ($cn)\n\n" + makeClass(dom, cn, classNames, Some(refs)))
    }.toMap

    // all refs, no duplicates and no name conflicts (i.e. product is Product would overwrite omni_product which is also Product
    val c2 = refs.keys
      .toSeq
      .sorted
      .filterNot{n=>
        val dn = refs(n)
        c.contains(n) || classNames.exists(e=> e._2==dn && c.contains(e._1))
      }.map {cn=>
      (cn, s"## ${classNames(cn)} ($cn)\n\n" + Try {
        makeClass(dom, cn, classNames, Some(refs))
      }.getOrElse("Error...")
      )
    }.toMap

    val call = c ++ c2

   val cs = call.keys.toSeq.sorted.map {k=>
     call.get(k).mkString
   }.mkString("\n\n")

    var s = ""
    s += s"""Domain... total ${call.size} classes \n\n"""
    s += cs
    s += s"\n\n"

    s
  }

}


text:
package com.pie.tlatoani.Core.Registration;

import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.ExpressionType;
import ch.njol.skript.lang.SkriptParser;
import ch.njol.skript.lang.util.SimpleExpression;
import ch.njol.util.Kleenean;
import org.bukkit.event.Event;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Tlatoani on 9/9/17.
 */
public class ExprEnumValues extends SimpleExpression<Object> {
    static final List<EnumClassInfo> enumClassInfos = new ArrayList<>();
    private static boolean registered = false;
    private static final ModifiableSyntaxElementInfo.Expression expressionInfo =
            new ModifiableSyntaxElementInfo.Expression(ExprEnumValues.class, Object.class, ExpressionType.SIMPLE);

    private EnumClassInfo enumClassInfo;

    static void addEnumClassInfo(EnumClassInfo enumClassInfo) {
        enumClassInfos.add(enumClassInfo);
        expressionInfo.addPattern("[all [of the]] " + enumClassInfo.getPluralCodeName());
        if (!registered) {
            expressionInfo.register();
            registered = true;
        }
    }

    @Override
    protected Object[] get(Event event) {
        return enumClassInfo.getAllValues();
    }

    @Override
    public boolean isSingle() {
        return false;
    }

    @Override
    public Class<? extends Object> getReturnType() {
        return enumClassInfo.getC();
    }

    @Override
    public String toString(Event event, boolean b) {
        return "all " + enumClassInfo.getPluralCodeName();
    }

    @Override
    public boolean init(Expression<?>[] expressions, int i, Kleenean kleenean, SkriptParser.ParseResult parseResult) {
        enumClassInfo = enumClassInfos.get(i);
        return true;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package nl.malienkolders.htm.lib

abstract class View
class EmptyView extends View
class PoolOverview extends View
class PoolRanking extends View
class FightView extends View


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:windowActionBar">false</item>
        <item name="android:windowNoTitle">true</item>
    </style>

    <style name="SplashTheme" parent="AppTheme">
        <item name="android:windowBackground">@drawable/background_splash</item>
        <item name="android:activityCloseExitAnimation">@null</item>
    </style>

</resources>


text:
{% macro entities_table(entities) %}
{% if entities|length == 0 %}

Keine Daten gefunden - und ich habe wirklich überall gesucht!

{% else %}
    {% set names = entities[0].__table__.columns.keys() %}

                {% for name in names %}
                {{ name }}
                {% endfor %}

        {% for entity in entities %}

                {% for name in names %}
                    {{ entity[name] }}
                {% endfor %}

        {% endfor %}

{% endif %}
{% endmacro %}


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [("scripts", "0012_auto_20190128_1820")]

    operations = [
        migrations.AlterField(
            model_name="scriptdb",
            name="db_typeclass_path",
            field=models.CharField(
                db_index=True,
                help_text="this defines what 'type' of entity this is. This variable holds a Python path to a module with a valid Evennia Typeclass.",
                max_length=255,
                null=True,
                verbose_name="typeclass",
            ),
        )
    ]


text:
package org.apache.accumulo.core.client.sample;

import static com.google.common.base.Preconditions.checkArgument;

import java.io.DataOutput;
import java.io.IOException;
import java.util.Map;
import java.util.Set;

import org.apache.accumulo.core.data.ByteSequence;
import org.apache.accumulo.core.data.Key;

/**
 * This sampler can hash any subset of a Key's fields. The fields that hashed for the sample are
 * determined by the configuration options passed in {@link #init(SamplerConfiguration)}. The
 * following key values are valid options.
 *
 *

 *
row=true|false
 *
family=true|false
 *
qualifier=true|false
 *
visibility=true|false
 *

 *
 *

 * If not specified in the options, fields default to false.
 *
 *

 * To determine what options are valid for hashing see {@link AbstractHashSampler}
 *
 *

 * To configure Accumulo to generate sample data on one thousandth of the column qualifiers, the
 * following SamplerConfiguration could be created and used to configure a table.
 *
 *

 *
 * new SamplerConfiguration(RowColumnSampler.class.getName()).setOptions(
 *   Map.of("hasher","murmur3_32","modulus","1009","qualifier","true"));
 *
 *

 *
 *

 * With this configuration, if a column qualifier is selected then all key values contains that
 * column qualifier will end up in the sample data.
 *
 * @since 1.8.0
 */
public class RowColumnSampler extends AbstractHashSampler {

  private boolean row = true;
  private boolean family = true;
  private boolean qualifier = true;
  private boolean visibility = true;

  private static final Set<String> VALID_OPTIONS =
      Set.of("row", "family", "qualifier", "visibility");

  private boolean hashField(SamplerConfiguration config, String field) {
    String optValue = config.getOptions().get(field);
    if (optValue != null) {
      return Boolean.parseBoolean(optValue);
    }

    return false;
  }

  @Override
  public void validateOptions(Map<String,String> config) {
    super.validateOptions(config);
    for (String option : config.keySet()) {
      checkArgument(VALID_OPTIONS.contains(option), "Unknown option : %s", option);
    }
  }

  @Override
  public void init(SamplerConfiguration config) {
    super.init(config);

    row = hashField(config, "row");
    family = hashField(config, "family");
    qualifier = hashField(config, "qualifier");
    visibility = hashField(config, "visibility");

    if (!row && !family && !qualifier && !visibility) {
      throw new IllegalStateException("Must hash at least one key field");
    }
  }

  private void putByteSequence(ByteSequence data, DataOutput hasher) throws IOException {
    hasher.write(data.getBackingArray(), data.offset(), data.length());
  }

  @Override
  protected void hash(DataOutput hasher, Key k) throws IOException {
    if (row) {
      putByteSequence(k.getRowData(), hasher);
    }

    if (family) {
      putByteSequence(k.getColumnFamilyData(), hasher);
    }

    if (qualifier) {
      putByteSequence(k.getColumnQualifierData(), hasher);
    }

    if (visibility) {
      putByteSequence(k.getColumnVisibilityData(), hasher);
    }
  }
}


text:
<?php

/**
 * Represents a template filter.
 *
 * Use Twig_SimpleFilter instead.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 *
 * @deprecated since 1.12 (to be removed in 2.0)
 */
abstract class Twig_Filter implements Twig_FilterInterface, Twig_FilterCallableInterface
{
    protected $options;
    protected $arguments = array();

    public function __construct(array $options = array())
    {
        $this->options = array_merge(array(
            'needs_environment' => false,
            'needs_context' => false,
            'pre_escape' => null,
            'preserves_safety' => null,
            'callable' => null,
        ), $options);
    }

    public function setArguments($arguments)
    {
        $this->arguments = $arguments;
    }

    public function getArguments()
    {
        return $this->arguments;
    }

    public function needsEnvironment()
    {
        return $this->options['needs_environment'];
    }

    public function needsContext()
    {
        return $this->options['needs_context'];
    }

    public function getSafe(Twig_Node $filterArgs)
    {
        if (isset($this->options['is_safe'])) {
            return $this->options['is_safe'];
        }

        if (isset($this->options['is_safe_callback'])) {
            return call_user_func($this->options['is_safe_callback'], $filterArgs);
        }
    }

    public function getPreservesSafety()
    {
        return $this->options['preserves_safety'];
    }

    public function getPreEscape()
    {
        return $this->options['pre_escape'];
    }

    public function getCallable()
    {
        return $this->options['callable'];
    }
}


text:
module ActsAsImageable
  # including this module into your Image model will give you finders and named scopes
  # useful for working with Images.
  # The named scopes are:
  #   in_order: Returns images in the order they were created (created_at ASC).
  #   recent: Returns images by how recently they were created (created_at DESC).
  #   limit(N): Return no more than N images.
  module Image
    def self.included(image_model)
      image_model.extend Finders
      image_model.scope :in_order, -> { image_model.order('created_at ASC') }
      image_model.scope :recent, -> { image_model.reorder('created_at DESC') }
    end

    def image_type?(type)
      type.to_s == role.singularize.to_s
    end

    module Finders
      # Helper class method to look up all images for
      # imageable class name and imageable id.
      def find_images_for_imageable(imageable_str, imageable_id)
        where(['imageable_type = ? and imageable_id = ? and role = ?', imageable_str, imageable_id, role]).order('created_at DESC')
      end

      # Helper class method to look up a imageable object
      # given the imageable class name and id
      def find_imageable(imageable_str, imageable_id)
        model = imageable_str.constantize
        model.respond_to?(:find_images_for) ? model.find(imageable_id) : nil
      end
    end
  end
end


text:
using namespace skland::graphic;

Test::Test()
    : testing::Test() {
}

Test::~Test() {

}

TEST_F(Test, enums_check_1) {

  // Compare Font::Weight and SkFontStyle::Weight
  ASSERT_TRUE((int) FontStyle::Weight::kWeightInvisible == (int) SkFontStyle::Weight::kInvisible_Weight);
  ASSERT_TRUE((int) FontStyle::Weight::kWeightThin == (int) SkFontStyle::Weight::kThin_Weight);
  ASSERT_TRUE((int) FontStyle::Weight::kWeightExtraLight == (int) SkFontStyle::Weight::kExtraLight_Weight);
  ASSERT_TRUE((int) FontStyle::Weight::kWeightLight == (int) SkFontStyle::Weight::kLight_Weight);
  ASSERT_TRUE((int) FontStyle::Weight::kWeightNormal == (int) SkFontStyle::Weight::kNormal_Weight);
  ASSERT_TRUE((int) FontStyle::Weight::kWeightMedium == (int) SkFontStyle::Weight::kMedium_Weight);
  ASSERT_TRUE((int) FontStyle::Weight::kWeightSemiBold == (int) SkFontStyle::Weight::kSemiBold_Weight);
  ASSERT_TRUE((int) FontStyle::Weight::kWeightBold == (int) SkFontStyle::Weight::kBold_Weight);
  ASSERT_TRUE((int) FontStyle::Weight::kWeightExtraBold == (int) SkFontStyle::Weight::kExtraBold_Weight);
  ASSERT_TRUE((int) FontStyle::Weight::kWeightBlack == (int) SkFontStyle::Weight::kBlack_Weight);
  ASSERT_TRUE((int) FontStyle::Weight::kWeightExtraBlack == (int) SkFontStyle::Weight::kExtraBlack_Weight);

  // Compare FontStyle::Width and SkFontStyle::Width
  ASSERT_TRUE((int) FontStyle::Width::kWidthUltraCondensed == (int) SkFontStyle::kUltraCondensed_Width);
  ASSERT_TRUE((int) FontStyle::Width::kWidthExtraCondensed == (int) SkFontStyle::kExtraCondensed_Width);
  ASSERT_TRUE((int) FontStyle::Width::kWidthCondensed == (int) SkFontStyle::kCondensed_Width);
  ASSERT_TRUE((int) FontStyle::Width::kWidthSemiCondensed == (int) SkFontStyle::kSemiCondensed_Width);
  ASSERT_TRUE((int) FontStyle::Width::kWidthNormal == (int) SkFontStyle::kNormal_Width);
  ASSERT_TRUE((int) FontStyle::Width::kWidthSemiExpanded == (int) SkFontStyle::kSemiExpanded_Width);
  ASSERT_TRUE((int) FontStyle::Width::kWidthExpanded == (int) SkFontStyle::kExpanded_Width);
  ASSERT_TRUE((int) FontStyle::Width::kWidthExtraExpanded == (int) SkFontStyle::kExtraExpanded_Width);
  ASSERT_TRUE((int) FontStyle::Width::kWidthUltraExpanded == (int) SkFontStyle::kUltraExpanded_Width);

  // Compare FontStyle::Slant and SkFontStyle::Slant
  ASSERT_TRUE((int) FontStyle::Slant::kSlantUpright == (int) SkFontStyle::kUpright_Slant);
  ASSERT_TRUE((int) FontStyle::Slant::kSlantItalic == (int) SkFontStyle::kItalic_Slant);
  ASSERT_TRUE((int) FontStyle::Slant::kSlantOblique == (int) SkFontStyle::kOblique_Slant);

}

TEST_F(Test, structure_1) {
  ASSERT_TRUE(sizeof(FontStyle) == sizeof(SkFontStyle));
}


text:
/**
 * @file Logic to calculate Hack coverage percentage of a source file.
 */

import * as vscode from "vscode";
import { LanguageClient } from "vscode-languageclient";
import { TypeCoverageResponse } from "./types/lsp";

export class HackCoverageChecker {
  // whether coverage errors are highlighted in code and visible in the "Problems" tab
  private visible: boolean = false;

  // the percentage coverage indicator in the status bar
  private coverageStatus: vscode.StatusBarItem;

  // the global coverage error collection
  private hhvmCoverDiag: vscode.DiagnosticCollection;

  // the global hack language client instance
  private languageClient: LanguageClient;

  constructor(languageClient: LanguageClient) {
    this.coverageStatus = vscode.window.createStatusBarItem(
      vscode.StatusBarAlignment.Left
    );
    this.hhvmCoverDiag = vscode.languages.createDiagnosticCollection(
      "hack_coverage"
    );
    this.languageClient = languageClient;
  }

  public async start(context: vscode.ExtensionContext) {
    context.subscriptions.push(
      vscode.workspace.onDidSaveTextDocument(async doc => this.check(doc))
    );
    context.subscriptions.push(
      vscode.window.onDidChangeActiveTextEditor(async editor => {
        if (editor) {
          await this.check(editor.document);
        } else {
          this.hhvmCoverDiag.clear();
          this.coverageStatus.hide();
        }
      })
    );
    context.subscriptions.push(
      vscode.commands.registerCommand(
        "hack.toggleCoverageHighlight",
        async () => this.toggle()
      )
    );
    context.subscriptions.push(this.hhvmCoverDiag, this.coverageStatus);

    // Check the active file, if any
    if (vscode.window.activeTextEditor) {
      await this.check(vscode.window.activeTextEditor.document);
    }
  }

  public async toggle() {
    if (this.visible) {
      this.hhvmCoverDiag.clear();
      this.visible = false;
    } else {
      this.visible = true;
      const editor = vscode.window.activeTextEditor;
      if (editor) {
        await this.check(editor.document);
      }
    }
  }

  private async check(document: vscode.TextDocument) {
    this.hhvmCoverDiag.clear();
    if (document.languageId !== "hack" || document.uri.scheme !== "file") {
      this.coverageStatus.hide();
      return;
    }

    let coverageResponse: TypeCoverageResponse;
    try {
      coverageResponse = await this.languageClient.sendRequest<
        TypeCoverageResponse
      >("textDocument/typeCoverage", {
        textDocument: this.languageClient.code2ProtocolConverter.asTextDocumentIdentifier(
          document
        )
      });
    } catch (e) {
      this.coverageStatus.hide();
      return;
    }

    this.coverageStatus.text = `$(paintcan)  ${coverageResponse.coveredPercent}%`;
    this.coverageStatus.tooltip = `This file is ${coverageResponse.coveredPercent}% covered by Hack.\nClick to toggle highlighting of uncovered areas.`;
    this.coverageStatus.command = "hack.toggleCoverageHighlight";
    this.coverageStatus.show();

    if (this.visible && coverageResponse.uncoveredRanges) {
      const diagnostics: vscode.Diagnostic[] = [];
      coverageResponse.uncoveredRanges.forEach(uncoveredRange => {
        const diagnostic = new vscode.Diagnostic(
          uncoveredRange.range,
          uncoveredRange.message || coverageResponse.defaultMessage,
          vscode.DiagnosticSeverity.Information
        );
        diagnostic.source = "Type Coverage";
        diagnostics.push(diagnostic);
      });
      this.hhvmCoverDiag.set(document.uri, diagnostics);
    }
  }
}


text:
namespace MatreshkaExpress.Domain.Migrations
{
    using System.CodeDom.Compiler;
    using System.Data.Entity.Migrations;
    using System.Data.Entity.Migrations.Infrastructure;
    using System.Resources;

    [GeneratedCode("EntityFramework.Migrations", "6.1.0-30225")]
    public sealed partial class InitialMigrate : IMigrationMetadata
    {
        private readonly ResourceManager Resources = new ResourceManager(typeof(InitialMigrate));

        string IMigrationMetadata.Id
        {
            get { return "201607101943354_InitialMigrate"; }
        }

        string IMigrationMetadata.Source
        {
            get { return null; }
        }

        string IMigrationMetadata.Target
        {
            get { return Resources.GetString("Target"); }
        }
    }
}


text:
class Error(Exception):
    # Base class exceptions
    def __init__(self, msg=''):
        self.message = msg
        Exception.__init__(self, self.message)

    def __repr__(self):
        return self.message

    __str__ = __repr__

class InvalidResponseError(Error):
    def __init__(self, url):
        self.message = 'invalid response, url: ' + url
        Error.__init__(self, self.message)

class InvalidInputTypeError(Error):
    def __init__(self, invalid_type):
        self.message = 'invalid input, type: ' + invalid_type
        Error.__init__(self, self.message)

class ParserTypeNotSupportError(Error):
    def __init__(self, not_support_type):
        self.message = 'parse type not support, type: ' + not_support_type
        Error.__init__(self, self.message)

class OuterIPError(Error):
    def __init__(self):
        self.message = 'fail to get out ip'
        Error.__init__(self, self.message)


text:
//
//  TFNavigator.h
//  TFNavigator
//
//  Created by Melvin on 3/31/16.
//  Copyright © 2016 TimeFace. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "UIWindow+TFNavigator.h"

///////////////////////////////////////////////////////////////////////////////////////////////////

static NSString *kOpenURLViewControllerIndexKey = @"OpenURLViewControllerIndex";///<替换某个viewcontroller的索引

UIViewController * TFOpenURL(NSString *URL ,NSDictionary *userInfo);
UIViewController * TFOpenStoryboardURL(NSString *URL , NSString * storyboardName ,NSDictionary *userInfo);

@class TFURLAction;

@interface TFNavigator : NSObject

+ (instancetype)sharedNavigator;
/**
 *  注册Controller
 *
 *  @param route
 *  @param controllerClass
 */
- (void)map:(NSString *)route toControllerClass:(Class)controllerClass;
/**
 *  注册app webview controller
 *
 *  @param route           路由
 *  @param controllerClass Class
 */
- (void)registeredWebViewController:(NSString *)route toControllerClass:(Class)controllerClass;

- (UIViewController *)openURLAction:(TFURLAction *)action;

- (UIViewController *)matchController:(NSString *)route;

- (UIViewController *)matchController:(NSString *)route userInfo:(NSDictionary *)userInfo;

- (UIViewController *)matchController:(NSString *)route storyboardName:(NSString *)storyboardName userInfo:(NSDictionary *)userInfo;

@end


text:
const { assert, skip, test, module: describe, only } = require('qunit');
const { GPU } = require('../../../../../../src');

describe('feature: to-string unsigned precision arguments Array(2)');

function testArgument(mode, context, canvas) {
  const gpu = new GPU({ mode });
  const originalKernel = gpu.createKernel(function(a) {
    return a;
  }, {
    canvas,
    context,
    output: [1],
    precision: 'unsigned',
    argumentTypes: { a: 'Array(2)' }
  });

  const a = new Float32Array([1, 2]);
  const expected = [new Float32Array([1,2])];
  const originalResult = originalKernel(a);
  assert.deepEqual(originalResult, expected);
  const kernelString = originalKernel.toString(a);
  const newKernel = new Function('return ' + kernelString)()({ context });
  const newResult = newKernel(a);
  assert.deepEqual(newResult, expected);

  const b = new Float32Array([2, 1]);
  const expected2 = [new Float32Array([2,1])];
  const newResult2 = newKernel(b);
  assert.deepEqual(newResult2, expected2);
  gpu.destroy();
}

(GPU.isWebGLSupported ? test : skip)('webgl', () => {
  const canvas = document.createElement('canvas');
  const context = canvas.getContext('webgl');
  testArgument('webgl', context, canvas);
});

(GPU.isWebGL2Supported ? test : skip)('webgl2', () => {
  const canvas = document.createElement('canvas');
  const context = canvas.getContext('webgl2');
  testArgument('webgl2', context, canvas);
});

(GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => {
  testArgument('headlessgl', require('gl')(1, 1), null);
});

test('cpu', () => {
  testArgument('cpu');
});


text:
package ua.com.javer.flowerexpert.dao;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import ua.com.javer.flowerexpert.entity.UserChoice;

import java.util.List;

@Repository("userChoiceDao") // TODO: do we need to specify "userChoiceDao"
public class UserChoiceDaoHibernate implements UserChoiceDao {

    private static final Logger DEBUG_LOGGER = Logger.getLogger(UserChoiceDaoHibernate.class);

    @Autowired
    private SessionFactory sessionFactory;

    public UserChoiceDaoHibernate() {
    }

	@Override
	public List<UserChoice> getAllUserChoices() {
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery("FROM UserChoice");
//        if( DEBUG_LOGGER.isDebugEnabled())
//            DEBUG_LOGGER.debug("UserChoiceDaoHibernate.getAllUserChoices() is executed: Returning query.list() = " + query.list());
       return  query.list();
    }

    @Override
    public void insertUserChoiceIntoDB(UserChoice userChoice) {
//        if( DEBUG_LOGGER.isDebugEnabled())
//            DEBUG_LOGGER.debug("UserChoiceDaoHibernate.insertUserChoiceIntoDB(userChoice) is executed: userChoice = " + userChoice);
        Session session = sessionFactory.getCurrentSession();
        session.save(userChoice);
    }
}


text:
package scutil.guid

import scala.scalajs.js.typedarray.*
import org.scalajs.dom.{ ByteString as _, * }

import scutil.lang.*

object Guid extends GuidBase {
	protected def randomBytes(size:Int):ByteString	= {
		val buffer	= new Int8Array(size)
		webcrypto getRandomValues buffer
		ByteString unsafeFromArray buffer.toArray
	}
}


text:
/* Google Font's Droid Sans */
@font-face {
  font-family: 'Droid Sans';
  font-style: normal;
  font-weight: 400;
  src: local('Droid Sans'), local('DroidSans'), url('/swagger/fonts/DroidSans.ttf') format('truetype');
}
/* Google Font's Droid Sans Bold */
@font-face {
  font-family: 'Droid Sans';
  font-style: normal;
  font-weight: 700;
  src: local('Droid Sans Bold'), local('DroidSans-Bold'), url('/swagger/fonts/DroidSans-Bold.ttf') format('truetype');
}


text:
<?php

namespace BackendBundle\Repository;

/**
 * WebsiteDataRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class WebsiteDataRepository extends \Doctrine\ORM\EntityRepository
{
    public function find($id, $lockMode = null, $lockVersion = null)
    {
        $qb = $this->createQueryBuilder('wd');
        $qb
            ->select('wd, i, sm')
            ->leftJoin('wd.logo', 'i')
            ->leftJoin('wd.socialMedias', 'sm')
        ;
        return $qb->getQuery()->getOneOrNullResult();
    }
}


text:
<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * J17JigsWeaponNames
 *
 * @ORM\Table(name="j17_jigs_weapon_names")
 * @ORM\Entity
 */
class J17JigsWeaponNames
{
    /**
     * @var string
     *
     * @ORM\Column(name="image", type="string", length=50, nullable=false)
     */
    private $image;

    /**
     * @var boolean
     *
     * @ORM\Column(name="max_ammunition", type="boolean", nullable=false)
     */
    private $maxAmmunition;

    /**
     * @var boolean
     *
     * @ORM\Column(name="attack", type="boolean", nullable=false)
     */
    private $attack;

    /**
     * @var boolean
     *
     * @ORM\Column(name="defence", type="boolean", nullable=false)
     */
    private $defence;

    /**
     * @var boolean
     *
     * @ORM\Column(name="precision", type="boolean", nullable=false)
     */
    private $precision;

    /**
     * @var boolean
     *
     * @ORM\Column(name="detente", type="boolean", nullable=false)
     */
    private $detente;

    /**
     * @var integer
     *
     * @ORM\Column(name="sell_price", type="integer", nullable=false)
     */
    private $sellPrice;

    /**
     * @var integer
     *
     * @ORM\Column(name="prix_munition", type="integer", nullable=false)
     */
    private $prixMunition;

    /**
     * @var string
     *
     * @ORM\Column(name="commentaire", type="text", nullable=false)
     */
    private $commentaire;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=20, nullable=false)
     */
    private $name;

    /**
     * @var integer
     *
     * @ORM\Column(name="idmagasin", type="integer", nullable=false)
     */
    private $idmagasin;

    /**
     * @var boolean
     *
     * @ORM\Column(name="nombre", type="boolean", nullable=false)
     */
    private $nombre;

    /**
     * @var integer
     *
     * @ORM\Column(name="xp", type="smallint", nullable=false)
     */
    private $xp;

    /**
     * @var boolean
     *
     * @ORM\Column(name="special", type="boolean", nullable=false)
     */
    private $special;

    /**
     * @var boolean
     *
     * @ORM\Column(name="published", type="boolean", nullable=false)
     */
    private $published;

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="smallint")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * Set image
     *
     * @param string $image
     * @return J17JigsWeaponNames
     */
    public function setImage($image)
    {
        $this->image = $image;

        return $this;
    }

    /**
     * Get image
     *
     * @return string
     */
    public function getImage()
    {
        return $this->image;
    }

    /**
     * Set maxAmmunition
     *
     * @param boolean $maxAmmunition
     * @return J17JigsWeaponNames
     */
    public function setMaxAmmunition($maxAmmunition)
    {
        $this->maxAmmunition = $maxAmmunition;

        return $this;
    }

    /**
     * Get maxAmmunition
     *
     * @return boolean
     */
    public function getMaxAmmunition()
    {
        return $this->maxAmmunition;
    }

    /**
     * Set attack
     *
     * @param boolean $attack
     * @return J17JigsWeaponNames
     */
    public function setAttack($attack)
    {
        $this->attack = $attack;

        return $this;
    }

    /**
     * Get attack
     *
     * @return boolean
     */
    public function getAttack()
    {
        return $this->attack;
    }

    /**
     * Set defence
     *
     * @param boolean $defence
     * @return J17JigsWeaponNames
     */
    public function setDefence($defence)
    {
        $this->defence = $defence;

        return $this;
    }

    /**
     * Get defence
     *
     * @return boolean
     */
    public function getDefence()
    {
        return $this->defence;
    }

    /**
     * Set precision
     *
     * @param boolean $precision
     * @return J17JigsWeaponNames
     */
    public function setPrecision($precision)
    {
        $this->precision = $precision;

        return $this;
    }

    /**
     * Get precision
     *
     * @return boolean
     */
    public function getPrecision()
    {
        return $this->precision;
    }

    /**
     * Set detente
     *
     * @param boolean $detente
     * @return J17JigsWeaponNames
     */
    public function setDetente($detente)
    {
        $this->detente = $detente;

        return $this;
    }

    /**
     * Get detente
     *
     * @return boolean
     */
    public function getDetente()
    {
        return $this->detente;
    }

    /**
     * Set sellPrice
     *
     * @param integer $sellPrice
     * @return J17JigsWeaponNames
     */
    public function setSellPrice($sellPrice)
    {
        $this->sellPrice = $sellPrice;

        return $this;
    }

    /**
     * Get sellPrice
     *
     * @return integer
     */
    public function getSellPrice()
    {
        return $this->sellPrice;
    }

    /**
     * Set prixMunition
     *
     * @param integer $prixMunition
     * @return J17JigsWeaponNames
     */
    public function setPrixMunition($prixMunition)
    {
        $this->prixMunition = $prixMunition;

        return $this;
    }

    /**
     * Get prixMunition
     *
     * @return integer
     */
    public function getPrixMunition()
    {
        return $this->prixMunition;
    }

    /**
     * Set commentaire
     *
     * @param string $commentaire
     * @return J17JigsWeaponNames
     */
    public function setCommentaire($commentaire)
    {
        $this->commentaire = $commentaire;

        return $this;
    }

    /**
     * Get commentaire
     *
     * @return string
     */
    public function getCommentaire()
    {
        return $this->commentaire;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return J17JigsWeaponNames
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set idmagasin
     *
     * @param integer $idmagasin
     * @return J17JigsWeaponNames
     */
    public function setIdmagasin($idmagasin)
    {
        $this->idmagasin = $idmagasin;

        return $this;
    }

    /**
     * Get idmagasin
     *
     * @return integer
     */
    public function getIdmagasin()
    {
        return $this->idmagasin;
    }

    /**
     * Set nombre
     *
     * @param boolean $nombre
     * @return J17JigsWeaponNames
     */
    public function setNombre($nombre)
    {
        $this->nombre = $nombre;

        return $this;
    }

    /**
     * Get nombre
     *
     * @return boolean
     */
    public function getNombre()
    {
        return $this->nombre;
    }

    /**
     * Set xp
     *
     * @param integer $xp
     * @return J17JigsWeaponNames
     */
    public function setXp($xp)
    {
        $this->xp = $xp;

        return $this;
    }

    /**
     * Get xp
     *
     * @return integer
     */
    public function getXp()
    {
        return $this->xp;
    }

    /**
     * Set special
     *
     * @param boolean $special
     * @return J17JigsWeaponNames
     */
    public function setSpecial($special)
    {
        $this->special = $special;

        return $this;
    }

    /**
     * Get special
     *
     * @return boolean
     */
    public function getSpecial()
    {
        return $this->special;
    }

    /**
     * Set published
     *
     * @param boolean $published
     * @return J17JigsWeaponNames
     */
    public function setPublished($published)
    {
        $this->published = $published;

        return $this;
    }

    /**
     * Get published
     *
     * @return boolean
     */
    public function getPublished()
    {
        return $this->published;
    }

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


text:
package org.jboss.netty.handler.codec.http;

import java.util.List;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.handler.codec.frame.TooLongFrameException;
import org.jboss.netty.handler.codec.replay.ReplayingDecoder;

/**
 * Decodes {@link ChannelBuffer}s into {@link HttpMessage}s and
 * {@link HttpChunk}s.
 *
 *
Parameters that prevents excessive memory consumption

 *

 *

 * Name	Meaning
 *

 *

 * {@code maxInitialLineLength}
 * The maximum length of the initial line
 *     (e.g. {@code "GET / HTTP/1.0"} or {@code "HTTP/1.0 200 OK"})
 *     If the length of the initial line exceeds this value, a
 *     {@link TooLongFrameException} will be raised.
 *

 *

 * {@code maxHeaderSize}
 * The maximum length of all headers.  If the sum of the length of each
 *     header exceeds this value, a {@link TooLongFrameException} will be raised.
 *

 *

 * {@code maxChunkSize}
 * The maximum length of the content or each chunk.  If the content length
 *     (or the length of each chunk) exceeds this value, the content or chunk
 *     will be split into multiple {@link HttpChunk}s whose length is
 *     {@code maxChunkSize} at maximum.
 *

 *

 *
 *
Chunked Content

 *
 * If the content of an HTTP message is greater than {@code maxChunkSize} or
 * the transfer encoding of the HTTP message is 'chunked', this decoder
 * generates one {@link HttpMessage} instance and its following
 * {@link HttpChunk}s per single HTTP message to avoid excessive memory
 * consumption. For example, the following HTTP message:
 *

 * GET / HTTP/1.1
 * Transfer-Encoding: chunked
 *
 * 1a
 * abcdefghijklmnopqrstuvwxyz
 * 10
 * 1234567890abcdef
 * 0
 * Content-MD5: ...
 * [blank line]
 *

 * triggers {@link HttpRequestDecoder} to generate 4 objects:
 *

 *
An {@link HttpRequest} whose {@link HttpMessage#isChunked() chunked}
 *     property is {@code true},

 *
The first {@link HttpChunk} whose content is {@code 'abcdefghijklmnopqrstuvwxyz'},

 *
The second {@link HttpChunk} whose content is {@code '1234567890abcdef'}, and

 *
An {@link HttpChunkTrailer} which marks the end of the content.

 *

 *
 * If you prefer not to handle {@link HttpChunk}s by yourself for your
 * convenience, insert {@link HttpChunkAggregator} after this decoder in the
 * {@link ChannelPipeline}.  However, please note that your server might not
 * be as memory efficient as without the aggregator.
 *
 *
Extensibility

 *
 * Please note that this decoder is designed to be extended to implement
 * a protocol derived from HTTP, such as
 * RTSP and
 * ICAP.
 * To implement the decoder of such a derived protocol, extend this class and
 * implement all abstract methods properly.
 *
 * @author The Netty Project
 * @author Andy Taylor (andy.taylor@jboss.org)
 * @author Trustin Lee
 * @version $Rev$, $Date$
 *
 * @apiviz.landmark
 */
public abstract class HttpMessageDecoder extends ReplayingDecoder<HttpMessageDecoder.State> {

    private final int maxInitialLineLength;
    private final int maxHeaderSize;
    private final int maxChunkSize;
    private HttpMessage message;
    private ChannelBuffer content;
    private long chunkSize;
    private int headerSize;

    /**
     * The internal state of {@link HttpMessageDecoder}.
     * Internal use only.
     *
     * @author The Netty Project
     * @author Trustin Lee
     * @version $Rev$, $Date$
     *
     * @apiviz.exclude
     */
    protected static enum State {
        SKIP_CONTROL_CHARS,
        READ_INITIAL,
        READ_HEADER,
        READ_VARIABLE_LENGTH_CONTENT,
        READ_VARIABLE_LENGTH_CONTENT_AS_CHUNKS,
        READ_FIXED_LENGTH_CONTENT,
        READ_FIXED_LENGTH_CONTENT_AS_CHUNKS,
        READ_CHUNK_SIZE,
        READ_CHUNKED_CONTENT,
        READ_CHUNKED_CONTENT_AS_CHUNKS,
        READ_CHUNK_DELIMITER,
        READ_CHUNK_FOOTER;
    }

    /**
     * Creates a new instance with the default
     * {@code maxInitialLineLength (4096}}, {@code maxHeaderSize (8192)}, and
     * {@code maxChunkSize (8192)}.
     */
    protected HttpMessageDecoder() {
        this(4096, 8192, 8192);
    }

    /**
     * Creates a new instance with the specified parameters.
     */
    protected HttpMessageDecoder(
            int maxInitialLineLength, int maxHeaderSize, int maxChunkSize) {

        super(State.SKIP_CONTROL_CHARS, true);

        if (maxInitialLineLength <= 0) {
            throw new IllegalArgumentException(
                    "maxInitialLineLength must be a positive integer: " +
                    maxInitialLineLength);
        }
        if (maxHeaderSize <= 0) {
            throw new IllegalArgumentException(
                    "maxHeaderSize must be a positive integer: " +
                    maxHeaderSize);
        }
        if (maxChunkSize < 0) {
            throw new IllegalArgumentException(
                    "maxChunkSize must be a positive integer: " +
                    maxChunkSize);
        }
        this.maxInitialLineLength = maxInitialLineLength;
        this.maxHeaderSize = maxHeaderSize;
        this.maxChunkSize = maxChunkSize;
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer, State state) throws Exception {
        switch (state) {
        case SKIP_CONTROL_CHARS: {
            try {
                skipControlCharacters(buffer);
                checkpoint(State.READ_INITIAL);
            } finally {
                checkpoint();
            }
        }
        case READ_INITIAL: {
            String[] initialLine = splitInitialLine(readLine(buffer, maxInitialLineLength));
            if (initialLine.length < 3) {
                // Invalid initial line - ignore.
                checkpoint(State.SKIP_CONTROL_CHARS);
                return null;
            }

            message = createMessage(initialLine);
            checkpoint(State.READ_HEADER);
        }
        case READ_HEADER: {
            State nextState = readHeaders(buffer);
            checkpoint(nextState);
            if (nextState == State.READ_CHUNK_SIZE) {
                // Chunked encoding
                message.setChunked(true);
                // Generate HttpMessage first.  HttpChunks will follow.
                return message;
            } else if (nextState == State.SKIP_CONTROL_CHARS) {
                // No content is expected.
                // Remove the headers which are not supposed to be present not
                // to confuse subsequent handlers.
                message.removeHeader(HttpHeaders.Names.TRANSFER_ENCODING);
                return message;
            } else {
                long contentLength = HttpHeaders.getContentLength(message, -1);
                if (contentLength == 0 || contentLength == -1 && isDecodingRequest()) {
                    content = ChannelBuffers.EMPTY_BUFFER;
                    return reset();
                }

                switch (nextState) {
                case READ_FIXED_LENGTH_CONTENT:
                    if (contentLength > maxChunkSize || HttpHeaders.is100ContinueExpected(message)) {
                        // Generate HttpMessage first.  HttpChunks will follow.
                        checkpoint(State.READ_FIXED_LENGTH_CONTENT_AS_CHUNKS);
                        message.setChunked(true);
                        // chunkSize will be decreased as the READ_FIXED_LENGTH_CONTENT_AS_CHUNKS
                        // state reads data chunk by chunk.
                        chunkSize = HttpHeaders.getContentLength(message, -1);
                        return message;
                    }
                    break;
                case READ_VARIABLE_LENGTH_CONTENT:
                    if (buffer.readableBytes() > maxChunkSize || HttpHeaders.is100ContinueExpected(message)) {
                        // Generate HttpMessage first.  HttpChunks will follow.
                        checkpoint(State.READ_VARIABLE_LENGTH_CONTENT_AS_CHUNKS);
                        message.setChunked(true);
                        return message;
                    }
                    break;
                default:
                    throw new IllegalStateException("Unexpected state: " + nextState);
                }
            }
            // We return null here, this forces decode to be called again where we will decode the content
            return null;
        }
        case READ_VARIABLE_LENGTH_CONTENT: {
            if (content == null) {
                content = ChannelBuffers.dynamicBuffer(channel.getConfig().getBufferFactory());
            }
            //this will cause a replay error until the channel is closed where this will read what's left in the buffer
            content.writeBytes(buffer.readBytes(buffer.readableBytes()));
            return reset();
        }
        case READ_VARIABLE_LENGTH_CONTENT_AS_CHUNKS: {
            // Keep reading data as a chunk until the end of connection is reached.
            int chunkSize = Math.min(maxChunkSize, buffer.readableBytes());
            HttpChunk chunk = new DefaultHttpChunk(buffer.readBytes(chunkSize));

            if (!buffer.readable()) {
                // Reached to the end of the connection.
                reset();
                if (!chunk.isLast()) {
                    // Append the last chunk.
                    return new Object[] { chunk, HttpChunk.LAST_CHUNK };
                }
            }
            return chunk;
        }
        case READ_FIXED_LENGTH_CONTENT: {
            //we have a content-length so we just read the correct number of bytes
            readFixedLengthContent(buffer);
            return reset();
        }
        case READ_FIXED_LENGTH_CONTENT_AS_CHUNKS: {
            long chunkSize = this.chunkSize;
            HttpChunk chunk;
            if (chunkSize > maxChunkSize) {
                chunk = new DefaultHttpChunk(buffer.readBytes(maxChunkSize));
                chunkSize -= maxChunkSize;
            } else {
                assert chunkSize <= Integer.MAX_VALUE;
                chunk = new DefaultHttpChunk(buffer.readBytes((int) chunkSize));
                chunkSize = 0;
            }
            this.chunkSize = chunkSize;

            if (chunkSize == 0) {
                // Read all content.
                reset();
                if (!chunk.isLast()) {
                    // Append the last chunk.
                    return new Object[] { chunk, HttpChunk.LAST_CHUNK };
                }
            }
            return chunk;
        }
        /**
         * everything else after this point takes care of reading chunked content. basically, read chunk size,
         * read chunk, read and ignore the CRLF and repeat until 0
         */
        case READ_CHUNK_SIZE: {
            String line = readLine(buffer, maxInitialLineLength);
            int chunkSize = getChunkSize(line);
            this.chunkSize = chunkSize;
            if (chunkSize == 0) {
                checkpoint(State.READ_CHUNK_FOOTER);
                return null;
            } else if (chunkSize > maxChunkSize) {
                // A chunk is too large. Split them into multiple chunks again.
                checkpoint(State.READ_CHUNKED_CONTENT_AS_CHUNKS);
            } else {
                checkpoint(State.READ_CHUNKED_CONTENT);
            }
        }
        case READ_CHUNKED_CONTENT: {
            assert chunkSize <= Integer.MAX_VALUE;
            HttpChunk chunk = new DefaultHttpChunk(buffer.readBytes((int) chunkSize));
            checkpoint(State.READ_CHUNK_DELIMITER);
            return chunk;
        }
        case READ_CHUNKED_CONTENT_AS_CHUNKS: {
            long chunkSize = this.chunkSize;
            HttpChunk chunk;
            if (chunkSize > maxChunkSize) {
                chunk = new DefaultHttpChunk(buffer.readBytes(maxChunkSize));
                chunkSize -= maxChunkSize;
            } else {
                assert chunkSize <= Integer.MAX_VALUE;
                chunk = new DefaultHttpChunk(buffer.readBytes((int) chunkSize));
                chunkSize = 0;
            }
            this.chunkSize = chunkSize;

            if (chunkSize == 0) {
                // Read all content.
                checkpoint(State.READ_CHUNK_DELIMITER);
            }

            if (!chunk.isLast()) {
                return chunk;
            }
        }
        case READ_CHUNK_DELIMITER: {
            for (;;) {
                byte next = buffer.readByte();
                if (next == HttpCodecUtil.CR) {
                    if (buffer.readByte() == HttpCodecUtil.LF) {
                        checkpoint(State.READ_CHUNK_SIZE);
                        return null;
                    }
                } else if (next == HttpCodecUtil.LF) {
                    checkpoint(State.READ_CHUNK_SIZE);
                    return null;
                }
            }
        }
        case READ_CHUNK_FOOTER: {
            HttpChunkTrailer trailer = readTrailingHeaders(buffer);
            if (maxChunkSize == 0) {
                // Chunked encoding disabled.
                return reset();
            } else {
                reset();
                // The last chunk, which is empty
                return trailer;
            }
        }
        default: {
            throw new Error("Shouldn't reach here.");
        }

        }
    }

    protected boolean isContentAlwaysEmpty(HttpMessage msg) {
        if (msg instanceof HttpResponse) {
            HttpResponse res = (HttpResponse) msg;
            int code = res.getStatus().getCode();
            if (code < 200) {
                return true;
            }
            switch (code) {
            case 204: case 205: case 304:
                return true;
            }
        }
        return false;
    }

    private Object reset() {
        HttpMessage message = this.message;
        ChannelBuffer content = this.content;

        if (content != null) {
            message.setContent(content);
            this.content = null;
        }
        this.message = null;

        checkpoint(State.SKIP_CONTROL_CHARS);
        return message;
    }

    private void skipControlCharacters(ChannelBuffer buffer) {
        for (;;) {
            char c = (char) buffer.readUnsignedByte();
            if (!Character.isISOControl(c) &&
                !Character.isWhitespace(c)) {
                buffer.readerIndex(buffer.readerIndex() - 1);
                break;
            }
        }
    }

    private void readFixedLengthContent(ChannelBuffer buffer) {
        long length = HttpHeaders.getContentLength(message, -1);
        assert length <= Integer.MAX_VALUE;

        if (content == null) {
            content = buffer.readBytes((int) length);
        } else {
            content.writeBytes(buffer.readBytes((int) length));
        }
    }

    private State readHeaders(ChannelBuffer buffer) throws TooLongFrameException {
        headerSize = 0;
        final HttpMessage message = this.message;
        String line = readHeader(buffer);
        String name = null;
        String value = null;
        if (line.length() != 0) {
            message.clearHeaders();
            do {
                char firstChar = line.charAt(0);
                if (name != null && (firstChar == ' ' || firstChar == '\t')) {
                    value = value + ' ' + line.trim();
                } else {
                    if (name != null) {
                        message.addHeader(name, value);
                    }
                    String[] header = splitHeader(line);
                    name = header[0];
                    value = header[1];
                }

                line = readHeader(buffer);
            } while (line.length() != 0);

            // Add the last header.
            if (name != null) {
                message.addHeader(name, value);
            }
        }

        State nextState;

        if (isContentAlwaysEmpty(message)) {
            nextState = State.SKIP_CONTROL_CHARS;
        } else if (message.isChunked()) {
            // HttpMessage.isChunked() returns true when either:
            // 1) HttpMessage.setChunked(true) was called or
            // 2) 'Transfer-Encoding' is 'chunked'.
            // Because this decoder did not call HttpMessage.setChunked(true)
            // yet, HttpMessage.isChunked() should return true only when
            // 'Transfer-Encoding' is 'chunked'.
            nextState = State.READ_CHUNK_SIZE;
        } else if (HttpHeaders.getContentLength(message, -1) >= 0) {
            nextState = State.READ_FIXED_LENGTH_CONTENT;
        } else {
            nextState = State.READ_VARIABLE_LENGTH_CONTENT;
        }
        return nextState;
    }

    private HttpChunkTrailer readTrailingHeaders(ChannelBuffer buffer) throws TooLongFrameException {
        headerSize = 0;
        String line = readHeader(buffer);
        String lastHeader = null;
        if (line.length() != 0) {
            HttpChunkTrailer trailer = new DefaultHttpChunkTrailer();
            do {
                char firstChar = line.charAt(0);
                if (lastHeader != null && (firstChar == ' ' || firstChar == '\t')) {
                    List<String> current = trailer.getHeaders(lastHeader);
                    if (current.size() != 0) {
                        int lastPos = current.size() - 1;
                        String newString = current.get(lastPos) + line.trim();
                        current.set(lastPos, newString);
                    } else {
                        // Content-Length, Transfer-Encoding, or Trailer
                    }
                } else {
                    String[] header = splitHeader(line);
                    String name = header[0];
                    if (!name.equalsIgnoreCase(HttpHeaders.Names.CONTENT_LENGTH) &&
                        !name.equalsIgnoreCase(HttpHeaders.Names.TRANSFER_ENCODING) &&
                        !name.equalsIgnoreCase(HttpHeaders.Names.TRAILER)) {
                        trailer.addHeader(name, header[1]);
                    }
                    lastHeader = name;
                }

                line = readHeader(buffer);
            } while (line.length() != 0);

            return trailer;
        }

        return HttpChunk.LAST_CHUNK;
    }

    private String readHeader(ChannelBuffer buffer) throws TooLongFrameException {
        StringBuilder sb = new StringBuilder(64);
        int headerSize = this.headerSize;

        loop:
        for (;;) {
            char nextByte = (char) buffer.readByte();
            headerSize ++;

            switch (nextByte) {
            case HttpCodecUtil.CR:
                nextByte = (char) buffer.readByte();
                headerSize ++;
                if (nextByte == HttpCodecUtil.LF) {
                    break loop;
                }
                break;
            case HttpCodecUtil.LF:
                break loop;
            }

            // Abort decoding if the header part is too large.
            if (headerSize >= maxHeaderSize) {
                // TODO: Respond with Bad Request and discard the traffic
                //    or close the connection.
                //       No need to notify the upstream handlers - just log.
                //       If decoding a response, just throw an exception.
                throw new TooLongFrameException(
                        "HTTP header is larger than " +
                        maxHeaderSize + " bytes.");

            }

            sb.append(nextByte);
        }

        this.headerSize = headerSize;
        return sb.toString();
    }

    protected abstract boolean isDecodingRequest();
    protected abstract HttpMessage createMessage(String[] initialLine) throws Exception;

    private int getChunkSize(String hex) {
        hex = hex.trim();
        for (int i = 0; i < hex.length(); i ++) {
            char c = hex.charAt(i);
            if (c == ';' || Character.isWhitespace(c) || Character.isISOControl(c)) {
                hex = hex.substring(0, i);
                break;
            }
        }

        return Integer.parseInt(hex, 16);
    }

    private String readLine(ChannelBuffer buffer, int maxLineLength) throws TooLongFrameException {
        StringBuilder sb = new StringBuilder(64);
        int lineLength = 0;
        while (true) {
            byte nextByte = buffer.readByte();
            if (nextByte == HttpCodecUtil.CR) {
                nextByte = buffer.readByte();
                if (nextByte == HttpCodecUtil.LF) {
                    return sb.toString();
                }
            }
            else if (nextByte == HttpCodecUtil.LF) {
                return sb.toString();
            }
            else {
                if (lineLength >= maxLineLength) {
                    // TODO: Respond with Bad Request and discard the traffic
                    //    or close the connection.
                    //       No need to notify the upstream handlers - just log.
                    //       If decoding a response, just throw an exception.
                    throw new TooLongFrameException(
                            "An HTTP line is larger than " + maxLineLength +
                            " bytes.");
                }
                lineLength ++;
                sb.append((char) nextByte);
            }
        }
    }

    private String[] splitInitialLine(String sb) {
        int aStart;
        int aEnd;
        int bStart;
        int bEnd;
        int cStart;
        int cEnd;

        aStart = findNonWhitespace(sb, 0);
        aEnd = findWhitespace(sb, aStart);

        bStart = findNonWhitespace(sb, aEnd);
        bEnd = findWhitespace(sb, bStart);

        cStart = findNonWhitespace(sb, bEnd);
        cEnd = findEndOfString(sb);

        return new String[] {
                sb.substring(aStart, aEnd),
                sb.substring(bStart, bEnd),
                cStart < cEnd? sb.substring(cStart, cEnd) : "" };
    }

    private String[] splitHeader(String sb) {
        final int length = sb.length();
        int nameStart;
        int nameEnd;
        int colonEnd;
        int valueStart;
        int valueEnd;

        nameStart = findNonWhitespace(sb, 0);
        for (nameEnd = nameStart; nameEnd < length; nameEnd ++) {
            char ch = sb.charAt(nameEnd);
            if (ch == ':' || Character.isWhitespace(ch)) {
                break;
            }
        }

        for (colonEnd = nameEnd; colonEnd < length; colonEnd ++) {
            if (sb.charAt(colonEnd) == ':') {
                colonEnd ++;
                break;
            }
        }

        valueStart = findNonWhitespace(sb, colonEnd);
        if (valueStart == length) {
            return new String[] {
                    sb.substring(nameStart, nameEnd),
                    ""
            };
        }

        valueEnd = findEndOfString(sb);
        return new String[] {
                sb.substring(nameStart, nameEnd),
                sb.substring(valueStart, valueEnd)
        };
    }

    private int findNonWhitespace(String sb, int offset) {
        int result;
        for (result = offset; result < sb.length(); result ++) {
            if (!Character.isWhitespace(sb.charAt(result))) {
                break;
            }
        }
        return result;
    }

    private int findWhitespace(String sb, int offset) {
        int result;
        for (result = offset; result < sb.length(); result ++) {
            if (Character.isWhitespace(sb.charAt(result))) {
                break;
            }
        }
        return result;
    }

    private int findEndOfString(String sb) {
        int result;
        for (result = sb.length(); result > 0; result --) {
            if (!Character.isWhitespace(sb.charAt(result - 1))) {
                break;
            }
        }
        return result;
    }
}


text:
* This Domain is for sale!! Welcome to contact me!!
* 这个域名在公开出售中, 欢迎联系!!

## Contact me

* email: <akagi201@gmail.com>

## official sites
* <http://openresty.org/>
* <https://github.com/openresty/lua-nginx-module>
* <https://github.com/iresty>

## videos
* <http://v.163.com/paike/V8H1BIE6U/V949ER8RD.html#from=search>

## web framework
* Vanilla: <https://idevz.gitbooks.io/vanilla-zh/content/>
* lapis: <http://leafo.net/lapis/>

## book
* <https://www.gitbook.com/book/moonbingbing/openresty-best-practices>
* <http://www.kancloud.cn/kancloud/openresty-best-practices>
* <http://chaos2openresty.readthedocs.org/zh_CN/latest/>

## wiki
* <https://github.com/iresty/nginx-lua-module-zh-wiki>
* <https://github.com/bungle/awesome-resty>

## tutorial
* <http://wiki.jikexueyuan.com/project/openresty-best-practice/>
* <http://wdicc.com/intro-openresty/>
* <http://chaos2.qiniudn.com/>
* <http://drops.wooyun.org/tips/6403>
* <http://huoding.com/2012/08/31/156>
* <http://wdicc.com/intro-openresty/>

## blogs
* <http://agentzh.org/>

## slides
* <http://agentzh.org/misc/slides/openresty-con-2015/#1>

## related awesomes
* awesome-lua: <https://github.com/LewisJEllis/awesome-lua>
* awesome-nginx: <https://github.com/agile6v/awesome-nginx>
* awesome-resty: <https://github.com/bungle/awesome-resty>


text:
<?php echo $nombre; ?>

                        <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-lg">Contacto</button>

                         Descargar

Ingeniero en informática

¿Quíen soy?

Hi, I am Bappy from Bangladesh.Adipiscing elit. Nullam dapibus vehicula condimentum. Curabitur elit enim, accumsan vitae tristique ut, mollis at orci. Fusce cursus interdum neque nec aliquam. Proin turpis leo, laoreet non ultricies non, dictum nec nulla. Duis vitae nisi eu odio Adipiscing elit. Nullam dapibus vehicula condimentum. Curabitur elit enim, accumsan.

Consectetur adipisicing elit. Hic labore, unde, ratione, itaque ducimus provident error similique qui, recusandae nam dignissimos autem. Sequi quas quis non, odit assumenda similique neque.

S. Quezada

Estudios

MSc in Design & Fine Art

Ideal Institute of Science and Technology

Studying all aspect of Graphic Design Including Advertising Design, Branding, Copy Exhibition Design, Ilustration, Information Design, Packaging Design and Website Design

2009-2011

BSc in Graphic Design

Ideal Institute of Science and Technology

Studying all aspect of Graphic Design Including Advertising Design, Branding, Copy Exhibition Design, Ilustration, Information Design, Packaging Design and Website Design

2006-2009

Diploma in Graphic Design

Ideal Institute of Science and Technology

Studying all aspect of Graphic Design Including Advertising Design, Branding, Copy Exhibition Design, Ilustration, Information Design, Packaging Design and Website Design

2003-2006

Experiencia Laboral

Lead Graphic Designer

Lifeview Media Ltd.

Adipiscing elit. Nullam dapibus vehicula condimentum. Curabitur elit enim, accumsan vitae tristique ut, mollis at orci. Fusce cursus interdum neque nec aliquam. Proin turpis leo, laoreet non ultricies non, dictum nec nulla.

2008 - present

Sr. Graphic Designer

Softech solution ltd.

Studying all aspect of Graphic Design Including Advertising Design, Branding, Copy Exhibition Design, Ilustration, Information Design, Packaging Design and Website Design

2006-2008

Jr. Graphic Designer

TwinTwin Design Solution

Studying all aspect of Graphic Design Including Advertising Design, Branding, Copy Exhibition Design, Ilustration, Information Design, Packaging Design and Website Design

2003-2006

Habilidades

PHP

	                    65% Complete (success)

JAVA

	                    85% Complete

C#

	                    60% Complete (warning)

Javascript

	                    30% Complete (danger)

Referencias

Sit amet, consectetur adipisicing elit. Fuga quidem ipsum maiores necessitatibus sint, porro temporibus labore, amet officia unde libero eligendi? Porro dolorum itaque, facere harum amet, rem libero.

Mushfiqul Islam

The UX Votch

Consectetur adipisicing elit. Fuga quidem ipsum maiores necessitatibus sint, porro temporibus labore, unde libero eligendi? Porro dolorum itaque, facere harum amet, rem libero.

E.A. Siblu

The Jatir Vobisshot

Fuga quidem ipsum maiores necessitatibus sint, porro temporibus labore, amet officia unde libero eligendi? Porro dolorum itaque, facere harum amet, rem libero.

Nasir Uddin

The Cute Huzur

	 		<form class="form-horizontal" role="form" method="post" action="<?php echo base_url("contacto/enviar"); ?>">

					Nombre

						<input type="text" class="form-control" id="name" name="name" placeholder="Sergio Quezada" value="">

					Email

						<input type="email" class="form-control" id="email" name="email" placeholder="ejemplo@domain.com" value="">

					Mensaje

						<textarea class="form-control" rows="4" name="message"></textarea>

					2 + 3 = ?

						<input type="text" class="form-control" id="human" name="human" placeholder="Respuesta">

						<input id="submit" name="submit" type="submit" value="Enviar" class="btn btn-primary">

						<! Will be used to display an alert to the user>

			</form>


text:
layout: post
status: publish
published: true
title: I Love Windows Phone
wordpress_id: 2261
wordpress_url: http://www.pedrolamas.com/?p=2261
date: 2011-12-02 18:42:24.000000000 +00:00
categories:
- Mobilidade
tags:
- Microsoft
- Windows Phone
- WP7
- Metro
- I Love Windows Phone
---
O Windows Phone ganhou um novo logótipo quando o "Mango" foi conhecido, algo que já tinha [antes reportado](2011/08/01/windows-phone-tem-novo-logotipo/).

Juntamente com este novo logótipo (simples, plano, monocromático, mais "Metro") apareceu uma imagem diferente do emblema "I Love Windows Phone"; a primeira vez que o vi foi num [artigo](http://www.wpcentral.com/windows-phone-mango-new-logo-goes-square) do [wpcentral](http://www.wpcentral.com/), com a imagem abaixo reproduzida.

[![](wp-content/uploads/2011/12/New-Windows-Phone-Mango-square-logo-gets-official-@-wpcentral-thumb.png "New Windows Phone Mango square logo gets official @ wpcentral")](wp-content/uploads/2011/12/New-Windows-Phone-Mango-square-logo-gets-official-@-wpcentral.png)

Quando vi esta imagem, tentei de várias formas encontrar a original na Internet, sempre sem grande sucesso!

Como parecia que ninguém conhece a origem deste emblema (nem a própria Microsoft, que cheguei até a contactar), tentei então vectorizar o mesmo, chegando ao resultado que podem ver se seguida.

![](wp-content/uploads/2011/12/ILWP.png "I Love Windows Phone")

É a cópia mais fiel que consegui fazer da foto do wpcentral, e que está agora aqui disponível para [download](wp-content/uploads/downloads/2011/12/ILWP.zip), nos formatos vectoriais PDF, SVG, Expression Design e num simples PNG transparente! :)

**Nota:** quem esteve presente no [Windows Phone Design Day](2011/10/07/windows-phone-design-day/) que decorreu em Outubro passado na Microsoft Portual, deve estar recordado de ter vindo para casa com uma t-shirt vermelha com este emblema em branco, certo? Pois então aqui tem a imagem original a partir da qual essas t-shirts foram criadas! ;)


text:
"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./ANTLRErrorListener"), exports);
__exportStar(require("./ANTLRErrorStrategy"), exports);
// export * from "./ANTLRFileStream";
__exportStar(require("./ANTLRInputStream"), exports);
__exportStar(require("./BailErrorStrategy"), exports);
__exportStar(require("./BufferedTokenStream"), exports);
__exportStar(require("./CharStream"), exports);
__exportStar(require("./CharStreams"), exports);
__exportStar(require("./CodePointBuffer"), exports);
__exportStar(require("./CodePointCharStream"), exports);
__exportStar(require("./CommonToken"), exports);
__exportStar(require("./CommonTokenFactory"), exports);
__exportStar(require("./CommonTokenStream"), exports);
__exportStar(require("./ConsoleErrorListener"), exports);
__exportStar(require("./DefaultErrorStrategy"), exports);
__exportStar(require("./Dependents"), exports);
__exportStar(require("./DiagnosticErrorListener"), exports);
__exportStar(require("./FailedPredicateException"), exports);
__exportStar(require("./InputMismatchException"), exports);
__exportStar(require("./InterpreterRuleContext"), exports);
__exportStar(require("./IntStream"), exports);
__exportStar(require("./Lexer"), exports);
__exportStar(require("./LexerInterpreter"), exports);
__exportStar(require("./LexerNoViableAltException"), exports);
__exportStar(require("./ListTokenSource"), exports);
__exportStar(require("./NoViableAltException"), exports);
__exportStar(require("./Parser"), exports);
__exportStar(require("./ParserErrorListener"), exports);
__exportStar(require("./ParserInterpreter"), exports);
__exportStar(require("./ParserRuleContext"), exports);
__exportStar(require("./ProxyErrorListener"), exports);
__exportStar(require("./ProxyParserErrorListener"), exports);
__exportStar(require("./RecognitionException"), exports);
__exportStar(require("./Recognizer"), exports);
__exportStar(require("./RuleContext"), exports);
__exportStar(require("./RuleContextWithAltNum"), exports);
__exportStar(require("./RuleDependency"), exports);
__exportStar(require("./RuleVersion"), exports);
__exportStar(require("./Token"), exports);
__exportStar(require("./TokenFactory"), exports);
__exportStar(require("./TokenSource"), exports);
__exportStar(require("./TokenStream"), exports);
__exportStar(require("./TokenStreamRewriter"), exports);
// export * from "./UnbufferedCharStream";
// export * from "./UnbufferedTokenStream";
__exportStar(require("./Vocabulary"), exports);
__exportStar(require("./VocabularyImpl"), exports);
__exportStar(require("./WritableToken"), exports);
//# sourceMappingURL=index.js.map