text:
package org.jhaws.common.pool;

public class PoolListenerAdapter<M> implements PoolListener<M> {
    @Override
    public void shutdown(Pool<M> pool) {
        //
    }

    @Override
    public void queued(Pool<M> pool, Job<M> job) {
        //
    }

    @Override
    public void started(Pool<M> pool, Job<M> job) {
        //
    }

    @Override
    public void ended(Pool<M> pool, Job<M> job) {
        //
    }
}


text:
Como Descobrir Quais Classes Existem no Java API?

Source: Head First: Java 2nd Ed.

redpajama_set_name: RedPajamaGithub


text:
MGR=./manage.py
PINST=pip install -r
WSGI=gunicorn

all: dev

deps:
	$(PINST) requirements.txt

dev-deps:
	$(PINST) dev.txt

db:
	$(MGR) migrate --noinput

provision: db build-static

dev: dev-deps provision
	$(MGR) runserver_plus 0.0.0.0:8080 --traceback $1

run: deps db
	$(WSGI) ato_children.wsgi $1

django-static:
	$(MGR) collectstatic --noinput

gulp-static:
	gulp build-prod

build-static: django-static gulp-static

run-front:
	gulp


text:
<?php

namespace Bundle\ConfigBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
 * Implementation of BundleInterface
 */
class ConfigBundle extends Bundle
{

}


text:
package org.apache.s2graph.core

import org.apache.s2graph.core.GraphExceptions.{InvalidHTableException, LabelAlreadyExistException, LabelNotExistException}
import org.apache.s2graph.core.Management.JsonModel.{Index, Prop}
import org.apache.s2graph.core.mysqls._
import org.apache.s2graph.core.types.HBaseType._
import org.apache.s2graph.core.types._
import play.api.libs.json.Reads._
import play.api.libs.json._

import scala.util.Try

/**
 * This is designed to be bridge between rest to s2core.
 * s2core never use this for finding models.
 */
object Management extends JSONParser {

  object JsonModel {

    case class Prop(name: String, defaultValue: String, datatType: String)

    object Prop extends ((String, String, String) => Prop)

    case class Index(name: String, propNames: Seq[String])

  }

  import HBaseType._

  val DefaultCompressionAlgorithm = "gz"

  def findService(serviceName: String) = {
    Service.findByName(serviceName, useCache = false)
  }

  def deleteService(serviceName: String) = {
    Service.findByName(serviceName).foreach { service =>
      //      service.deleteAll()
    }
  }

  def updateHTable(labelName: String, newHTableName: String): Try[Int] = Try {
    val targetLabel = Label.findByName(labelName).getOrElse(throw new LabelNotExistException(s"Target label $labelName does not exist."))
    if (targetLabel.hTableName == newHTableName) throw new InvalidHTableException(s"New HTable name is already in use for target label.")

    Label.updateHTableName(targetLabel.label, newHTableName)
  }

  def createServiceColumn(serviceName: String,
                          columnName: String,
                          columnType: String,
                          props: Seq[Prop],
                          schemaVersion: String = DEFAULT_VERSION) = {

    Model withTx { implicit session =>
      val serviceOpt = Service.findByName(serviceName)
      serviceOpt match {
        case None => throw new RuntimeException(s"create service $serviceName has not been created.")
        case Some(service) =>
          val serviceColumn = ServiceColumn.findOrInsert(service.id.get, columnName, Some(columnType), schemaVersion)
          for {
            Prop(propName, defaultValue, dataType) <- props
          } yield {
            ColumnMeta.findOrInsert(serviceColumn.id.get, propName, dataType)
          }
      }
    }
  }

  def deleteColumn(serviceName: String, columnName: String, schemaVersion: String = DEFAULT_VERSION) = {
    Model withTx { implicit session =>
      val service = Service.findByName(serviceName, useCache = false).getOrElse(throw new RuntimeException("Service not Found"))
      val serviceColumns = ServiceColumn.find(service.id.get, columnName, useCache = false)
      val columnNames = serviceColumns.map { serviceColumn =>
        ServiceColumn.delete(serviceColumn.id.get)
        serviceColumn.columnName
      }

      columnNames.getOrElse(throw new RuntimeException("column not found"))
    }
  }

  def findLabel(labelName: String): Option[Label] = {
    Label.findByName(labelName, useCache = false)
  }

  def deleteLabel(labelName: String) = {
    Model withTx { implicit session =>
      Label.findByName(labelName, useCache = false).foreach { label =>
        Label.deleteAll(label)
      }
      labelName
    }
  }

  def addIndex(labelStr: String, indices: Seq[Index]): Try[Label] = {
    Model withTx { implicit session =>
      val label = Label.findByName(labelStr).getOrElse(throw LabelNotExistException(s"$labelStr not found"))
      val labelMetaMap = label.metaPropsInvMap

      indices.foreach { index =>
        val metaSeq = index.propNames.map { name => labelMetaMap(name).seq }
        LabelIndex.findOrInsert(label.id.get, index.name, metaSeq.toList, "none")
      }

      label
    }
  }

  def addProp(labelStr: String, prop: Prop) = {
    Model withTx { implicit session =>
      val labelOpt = Label.findByName(labelStr)
      val label = labelOpt.getOrElse(throw LabelNotExistException(s"$labelStr not found"))

      LabelMeta.findOrInsert(label.id.get, prop.name, prop.defaultValue, prop.datatType)
    }
  }

  def addProps(labelStr: String, props: Seq[Prop]) = {
    Model withTx { implicit session =>
      val labelOpt = Label.findByName(labelStr)
      val label = labelOpt.getOrElse(throw LabelNotExistException(s"$labelStr not found"))

      props.map {
        case Prop(propName, defaultValue, dataType) =>
          LabelMeta.findOrInsert(label.id.get, propName, defaultValue, dataType)
      }
    }
  }

  def addVertexProp(serviceName: String,
                    columnName: String,
                    propsName: String,
                    propsType: String,
                    schemaVersion: String = DEFAULT_VERSION): ColumnMeta = {
    val result = for {
      service <- Service.findByName(serviceName, useCache = false)
      serviceColumn <- ServiceColumn.find(service.id.get, columnName)
    } yield {
        ColumnMeta.findOrInsert(serviceColumn.id.get, propsName, propsType)
      }
    result.getOrElse({
      throw new RuntimeException(s"add property on vertex failed")
    })
  }

  def getServiceLabel(label: String): Option[Label] = {
    Label.findByName(label, useCache = true)
  }

  /**
   *
   */

  def toLabelWithDirectionAndOp(label: Label, direction: String): Option[LabelWithDirection] = {
    for {
      labelId <- label.id
      dir = GraphUtil.toDirection(direction)
    } yield LabelWithDirection(labelId, dir)
  }

  def tryOption[A, R](key: A, f: A => Option[R]) = {
    f(key) match {
      case None => throw new GraphExceptions.InternalException(s"$key is not found in DB. create $key first.")
      case Some(r) => r
    }
  }

  def toEdge(ts: Long, operation: String, srcId: String, tgtId: String,
             labelStr: String, direction: String = "", props: String): Edge = {

    val label = tryOption(labelStr, getServiceLabel)
    val dir =
      if (direction == "")
//        GraphUtil.toDirection(label.direction)
        GraphUtil.directions("out")
      else
        GraphUtil.toDirection(direction)

    //    logger.debug(s"$srcId, ${label.srcColumnWithDir(dir)}")
    //    logger.debug(s"$tgtId, ${label.tgtColumnWithDir(dir)}")

    val srcVertexId = toInnerVal(srcId, label.srcColumn.columnType, label.schemaVersion)
    val tgtVertexId = toInnerVal(tgtId, label.tgtColumn.columnType, label.schemaVersion)

    val srcColId = label.srcColumn.id.get
    val tgtColId = label.tgtColumn.id.get
    val (srcVertex, tgtVertex) = if (dir == GraphUtil.directions("out")) {
      (Vertex(SourceVertexId(srcColId, srcVertexId), System.currentTimeMillis()),
        Vertex(TargetVertexId(tgtColId, tgtVertexId), System.currentTimeMillis()))
    } else {
      (Vertex(SourceVertexId(tgtColId, tgtVertexId), System.currentTimeMillis()),
        Vertex(TargetVertexId(srcColId, srcVertexId), System.currentTimeMillis()))
    }

    //    val dir = if (direction == "") GraphUtil.toDirection(label.direction) else GraphUtil.toDirection(direction)
    val labelWithDir = LabelWithDirection(label.id.get, dir)
    val op = tryOption(operation, GraphUtil.toOp)

    val jsObject = Json.parse(props).asOpt[JsObject].getOrElse(Json.obj())
    val parsedProps = toProps(label, jsObject.fields).toMap
    val propsWithTs = parsedProps.map(kv => (kv._1 -> InnerValLikeWithTs(kv._2, ts))) ++
      Map(LabelMeta.timeStampSeq -> InnerValLikeWithTs(InnerVal.withLong(ts, label.schemaVersion), ts))

    Edge(srcVertex, tgtVertex, labelWithDir, op, version = ts, propsWithTs = propsWithTs)

  }

  def toVertex(ts: Long, operation: String, id: String, serviceName: String, columnName: String, props: String): Vertex = {
    Service.findByName(serviceName) match {
      case None => throw new RuntimeException(s"$serviceName does not exist. create service first.")
      case Some(service) =>
        ServiceColumn.find(service.id.get, columnName) match {
          case None => throw new RuntimeException(s"$columnName is not exist. create service column first.")
          case Some(col) =>
            val idVal = toInnerVal(id, col.columnType, col.schemaVersion)
            val op = tryOption(operation, GraphUtil.toOp)
            val jsObject = Json.parse(props).asOpt[JsObject].getOrElse(Json.obj())
            val parsedProps = toProps(col, jsObject).toMap
            Vertex(VertexId(col.id.get, idVal), ts, parsedProps, op = op)
        }
    }
  }

  def toProps(column: ServiceColumn, js: JsObject): Seq[(Int, InnerValLike)] = {

    val props = for {
      (k, v) <- js.fields
      meta <- column.metasInvMap.get(k)
    } yield {
        val innerVal = jsValueToInnerVal(v, meta.dataType, column.schemaVersion).getOrElse(
          throw new RuntimeException(s"$k is not defined. create schema for vertex."))

        (meta.seq.toInt, innerVal)
      }
    props

  }

  def toProps(label: Label, js: Seq[(String, JsValue)]): Seq[(Byte, InnerValLike)] = {
    val props = for {
      (k, v) <- js
      meta <- label.metaPropsInvMap.get(k)
      innerVal <- jsValueToInnerVal(v, meta.dataType, label.schemaVersion)
    } yield (meta.seq, innerVal)

    props
  }

  /**
   * update label name.
   */
  def updateLabelName(oldLabelName: String, newLabelName: String) = {
    Model withTx { implicit session =>
      for {
        old <- Label.findByName(oldLabelName, useCache = false)
      } {
        Label.findByName(newLabelName, useCache = false) match {
          case None =>
            Label.updateName(oldLabelName, newLabelName)
          case Some(_) =>
            throw new RuntimeException(s"$newLabelName already exist")
        }
      }
    }
  }

  /**
   * swap label names.
   */
  def swapLabelNames(leftLabel: String, rightLabel: String) = {
    Model withTx { implicit session =>
      val tempLabel = "_" + leftLabel + "_"
      Label.updateName(leftLabel, tempLabel)
      Label.updateName(rightLabel, leftLabel)
      Label.updateName(tempLabel, rightLabel)
    }
  }
}

class Management(graph: Graph) {
  import Management._
  val storage = graph.storage

  def createTable(zkAddr: String,
                  tableName: String,
                  cfs: List[String],
                  regionMultiplier: Int,
                  ttl: Option[Int],
                  compressionAlgorithm: String = DefaultCompressionAlgorithm): Unit =
    storage.createTable(zkAddr, tableName, cfs, regionMultiplier, ttl, compressionAlgorithm)

  /** HBase specific code */
  def createService(serviceName: String,
                    cluster: String, hTableName: String,
                    preSplitSize: Int, hTableTTL: Option[Int],
                    compressionAlgorithm: String = DefaultCompressionAlgorithm): Try[Service] = {

    Model withTx { implicit session =>
      val service = Service.findOrInsert(serviceName, cluster, hTableName, preSplitSize, hTableTTL, compressionAlgorithm)
      /* create hbase table for service */
      storage.createTable(cluster, hTableName, List("e", "v"), preSplitSize, hTableTTL, compressionAlgorithm)
      service
    }
  }

  /** HBase specific code */
  def createLabel(label: String,
                  srcServiceName: String,
                  srcColumnName: String,
                  srcColumnType: String,
                  tgtServiceName: String,
                  tgtColumnName: String,
                  tgtColumnType: String,
                  isDirected: Boolean = true,
                  serviceName: String,
                  indices: Seq[Index],
                  props: Seq[Prop],
                  consistencyLevel: String,
                  hTableName: Option[String],
                  hTableTTL: Option[Int],
                  schemaVersion: String = DEFAULT_VERSION,
                  isAsync: Boolean,
                  compressionAlgorithm: String = "gz"): Try[Label] = {

    val labelOpt = Label.findByName(label, useCache = false)

    Model withTx { implicit session =>
      labelOpt match {
        case Some(l) =>
          throw new GraphExceptions.LabelAlreadyExistException(s"Label name ${l.label} already exist.")
        case None =>
          /* create all models */
          val newLabel = Label.insertAll(label,
            srcServiceName, srcColumnName, srcColumnType,
            tgtServiceName, tgtColumnName, tgtColumnType,
            isDirected, serviceName, indices, props, consistencyLevel,
            hTableName, hTableTTL, schemaVersion, isAsync, compressionAlgorithm)

          /* create hbase table */
          val service = newLabel.service
          (hTableName, hTableTTL) match {
            case (None, None) => // do nothing
            case (None, Some(hbaseTableTTL)) => throw new RuntimeException("if want to specify ttl, give hbaseTableName also")
            case (Some(hbaseTableName), None) =>
              // create own hbase table with default ttl on service level.
              storage.createTable(service.cluster, hbaseTableName, List("e", "v"), service.preSplitSize, service.hTableTTL, compressionAlgorithm)
            case (Some(hbaseTableName), Some(hbaseTableTTL)) =>
              // create own hbase table with own ttl.
              storage.createTable(service.cluster, hbaseTableName, List("e", "v"), service.preSplitSize, hTableTTL, compressionAlgorithm)
          }
          newLabel
      }
    }
  }

  /**
   * label
   */
  /**
   * copy label when if oldLabel exist and newLabel do not exist.
   * copy label: only used by bulk load job. not sure if we need to parameterize hbase cluster.
   */
  def copyLabel(oldLabelName: String, newLabelName: String, hTableName: Option[String]) = {
    val old = Label.findByName(oldLabelName).getOrElse(throw new LabelAlreadyExistException(s"Old label $oldLabelName not exists."))
    if (Label.findByName(newLabelName).isDefined) throw new LabelAlreadyExistException(s"New label $newLabelName already exists.")

    val allProps = old.metas.map { labelMeta => Prop(labelMeta.name, labelMeta.defaultValue, labelMeta.dataType) }
    val allIndices = old.indices.map { index => Index(index.name, index.propNames) }

    createLabel(newLabelName, old.srcService.serviceName, old.srcColumnName, old.srcColumnType,
      old.tgtService.serviceName, old.tgtColumnName, old.tgtColumnType,
      old.isDirected, old.serviceName,
      allIndices, allProps,
      old.consistencyLevel, hTableName, old.hTableTTL, old.schemaVersion, old.isAsync, old.compressionAlgorithm)
  }
}


text:
<?php
namespace Sandstorm\UserManagement\Domain\Service\Flow;

use Sandstorm\UserManagement\Domain\Model\RegistrationFlow;
use Sandstorm\UserManagement\Domain\Repository\UserRepository;
use Sandstorm\UserManagement\Domain\Service\UserCreationServiceInterface;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Persistence\PersistenceManagerInterface;
use Neos\Flow\Security\Account;
use Neos\Flow\Security\Policy\Role;
use Sandstorm\UserManagement\Domain\Model\User;

/**
 * @Flow\Scope("singleton")
 */
class FlowUserCreationService implements UserCreationServiceInterface
{

    /**
     * @Flow\Inject
     * @var PersistenceManagerInterface
     */
    protected $persistenceManager;

    /**
     * @Flow\Inject
     * @var UserRepository
     */
    protected $userRepository;

    /**
     * @Flow\InjectConfiguration(path="rolesForNewUsers")
     */
    protected $rolesForNewUsers;

    /**
     * In this method, actually create the user / account.
     *
     * NOTE: After this method is called, the $registrationFlow is DESTROYED, so you need to store all attributes
     * in your object as you need them.
     *
     * @param RegistrationFlow $registrationFlow
     * @return User
     */
    public function createUserAndAccount(RegistrationFlow $registrationFlow)
    {
        // Create the account
        $account = new Account();
        $account->setAccountIdentifier($registrationFlow->getEmail());
        $account->setCredentialsSource($registrationFlow->getEncryptedPassword());
        $account->setAuthenticationProviderName('Sandstorm.UserManagement:Login');

        // Assign pre-configured roles
        foreach ($this->rolesForNewUsers as $roleString) {
            $account->addRole(new Role($roleString));
        }

        // Create the user
        $user = new User();
        $user->setAccount($account);
        $user->setEmail($registrationFlow->getEmail());
        if (array_key_exists('salutation', $registrationFlow->getAttributes())) {
            $user->setGender($registrationFlow->getAttributes()['salutation']);
        }
        if (array_key_exists('firstName', $registrationFlow->getAttributes())) {
            $user->setFirstName($registrationFlow->getAttributes()['firstName']);
        }
        if (array_key_exists('lastName', $registrationFlow->getAttributes())) {
            $user->setLastName($registrationFlow->getAttributes()['lastName']);
        }

        // Persist user
        $this->userRepository->add($user);
        $this->persistenceManager->allowObject($user);
        $this->persistenceManager->allowObject($account);

        // Return the user so the controller can directly use it
        return $user;
    }
}


text:
@interface PodsDummy_Pods_Accented : NSObject
@end
@implementation PodsDummy_Pods_Accented
@end


text:
    Leave picback with pictures you like
    <input id="search-phrase" name="searchPhrase" ng-model="searchPhrase" ng-change="changeSearchPhrase(searchPhrase)" type="text" class="form-control" />


text:
require 'config_test'

module ChapterFour
  class TestOne < Minitest::Test

    class DataStructures::BinarySearchTreeMap
      include One
    end

    def setup
      @tree = DataStructures::BinarySearchTreeMap.new
    end

    def test_returns_true_if_tree_is_balanced
      @tree.put(:c, 3)
      @tree.put(:a, 1)
      @tree.put(:b, 2)
      @tree.put(:d, 4)

      assert @tree.balanced?
    end

    def test_returns_false_if_tree_is_not_balanced
      @tree.put(:b, 2)
      @tree.put(:a, 1)
      @tree.put(:c, 3)
      @tree.put(:d, 4)
      @tree.put(:e, 5)

      refute @tree.balanced?
    end

    def test_returns_true_if_empty
      assert @tree.balanced?
    end

  end
end


text:
<?php

namespace App\Presenters;

use Nette;

/**
 * Homepage presenter.
 */
class HomepagePresenter extends BasePresenter
{

	public function renderDefault()
	{
		$this->setTheme('Default');
	}

}


text:
#ifndef vnsw_agent_vrf_assign_kstate_h
#define vnsw_agent_vrf_assign_kstate_h

class VrfAssignKState: public KState {
public:
    VrfAssignKState(KVrfAssignResp *obj, const std::string &resp_ctx,
                    vr_vrf_assign_req &req, int id);
    virtual void SendResponse();
    virtual void Handler();
    virtual void SendNextRequest();
};

struct VrfAssignContext {
    uint32_t vif_index_;
    int      marker_;
};

#endif //vnsw_agent_vrf_assign_kstate_h


text:
/*	$NetBSD: SYS.h,v 1.12 2012/02/27 12:26:21 joerg Exp $ */
/*
 * Copyright (c) 1983, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)SYS.h	8.1 (Berkeley) 6/4/93
 */

#include <machine/asm.h>
#include <sys/syscall.h>

#define	CERROR	_C_LABEL(__cerror)
#define	CURBRK	_C_LABEL(__curbrk)

#ifdef __STDC__
#define SYSTRAP(x)	chmk $ SYS_ ## x
#else
#define SYSTRAP(x)	chmk $ SYS_/**/x
#endif

#define _SYSCALL_NOERROR(x,y)						\
	ENTRY(x,0);							\
	SYSTRAP(y)

#define _SYSCALL(x,y)							\
	.p2align 2;							\
	err: nop; nop; jmp CERROR+2;					\
	_SYSCALL_NOERROR(x,y);						\
	jcs err+2

#define SYSCALL_NOERROR(x)						\
	_SYSCALL_NOERROR(x,x)

#define SYSCALL(x)							\
	_SYSCALL(x,x)

#define PSEUDO_NOERROR(x,y)						\
	_SYSCALL_NOERROR(x,y);						\
	ret;								\
	END(x)

#define PSEUDO(x,y)							\
	_SYSCALL(x,y);							\
	ret;								\
	END(x)

#define RSYSCALL_NOERROR(x)						\
	PSEUDO_NOERROR(x,x)

#define RSYSCALL(x)							\
	PSEUDO(x,x)

#ifdef WEAK_ALIAS
#define	WSYSCALL(weak,strong)						\
	WEAK_ALIAS(weak,strong);					\
	PSEUDO(strong,weak)
#else
#define	WSYSCALL(weak,strong)						\
	PSEUDO(weak,weak)
#endif

#define	ASMSTR		.asciz

	.protected	CERROR
	.globl	CERROR


text:
package PaymentSplitItemObj;

use strict;
use DeQuote;

sub new {
    my ($class, %args) = @_;

    my $self = {
        _itemID           => $args{itemID},
        _splitID          => $args{splitID},
        _levelID          => $args{levelID},
        _otherBankCode    => $args{otherBankCode},
        _otherAccountNo   => $args{otherAccountNo},
        _otherAccountName => $args{otherAccountName},
        _amount           => $args{amount},
        _factor           => $args{factor},
        _remainder        => $args{remainder},
        _mpEmail          => $args{mpEmail}
    };

    $self = bless ($self, $class);

    return $self;
}

###############################################################################
# Getters
###############################################################################

sub getItemID {
    my ($self) = shift;
    return $self->{_itemID};
}

sub getSplitID {
    my ($self) = shift;
    return $self->{_splitID};
}

sub getLevelID {
    my ($self) = shift;
    return $self->{_levelID};
}

sub getOtherBankCode {
    my ($self) = shift;
    return $self->{_otherBankCode};
}

sub getOtherAccountNo {
    my ($self) = shift;
    return $self->{_otherAccountNo};
}

sub getOtherAccountName {
    my ($self) = shift;
    return $self->{_otherAccountName};
}

sub getAmount {
    my ($self) = shift;
    return $self->{_amount};
}

sub getFactor {
    my ($self) = shift;
    return $self->{_factor};
}

sub getRemainder {
    my ($self) = shift;
    return $self->{_remainder};
}

sub getMPEmail {
    my ($self) = shift;
    return $self->{_mpEmail};
}

sub getList {
    my ($self, $splitID, $dbh) = @_;
    my $where   = qq[intSplitID = $splitID];
    my $orderBy = qq[ORDER BY intItemID];
    return _processQuery($where, $orderBy, $dbh);
}

###############################################################################
# Setters
###############################################################################

sub setSplitID {
    my ($self, $splitID) = @_;
    $self->{_splitID} = $splitID if defined $splitID;
}

sub setLevelID {
    my ($self, $levelID) = @_;
    $self->{_levelID} = $levelID if defined $levelID;
}

sub setOtherBankCode {
    my ($self, $otherBankCode) = @_;
    $self->{_otherBankCode} = $otherBankCode if defined $otherBankCode;
}

sub setOtherAccountNo {
    my ($self, $otherAccountNo) = @_;
    $self->{_otherAccountNo} = $otherAccountNo if defined $otherAccountNo;
}

sub setOtherAccountName {
    my ($self, $otherAccountName) = @_;
    $self->{_otherAccountName} = $otherAccountName if defined $otherAccountName;
}

sub setAmount {
    my ($self, $amount) = @_;
    $self->{_amount} = $amount if defined $amount;
}

sub setFactor {
    my ($self, $factor) = @_;
    $self->{_factor} = $factor if defined $factor;
}

sub setRemainder {
    my ($self, $remainder) = @_;
    $self->{_remainder} = $remainder if defined $remainder;
}

sub setMPEmail {
    my ($self, $mpEmail) = @_;
    $self->{_mpEmail} = $mpEmail if defined $mpEmail;
}

###############################################################################
# Persistence
###############################################################################

sub load {
    my ($self, $itemID, $dbh) = @_;

    my $where   = qq[intItemID = $itemID];
    my $orderBy = '';
    my $dref    = _processQuery($where, $orderBy, $dbh);

    my $paymentSplitItem = @{$dref}[0];

    return ($paymentSplitItem)
        ? $self->new(
            itemID           => $paymentSplitItem->{'intItemID'},
            splitID          => $paymentSplitItem->{'intSplitID'},
            levelID          => $paymentSplitItem->{'intLevelID'},
            otherBankCode    => $paymentSplitItem->{'strOtherBankCode'},
            otherAccountNo   => $paymentSplitItem->{'strOtherAccountNo'},
            otherAccountName => $paymentSplitItem->{'strOtherAccountName'},
            amount           => $paymentSplitItem->{'curAmount'},
            factor           => $paymentSplitItem->{'dblFactor'},
            remainder        => $paymentSplitItem->{'intRemainder'},
            mpEmail          => $paymentSplitItem->{'strMPEmail'}
          )
        : '';
}

sub delete {
    my ($self, $splitID, $dbh) = @_;

    my $sql = qq[
        DELETE FROM tblPaymentSplitItem
        WHERE intSplitID=$splitID
    ];

    my $query = $dbh->prepare($sql);
    $query->execute;

}

sub save {
    my ($self, $dbh) = @_;

    my $itemID            = $self->getItemID;
    my $splitID           = $self->getSplitID;
    my $levelID           = $self->getLevelID;
    my $otherBankCode     = $self->getOtherBankCode;
    my $otherAccountNo    = $self->getOtherAccountNo;
    my $otherAccountName  = $self->getOtherAccountName;
    my $amount            = $self->getAmount;
    my $factor            = $self->getFactor;
    my $remainder         = $self->getRemainder;
    my $mpEmail           = $self->getMPEmail;

    my $sql = '';

    #deQuote($dbh, \$otherBankCode);
    #deQuote($dbh, \$otherAccountNo);
    #deQuote($dbh, \$otherAccountName);
    deQuote($dbh, \$mpEmail);

    if ($itemID) {
        $sql = qq[
            UPDATE tblPaymentSplitItem
            SET intSplitID=$splitID,
                intLevelID=$levelID,
                strOtherBankCode=?,
                strOtherAccountNo=?,
                strOtherAccountName=?,
                curAmount=$amount,
                dblFactor=$factor,
                intRemainder=$remainder,
                strMPEmail=$mpEmail
            WHERE intItemID=$itemID
        ];
    }
    else {
        $sql = qq[
            INSERT INTO tblPaymentSplitItem (
                intSplitID, intLevelID, strOtherBankCode, strOtherAccountNo,
                strOtherAccountName, curAmount, dblFactor, intRemainder, strMPEmail
            )
            VALUES (
                $splitID, $levelID, ?, ?, ?, $amount, $factor, $remainder, $mpEmail
            )
        ];
    }

    my $query = $dbh->prepare($sql);
    $query->execute($otherBankCode, $otherAccountNo, $otherAccountName);

    if (!$itemID) {
        $itemID = $query->{'mysql_insertid'}
    }

    $query->finish();

    return $itemID;
}

###############################################################################
# Privates
###############################################################################

sub _processQuery {
    my ($where, $orderBy, $dbh) = @_;

    my $sql = qq[
        SELECT *
        FROM tblPaymentSplitItem
        WHERE $where
        $orderBy
    ];
    my $query = $dbh->prepare($sql);
    my @paymentSplitItems = ();

    $query->execute;

    while (my $dref = $query->fetchrow_hashref()) {
        push @paymentSplitItems, $dref;
    }

    $query->finish();

    return \@paymentSplitItems;
}

1;


text:
#import "UIToolbar.h"
#import "UIBarButtonItem.h"
#import "UIToolbarButton.h"
#import "UIColor.h"
#import "UIGraphics.h"

@interface UIToolbarItem : NSObject {
    UIBarButtonItem *item;
    UIView *view;
}

- (id)initWithBarButtonItem:(UIBarButtonItem *)anItem;

@property (nonatomic, readonly) UIView *view;
@property (nonatomic, readonly) UIBarButtonItem *item;
@property (nonatomic, readonly) CGFloat width;

@end

@implementation UIToolbarItem
@synthesize item, view;

- (id)initWithBarButtonItem:(UIBarButtonItem *)anItem
{
    if ((self=[super init])) {
        NSAssert((anItem != nil), @"the bar button item must not be nil");

        item = [anItem retain];

        if (!item->_isSystemItem && item.customView) {
            view = [item.customView retain];
        } else if (!item->_isSystemItem || (item->_systemItem != UIBarButtonSystemItemFixedSpace && item->_systemItem != UIBarButtonSystemItemFlexibleSpace)) {
            view = [[UIToolbarButton alloc] initWithBarButtonItem:item];
        }
    }
    return self;
}

- (void)dealloc
{
    [item release];
    [view release];
    [super dealloc];
}

- (CGFloat)width
{
    if (view) {
        return view.frame.size.width;
    } else if (item->_isSystemItem && item->_systemItem == UIBarButtonSystemItemFixedSpace) {
        return item.width;
    } else {
        return -1;
    }
}

@end

@implementation UIToolbar
@synthesize barStyle=_barStyle, tintColor=_tintColor, translucent=_translucent;

- (id)init
{
    return [self initWithFrame:CGRectMake(0,0,320,32)];
}

- (id)initWithFrame:(CGRect)frame
{
    if ((self=[super initWithFrame:frame])) {
        _toolbarItems = [[NSMutableArray alloc] init];
        self.barStyle = UIBarStyleDefault;
        self.translucent = NO;
        self.tintColor = nil;
    }
    return self;
}

- (void)dealloc
{
    [_tintColor release];
    [_toolbarItems release];
    [super dealloc];
}

- (void)setBarStyle:(UIBarStyle)newStyle
{
    _barStyle = newStyle;

    // this is for backward compatibility - UIBarStyleBlackTranslucent is deprecated
    if (_barStyle == UIBarStyleBlackTranslucent) {
        self.translucent = YES;
    }
}

/*
- (void)_updateItemViews
{
    [_itemViews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [_itemViews removeAllObjects];

    NSUInteger numberOfFlexibleItems = 0;

    for (UIBarButtonItem *item in _items) {
        if ((item->_isSystemItem) && (item->_systemItem == UIBarButtonSystemItemFlexibleSpace)) {
            numberOfFlexibleItems++;
        }
    }

    const CGSize size = self.bounds.size;
    const CGFloat flexibleSpaceWidth = (numberOfFlexibleItems > 0)? MAX(0, size.width/numberOfFlexibleItems) : 0;
    CGFloat left = 0;

    for (UIBarButtonItem *item in _items) {
        UIView *view = item.customView;

        if (!view) {
            if (item->_isSystemItem && item->_systemItem == UIBarButtonSystemItemFlexibleSpace) {
                left += flexibleSpaceWidth;
            } else if (item->_isSystemItem && item->_systemItem == UIBarButtonSystemItemFixedSpace) {
                left += item.width;
            } else {
                view = [[[UIToolbarButton alloc] initWithBarButtonItem:item] autorelease];
            }
        }

        if (view) {
            CGRect frame = view.frame;
            frame.origin.x = left;
            frame.origin.y = (size.height / 2.f) - (frame.size.height / 2.f);
            frame = CGRectStandardize(frame);

            view.frame = frame;
            left += frame.size.width;

            [self addSubview:view];
        }
    }
}
*/

- (void)layoutSubviews
{
    [super layoutSubviews];

    CGFloat itemWidth = 0;
    NSUInteger numberOfFlexibleItems = 0;

    for (UIToolbarItem *toolbarItem in _toolbarItems) {
        const CGFloat width = toolbarItem.width;
        if (width >= 0) {
            itemWidth += width;
        } else {
            numberOfFlexibleItems++;
        }
    }

    const CGSize size = self.bounds.size;
    const CGFloat flexibleSpaceWidth = (numberOfFlexibleItems > 0)? ((size.width - itemWidth) / numberOfFlexibleItems) : 0;
    const CGFloat centerY = size.height / 2.f;

    CGFloat x = 0;

    for (UIToolbarItem *toolbarItem in _toolbarItems) {
        UIView *view = toolbarItem.view;
        const CGFloat width = toolbarItem.width;

        if (view) {
            CGRect frame = view.frame;
            frame.origin.x = x;
            frame.origin.y = floorf(centerY - (frame.size.height / 2.f));
            view.frame = frame;
        }

        if (width < 0) {
            x += flexibleSpaceWidth;
        } else {
            x += width;
        }
    }
}

- (void)setItems:(NSArray *)newItems animated:(BOOL)animated
{
    if (![self.items isEqualToArray:newItems]) {
        // if animated, fade old item views out, otherwise just remove them
        for (UIToolbarItem *toolbarItem in _toolbarItems) {
            UIView *view = toolbarItem.view;
            if (view) {
                [UIView animateWithDuration:animated? 0.2 : 0
                                 animations:^(void) {
                                     view.alpha = 0;
                                 }
                                 completion:^(BOOL finished) {
                                     [view removeFromSuperview];
                                 }];
            }
        }

        [_toolbarItems removeAllObjects];

        for (UIBarButtonItem *item in newItems) {
            UIToolbarItem *toolbarItem = [[UIToolbarItem alloc] initWithBarButtonItem:item];
            [_toolbarItems addObject:toolbarItem];
            [self addSubview:toolbarItem.view];
            [toolbarItem release];
        }

        // if animated, fade them in
        if (animated) {
            for (UIToolbarItem *toolbarItem in _toolbarItems) {
                UIView *view = toolbarItem.view;
                if (view) {
                    view.alpha = 0;

                    [UIView animateWithDuration:0.2
                                     animations:^(void) {
                                         view.alpha = 1;
                                     }];
                }
            }
        }
    }
}

- (void)setItems:(NSArray *)items
{
    [self setItems:items animated:NO];
}

- (NSArray *)items
{
    return [_toolbarItems valueForKey:@"item"];
}

- (void)drawRect:(CGRect)rect
{
    const CGRect bounds = self.bounds;

    UIColor *color = _tintColor ?: [UIColor colorWithRed:21/255.f green:21/255.f blue:25/255.f alpha:1];

    [color setFill];
    UIRectFill(bounds);

    [[UIColor blackColor] setFill];
    UIRectFill(CGRectMake(0,0,bounds.size.width,1));
}

- (NSString *)description
{
    NSString *barStyle = @"";
    switch (self.barStyle) {
        case UIBarStyleDefault:
            barStyle = @"Default";
            break;
        case UIBarStyleBlack:
            barStyle = @"Black";
            break;
        case UIBarStyleBlackTranslucent:
            barStyle = @"Black Translucent (Deprecated)";
            break;
    }
    return [NSString stringWithFormat:@"<%@: %p; barStyle = %@; tintColor = %@, isTranslucent = %@>", [self className], self, barStyle, ([self.tintColor description] ?: @"Default"), (self.translucent ? @"YES" : @"NO")];
}

@end


text:
CONFIG_FILE=/kubernetes-vault/kubernetes-vault.yml

# Write the configuration if it was passed in using the KUBERNETES_VAULT_LOCAL_CONFIG environment variable
if [ -n "$KUBERNETES_VAULT_LOCAL_CONFIG" ]; then
    echo "$KUBERNETES_VAULT_LOCAL_CONFIG" > "$CONFIG_FILE"
fi

NUM_ARGS=$#

# If the user is trying to run kuberentes-vault directly with some or no arguments, then
# pass them to kubernetes-vault.
if [ "${1:0:1}" = '-' ] || [ $NUM_ARGS = 0 ]; then
    set -- kubernetes-vault "$@"
fi

HAS_CONFIG_FLAG=false

for i in "$@" ; do
    if [[ "${i:0:8}" == "--config" ]] ; then
        HAS_CONFIG_FLAG=true
        break
    fi
done

HAS_LOG_LEVEL_FLAG=false

for i in "$@" ; do
    if [[ "${i:0:11}" == "--log-level" ]] ; then
        HAS_LOG_LEVEL_FLAG=true
        break
    fi
done

if [ "$HAS_CONFIG_FLAG" = false -a "$HAS_LOG_LEVEL_FLAG" = true ] || [ $NUM_ARGS = 0 ] ; then
    set -- "$@" --config="$CONFIG_FILE"
fi

exec "$@"


text:
package org.s1.weboperation;

import org.s1.objects.Objects;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Operation that executes multiple other web operations at once.

 * Accepts requests like:
 *
{list: [{
 *     operation: "...operation name...",
 *     method: "...method...",
 *     params: Object
 * }, ...]}

 * Usually uses with {@link org.s1.weboperation.MapWebOperation} because params must be parseable
 * with {@link org.s1.weboperation.MapWebOperation#convertRequestToMap(javax.servlet.http.HttpServletRequest)}
 */
public class CommandWebOperation extends MapWebOperation {

    @Override
    protected Map<String, Object> process(String method, Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<Map<String,Object>> listParams = Objects.get(params,"list",new ArrayList<Map<String, Object>>());
        List<Map<String,Object>> listResults = Objects.newArrayList();

        int i=0;
        for (Map<String,Object> cmd : listParams) {
            Map<String,Object> cmdFinalResult = null;
            try {
                Object cmdParams = Objects.get(cmd,"params",Objects.newSOHashMap());
                String cmdOperation = Objects.get(cmd,"operation");
                String cmdMethod = Objects.get(cmd,"method");
                Objects.assertNotEmpty("Operation ("+i+") must not be empty",cmdOperation);
                WebOperation wo = DispatcherServlet.getOperationByName(cmdOperation);

                Object cmdResult = wo.process(cmdMethod, cmdParams, request, response);
                cmdFinalResult = Objects.newHashMap("data",cmdResult,"success",true);
            } catch (Throwable e) {
                logError(e);
                cmdFinalResult = Objects.newHashMap("data",transformError(e, request, response),"success",false);
            }
            listResults.add(cmdFinalResult);
            i++;
        }

        return Objects.newHashMap("list",listResults);
    }
}


text:
// Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <paddle/fluid/framework/op_registry.h>

#include <chrono>
#include <iostream>
#include <memory>
#include <set>
#include <string>
#include <vector>

#include "glog/logging.h"
#include "gtest/gtest.h"
#include "paddle/fluid/eager/tests/performance_tests/benchmark_utils.h"
#include "paddle/fluid/eager/tests/test_utils.h"
#include "paddle/fluid/imperative/basic_engine.h"
#include "paddle/fluid/imperative/tracer.h"
#include "paddle/fluid/memory/memcpy.h"

#ifdef WITH_GPERFTOOLS
#include "gperftools/profiler.h"
#endif

#include "paddle/phi/core/kernel_registry.h"

#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)

PD_DECLARE_KERNEL(full, GPU, ALL_LAYOUT);
PD_DECLARE_KERNEL(matmul, GPU, ALL_LAYOUT);
PD_DECLARE_KERNEL(matmul_grad, GPU, ALL_LAYOUT);
PD_DECLARE_KERNEL(add, KPS, ALL_LAYOUT);
PD_DECLARE_KERNEL(add_grad, GPU, ALL_LAYOUT);
PD_DECLARE_KERNEL(sum, GPU, ALL_LAYOUT);
PD_DECLARE_KERNEL(sum_grad, GPU, ALL_LAYOUT);

namespace paddle {
namespace imperative {

TEST(Benchmark, FluidScaleCUDA) {
  // Prepare Device Contexts
  platform::CUDAPlace place;
  eager_test::InitEnv(place);

  for (const std::string& mode : {"Accuracy", "WarmUp", "Performance"}) {
    std::shared_ptr<imperative::VarBase> X(new imperative::VarBase(true, "X"));
    X->SetOverridedStopGradient(false);

    std::vector<float> src_data(128, 5.0);
    std::vector<int64_t> dims = {2, 4, 4, 4};

    auto* x_tensor = X->MutableVar()->GetMutable<phi::DenseTensor>();
    x_tensor->Resize(phi::make_ddim(dims));
    auto* mutable_x = x_tensor->mutable_data<float>(place);

    paddle::platform::DeviceContextPool& pool =
        paddle::platform::DeviceContextPool::Instance();
    auto* dev_ctx = dynamic_cast<phi::GPUContext*>(pool.Get(place));
    auto stream = dev_ctx->stream();
    paddle::memory::Copy(place,
                         mutable_x,
                         platform::CPUPlace(),
                         src_data.data(),
                         sizeof(float) * src_data.size(),
                         stream);

    if (mode == "Accuracy") {
      benchmark_fluid_scale(
          X, platform::Place(place), true /* accuracy_check */);

    } else if (mode == "WarmUp") {
      benchmark_fluid_scale(X, platform::Place(place));

    } else if (mode == "Performance") {
      auto t_start = std::chrono::high_resolution_clock::now();
#ifdef WITH_GPERFTOOLS
      ProfilerStart("fluid_scale_cuda.out");
#endif
      benchmark_fluid_scale(X, platform::Place(place));

#ifdef WITH_GPERFTOOLS
      ProfilerStop();
#endif
      auto t_end = std::chrono::high_resolution_clock::now();
      double elapsed_time_ms =
          std::chrono::duration<double, std::milli>(t_end - t_start).count();
      std::cout << "Duration: " << elapsed_time_ms << " ms" << std::endl;

    } else {
      PADDLE_THROW(paddle::platform::errors::Fatal("Unknown benchmark mode"));
    }
  }
}

TEST(Benchmark, FluidMatmulCUDA) {
  // Prepare Device Contexts
  platform::CUDAPlace place;
  eager_test::InitEnv(place);

  for (const std::string& mode : {"Accuracy", "WarmUp", "Performance"}) {
    std::shared_ptr<imperative::VarBase> X(new imperative::VarBase(true, "X"));
    X->SetOverridedStopGradient(false);
    std::shared_ptr<imperative::VarBase> Y(new imperative::VarBase(true, "Y"));
    Y->SetOverridedStopGradient(false);

    std::vector<float> x_src_data(4, 1.0);
    std::vector<float> y_src_data(4, 2.0);
    std::vector<int64_t> dims = {2, 2};

    paddle::platform::DeviceContextPool& pool =
        paddle::platform::DeviceContextPool::Instance();
    auto* dev_ctx = dynamic_cast<phi::GPUContext*>(pool.Get(place));
    auto stream = dev_ctx->stream();

    auto* x_tensor = X->MutableVar()->GetMutable<phi::DenseTensor>();
    x_tensor->Resize(phi::make_ddim(dims));
    auto* mutable_x = x_tensor->mutable_data<float>(place);
    paddle::memory::Copy(place,
                         mutable_x,
                         platform::CPUPlace(),
                         x_src_data.data(),
                         sizeof(float) * x_src_data.size(),
                         stream);

    auto* y_tensor = Y->MutableVar()->GetMutable<phi::DenseTensor>();
    y_tensor->Resize(phi::make_ddim(dims));
    auto* mutable_y = y_tensor->mutable_data<float>(place);
    paddle::memory::Copy(place,
                         mutable_y,
                         platform::CPUPlace(),
                         y_src_data.data(),
                         sizeof(float) * y_src_data.size(),
                         stream);

    if (mode == "Accuracy") {
      benchmark_fluid_matmul(
          X, Y, platform::Place(place), true /* accuracy_check */);

    } else if (mode == "WarmUp") {
      benchmark_fluid_matmul(X, Y, platform::Place(place));

    } else if (mode == "Performance") {
      auto t_start = std::chrono::high_resolution_clock::now();
#ifdef WITH_GPERFTOOLS
      ProfilerStart("fluid_matmul_cuda.out");
#endif
      benchmark_fluid_matmul(X, Y, platform::Place(place));

#ifdef WITH_GPERFTOOLS
      ProfilerStop();
#endif
      auto t_end = std::chrono::high_resolution_clock::now();
      double elapsed_time_ms =
          std::chrono::duration<double, std::milli>(t_end - t_start).count();
      std::cout << "Duration: " << elapsed_time_ms << " ms" << std::endl;

    } else {
      PADDLE_THROW(paddle::platform::errors::Fatal("Unknown benchmark mode"));
    }
  }
}

TEST(Benchmark, FluidMLPCUDA) {
  // Prepare Device Contexts
  platform::CUDAPlace place;
  eager_test::InitEnv(place);

  for (const std::string& mode : {"Accuracy", "WarmUp", "Performance"}) {
    paddle::platform::DeviceContextPool& pool =
        paddle::platform::DeviceContextPool::Instance();
    auto* dev_ctx = dynamic_cast<phi::GPUContext*>(pool.Get(place));
    auto stream = dev_ctx->stream();

    std::vector<float> x_src_data(MLP_M * MLP_N, MLP_X_VAL);
    std::vector<float> w_src_data(MLP_N * MLP_K, MLP_W_VAL);
    std::vector<float> b_src_data(MLP_K, MLP_B_VAL);

    std::vector<int64_t> x_dims = {MLP_M, MLP_N};
    std::vector<int64_t> w_dims = {MLP_N, MLP_K};
    std::vector<int64_t> b_dims = {MLP_K};

    std::shared_ptr<imperative::VarBase> X(new imperative::VarBase(true, "X"));
    X->SetOverridedStopGradient(false);

    auto* x_tensor = X->MutableVar()->GetMutable<phi::DenseTensor>();
    x_tensor->Resize(phi::make_ddim(x_dims));
    auto* mutable_x = x_tensor->mutable_data<float>(place);
    paddle::memory::Copy(place,
                         mutable_x,
                         platform::CPUPlace(),
                         x_src_data.data(),
                         sizeof(float) * x_src_data.size(),
                         stream);

    std::vector<std::shared_ptr<imperative::VarBase>> Ws;
    std::vector<std::shared_ptr<imperative::VarBase>> Bs;
    for (size_t i = 0; i < MLP_NUM_LINEAR; i++) {
      std::shared_ptr<imperative::VarBase> W(
          new imperative::VarBase(true, "W"));
      W->SetOverridedStopGradient(false);
      std::shared_ptr<imperative::VarBase> B(
          new imperative::VarBase(true, "B"));
      B->SetOverridedStopGradient(false);

      auto* w_tensor = W->MutableVar()->GetMutable<phi::DenseTensor>();
      w_tensor->Resize(phi::make_ddim(w_dims));
      auto* mutable_w = w_tensor->mutable_data<float>(place);
      paddle::memory::Copy(place,
                           mutable_w,
                           platform::CPUPlace(),
                           w_src_data.data(),
                           sizeof(float) * w_src_data.size(),
                           stream);

      auto* b_tensor = B->MutableVar()->GetMutable<phi::DenseTensor>();
      b_tensor->Resize(phi::make_ddim(b_dims));
      auto* mutable_b = b_tensor->mutable_data<float>(place);
      paddle::memory::Copy(place,
                           mutable_b,
                           platform::CPUPlace(),
                           b_src_data.data(),
                           sizeof(float) * b_src_data.size(),
                           stream);

      Ws.emplace_back(std::move(W));
      Bs.emplace_back(std::move(B));
    }

    if (mode == "Accuracy") {
      benchmark_fluid_mlp(
          X, Ws, Bs, platform::Place(place), true /* accuracy_check */);

    } else if (mode == "WarmUp") {
      benchmark_fluid_mlp(X, Ws, Bs, platform::Place(place));

    } else if (mode == "Performance") {
      auto t_start = std::chrono::high_resolution_clock::now();
#ifdef WITH_GPERFTOOLS
      ProfilerStart("fluid_mlp_cuda.out");
#endif
      benchmark_fluid_mlp(X, Ws, Bs, platform::Place(place));

#ifdef WITH_GPERFTOOLS
      ProfilerStop();
#endif
      auto t_end = std::chrono::high_resolution_clock::now();
      double elapsed_time_ms =
          std::chrono::duration<double, std::milli>(t_end - t_start).count();

      std::cout << "Duration: " << elapsed_time_ms << " ms" << std::endl;

    } else {
      PADDLE_THROW(paddle::platform::errors::Fatal("Unknown benchmark mode"));
    }
  }
}

}  // namespace imperative
}  // namespace paddle

USE_OP_ITSELF(scale);
USE_OP_ITSELF(matmul_v2);
USE_OP_ITSELF(reduce_sum);
USE_OP_ITSELF(reduce_sum_grad);
USE_OP_ITSELF(elementwise_add);

#endif  // PADDLE_WITH_CUDA || PADDLE_WITH_HIP


text: Ejemplo sencillo calculadora


text:
package coremain

// Various CoreDNS constants.
const (
	CoreVersion = "1.2.6"
	coreName    = "CoreDNS"
	serverType  = "dns"
)


text:
NodeProp, also known as np for short, is a unified
application programming interface for arbitrary graph
constructions.

## In Development and Contributing
NodeProp is currently under development and as such most
features described here are unimplemented. Please see the
ROADMAP.md file for implementation progress. Contributions
under the license described in LICENSE.md are most defintely welcome,
please use the github fork/pull request featureset for patches.

## Requirements and Runtime Dependencies
* Ruby 1.9.2p136 or greater
* ActiveSupport ~> v3.0.3

## Graph Object API and NodeProp Object Schema

### Graph Object API
Examples of using the proposed Graph Object API below:

#### Setup
    graph = NodeProp::Graph.new
    property = NodeProp::Property.new(:name, String, :default => 'DefaultNodeName')
    property_set = NodeProp::PropertySet.new(property)
    node = NodeProp::Node.new(:property_set => property_set)

#### Adding Nodes to the Graph
    graph.add_node(node)

#### Removing a Node from a Graph
    graph.remove_node(node)

#### Adding an Index to a Graph
    index = NodeProp::Index.new( :type => :node, :key => :name )
    graph.add_index(index)

#### Mutating a PropertySet
    property_set.add_property :quantity, Integer, :default => 0
    property_set.remove_property :name

#### Mutating a Property Entry
    No interface has yet been decided on for mutating property entries.

### Object Schema/Primitives
The NodeProp schema is relatively constrained in order to
present the most flexible interface possible for graph
containment. With this concept in mind, the primitives with which
we will work are: Node, PropertySet, Index, Graph, Traveller,
and QueryEngine.

#### The Node
The Node primative represents an atom within the
graph, essentially a particular instance of a PropertySet.

#### The Property
The Property is essentially a key-value pair with metadata. It is named, and
is also namespaced. Property names must be unique within their namespace.

#### The PropertyNamespace
The PropertyNamespace is a collection of named key-value pairs. The PropertyNamespace
enforces unique name constraints within the namespace.

#### The PropertySet
The PropertySet represents a collection of key-value pairs which
describe the particular properties ascribed to a node or set of
nodes. PropertySets are equal if all of their key-value pairs
are equal.

#### The Index
The Index maintains a forward mapping from key-value pairs
in a nodes PropertySet to the list of nodes containing equal
key-values. For instance, given a set of nodes A and B with
PropertySets Ap and Bp both containing namespaced key-value
pairs of Ap -> { :test/key => 1 }, Bp -> { :test/key => 1 } than the
Index for ns:test/key would contain the values:
{ 1 => [A, B] }.

#### The Graph
The Graph coordinates the mutation of a named set of nodes and
PropertySets.

#### The Traveller
The Traveller encapsulates the operations required for traversing
the graph in the most efficient manor for the requirements given.

#### The QueryEngine
The QueryEngine provides an interface for specifying arbitrarily
complex queries for a given graph in a standardized format. The
QueryEngine then creates a customized Traveller to execute the query.

## Persistence
Currently only for in-process in-memory graph structures, nodeprop
does not provide any specific persistence mechanism. However, a
persistence mechanism may be implemented by hooking into the
provided Graph, Node, PropertySet, and Index modification
and data-loading callbacks. See the project NodePropDB for
the NodeProp primary implementation of persistence once the project
has been started.

## ACID Principles
ACID principles ( Atomicity, Consistency, Isolation, and Durability )
provide a certain set of guarantees for data stores. As a group,
providing support for ACID guarantees is an early roadmap goal.
Full support will likely depend on the backing store eventually
implemented, and will remain optional so that any overhead introduced
with those guarantees need not be experienced by those not requiring
them.


text:
XCrataPult.CMS
==============

[not production]


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/logging/v2/logging.proto

package com.google.logging.v2;

public interface WriteLogEntriesRequestOrBuilder extends
    // @@protoc_insertion_point(interface_extends:google.logging.v2.WriteLogEntriesRequest)
    com.google.protobuf.MessageOrBuilder {

  /**
   *

   * Optional. A default log resource name that is assigned to all log entries
   * in `entries` that do not specify a value for `log_name`:
   *     "projects/[PROJECT_ID]/logs/[LOG_ID]"
   *     "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]"
   * `[LOG_ID]` must be URL-encoded. For example,
   * `"projects/my-project-id/logs/syslog"` or
   * `"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"`.
   * For more information about log names, see
   * [LogEntry][google.logging.v2.LogEntry].
   *

   *
   * optional string log_name = 1;
   */
  java.lang.String getLogName();
  /**
   *

   * Optional. A default log resource name that is assigned to all log entries
   * in `entries` that do not specify a value for `log_name`:
   *     "projects/[PROJECT_ID]/logs/[LOG_ID]"
   *     "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]"
   * `[LOG_ID]` must be URL-encoded. For example,
   * `"projects/my-project-id/logs/syslog"` or
   * `"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"`.
   * For more information about log names, see
   * [LogEntry][google.logging.v2.LogEntry].
   *

   *
   * optional string log_name = 1;
   */
  com.google.protobuf.ByteString
      getLogNameBytes();

  /**
   *

   * Optional. A default monitored resource object that is assigned to all log
   * entries in `entries` that do not specify a value for `resource`. Example:
   *     { "type": "gce_instance",
   *       "labels": {
   *         "zone": "us-central1-a", "instance_id": "00000000000000000000" }}
   * See [LogEntry][google.logging.v2.LogEntry].
   *

   *
   * optional .google.api.MonitoredResource resource = 2;
   */
  boolean hasResource();
  /**
   *

   * Optional. A default monitored resource object that is assigned to all log
   * entries in `entries` that do not specify a value for `resource`. Example:
   *     { "type": "gce_instance",
   *       "labels": {
   *         "zone": "us-central1-a", "instance_id": "00000000000000000000" }}
   * See [LogEntry][google.logging.v2.LogEntry].
   *

   *
   * optional .google.api.MonitoredResource resource = 2;
   */
  com.google.api.MonitoredResource getResource();
  /**
   *

   * Optional. A default monitored resource object that is assigned to all log
   * entries in `entries` that do not specify a value for `resource`. Example:
   *     { "type": "gce_instance",
   *       "labels": {
   *         "zone": "us-central1-a", "instance_id": "00000000000000000000" }}
   * See [LogEntry][google.logging.v2.LogEntry].
   *

   *
   * optional .google.api.MonitoredResource resource = 2;
   */
  com.google.api.MonitoredResourceOrBuilder getResourceOrBuilder();

  /**
   *

   * Optional. Default labels that are added to the `labels` field of all log
   * entries in `entries`. If a log entry already has a label with the same key
   * as a label in this parameter, then the log entry's label is not changed.
   * See [LogEntry][google.logging.v2.LogEntry].
   *

   *
   * map<string, string> labels = 3;
   */
  int getLabelsCount();
  /**
   *

   * Optional. Default labels that are added to the `labels` field of all log
   * entries in `entries`. If a log entry already has a label with the same key
   * as a label in this parameter, then the log entry's label is not changed.
   * See [LogEntry][google.logging.v2.LogEntry].
   *

   *
   * map<string, string> labels = 3;
   */
  boolean containsLabels(
      java.lang.String key);
  /**
   * Use {@link #getLabelsMap()} instead.
   */
  @java.lang.Deprecated
  java.util.Map<java.lang.String, java.lang.String>
  getLabels();
  /**
   *

   * Optional. Default labels that are added to the `labels` field of all log
   * entries in `entries`. If a log entry already has a label with the same key
   * as a label in this parameter, then the log entry's label is not changed.
   * See [LogEntry][google.logging.v2.LogEntry].
   *

   *
   * map<string, string> labels = 3;
   */
  java.util.Map<java.lang.String, java.lang.String>
  getLabelsMap();
  /**
   *

   * Optional. Default labels that are added to the `labels` field of all log
   * entries in `entries`. If a log entry already has a label with the same key
   * as a label in this parameter, then the log entry's label is not changed.
   * See [LogEntry][google.logging.v2.LogEntry].
   *

   *
   * map<string, string> labels = 3;
   */

  java.lang.String getLabelsOrDefault(
      java.lang.String key,
      java.lang.String defaultValue);
  /**
   *

   * Optional. Default labels that are added to the `labels` field of all log
   * entries in `entries`. If a log entry already has a label with the same key
   * as a label in this parameter, then the log entry's label is not changed.
   * See [LogEntry][google.logging.v2.LogEntry].
   *

   *
   * map<string, string> labels = 3;
   */

  java.lang.String getLabelsOrThrow(
      java.lang.String key);

  /**
   *

   * Required. The log entries to write. Values supplied for the fields
   * `log_name`, `resource`, and `labels` in this `entries.write` request are
   * added to those log entries that do not provide their own values for the
   * fields.
   * To improve throughput and to avoid exceeding the
   * [quota limit](/logging/quota-policy) for calls to `entries.write`,
   * you should write multiple log entries at once rather than
   * calling this method for each individual log entry.
   *

   *
   * repeated .google.logging.v2.LogEntry entries = 4;
   */
  java.util.List<com.google.logging.v2.LogEntry>
      getEntriesList();
  /**
   *

   * Required. The log entries to write. Values supplied for the fields
   * `log_name`, `resource`, and `labels` in this `entries.write` request are
   * added to those log entries that do not provide their own values for the
   * fields.
   * To improve throughput and to avoid exceeding the
   * [quota limit](/logging/quota-policy) for calls to `entries.write`,
   * you should write multiple log entries at once rather than
   * calling this method for each individual log entry.
   *

   *
   * repeated .google.logging.v2.LogEntry entries = 4;
   */
  com.google.logging.v2.LogEntry getEntries(int index);
  /**
   *

   * Required. The log entries to write. Values supplied for the fields
   * `log_name`, `resource`, and `labels` in this `entries.write` request are
   * added to those log entries that do not provide their own values for the
   * fields.
   * To improve throughput and to avoid exceeding the
   * [quota limit](/logging/quota-policy) for calls to `entries.write`,
   * you should write multiple log entries at once rather than
   * calling this method for each individual log entry.
   *

   *
   * repeated .google.logging.v2.LogEntry entries = 4;
   */
  int getEntriesCount();
  /**
   *

   * Required. The log entries to write. Values supplied for the fields
   * `log_name`, `resource`, and `labels` in this `entries.write` request are
   * added to those log entries that do not provide their own values for the
   * fields.
   * To improve throughput and to avoid exceeding the
   * [quota limit](/logging/quota-policy) for calls to `entries.write`,
   * you should write multiple log entries at once rather than
   * calling this method for each individual log entry.
   *

   *
   * repeated .google.logging.v2.LogEntry entries = 4;
   */
  java.util.List<? extends com.google.logging.v2.LogEntryOrBuilder>
      getEntriesOrBuilderList();
  /**
   *

   * Required. The log entries to write. Values supplied for the fields
   * `log_name`, `resource`, and `labels` in this `entries.write` request are
   * added to those log entries that do not provide their own values for the
   * fields.
   * To improve throughput and to avoid exceeding the
   * [quota limit](/logging/quota-policy) for calls to `entries.write`,
   * you should write multiple log entries at once rather than
   * calling this method for each individual log entry.
   *

   *
   * repeated .google.logging.v2.LogEntry entries = 4;
   */
  com.google.logging.v2.LogEntryOrBuilder getEntriesOrBuilder(
      int index);

  /**
   *

   * Optional. Whether valid entries should be written even if some other
   * entries fail due to INVALID_ARGUMENT or PERMISSION_DENIED errors. If any
   * entry is not written, the response status will be the error associated
   * with one of the failed entries and include error details in the form of
   * WriteLogEntriesPartialErrors.
   *

   *
   * optional bool partial_success = 5;
   */
  boolean getPartialSuccess();
}


text:
<?php

namespace app\Models;

use Egulias\EmailValidator\EmailValidator;
use \Gelembjuk\WebApp\Exceptions\FormException as FormException;

class Login extends \Gelembjuk\WebApp\Model {
    protected $remembermecodetime = 1209600; // 14 days

    public function getAntiSpamData()
    {
        // get 2 random numbers and remember their sum in a session

        $n1 = rand(1,100);
        $n2 = rand(1,100);

        $_SESSION['antispamsum'] = $n1+$n2;

        return array('a'=>$n1,'b'=>$n2);
    }

    public function checkAntiSpam($data)
    {

        if ($_SESSION['antispamsum'] == $data['c']) {
            return true;
        }

        return false;
    }

    protected function completeUserSignin($userid,$logintype = '', $rememberme = '',$referrer = '')
    {

        $logindb = $this->application->getDBO('Login');

        $user_rec = $logindb->getUserRecord($userid);

        if (!$user_rec) {
            throw new \Exception($this->_('usernotfound','account'));
        }

        $_SESSION['userid'] = $user_rec['id'];

        $this->application->setUserID($user_rec['id']);

        // remember in cookies or not
        if ($logintype == 'site') {
            if ($rememberme === 'y' || $rememberme === 'yes' || $rememberme === true ||
                $rememberme === 1 || $rememberme === '1') {

                $this->logQ('set cookie for '.$user_rec['id'],'login');
                // remember this user in the cookie
                $autologincode = $this->getAutologinCode($user_rec);

                setcookie('remembermecode',$autologincode,time() + $this->remembermecodetime, '/');
            } elseif ($rememberme != '') {

                setcookie('remembermecode','',time() + $this->remembermecodetime);
            }
        } elseif ($user_rec['email'] == '') {
            // redirect this user to a script to get email address
            return $this->application->makeUrl('login',array('view'=>'askemail'));
        }

        $this->logQ('complete login','login');

        if ($user_rec['id'] == 1) {
        	// this is admin. redirect to admin home
        	return $this->application->makeUrl('',array('s'=>'ahome'));
        }

        if ($referrer != '') {
            return $referrer;
        }

        return $this->application->makeUrl('',array('s'=>'home'));
    }

    public function logIn($email,$password,$rememberme = '',$referrer = '')
    {
        $email = trim($email);

        if ($email == '') {
            throw new \Exception($this->_('emailmissed','account'));
        }

        $password = trim($password);

        if ($password == '') {
            throw new \Exception($this->_('passwordmissed','account'));
        }

        $logindb = $this->application->getDBO('Login');

        $user_rec = $logindb->getUserByEmail($email);

        if (!$user_rec) {
            throw new \Exception($this->_('accountnotfound','account'));
        }

        if ($user_rec['logintype'] != 'site') {
            throw new \Exception($this->_('usesociallogin','account'));
        }

        if (!$this->checkPassword($password,$user_rec['password'],$user_rec['id'])) {
            throw new \Exception($this->_('passworddoesntmatch','account'));
        }

        if ($user_rec['active'] == '0') {
            throw new \Exception($this->_('accountisnotactive','account'));
        }

        $redirecturl = $this->completeUserSignin($user_rec,'site',$rememberme,$referrer);

        return $redirecturl;
    }

    public function logOut()
    {
        $_SESSION['userid'] = 0;
        unset($_SESSION['userid']);
        $this->application->setUserID(0);

        setcookie('remembermecode','',time()+$this->remembermecodetime,'/');
    }
    public function checkSocialLoginConfigured($network)
    {
        $networkobj = $this->getNetworkObject($network);

        return $networkobj->isConfigured();
    }
    public function getSocialLoginStartUrl($network,$referrer = '')
    {
        $networkobj = $this->getNetworkObject($network);

        $redirecturl = $this->application->makeAbsUrlQ('login','','do','sociallogincomplete',$network);

        $_SESSION['lastreferrer'] = $referrer;

        $url = $networkobj->getLoginStartUrl($redirecturl);

        $_SESSION['socialloginsate_'.$network] = $networkobj->serialize();

        return $url;
    }

    public function getSocialLoginExtraInputs($network)
    {
        $networkobj = $this->getNetworkObject($network);

        return $networkobj->getFinalExtraInputs();
    }

    public function loginWithSocial($network,$arguments)
    {
        $networkobj = $this->getNetworkObject($network);

        $networkobj->unSerialize($_SESSION['socialloginsate_'.$network]);
        // if fails then throws exception and controller will catch
        $profile = $networkobj->completeLogin($arguments);

        $this->logQ($profile,'login|sociallogin');

        // check if this user is already registered
        $logindb = $this->application->getDBO('Login');

        $user_rec = $logindb->getUserByExternalAuth($network,$profile['userid']);

        if (!$user_rec) {
            //check email is not used in the system
            if ($profile['email'] != '' && $logindb->checkEmailUsed($profile['email'])) {
                throw new \Exception($this->_('socialemailnameisused','account'));
            }
            // register this user
            $userid = $logindb->addUser($network,1,$profile['name'],$profile['email'],'nopassword','s',$profile['userid']);

            $user_rec = $logindb->getUser($userid);

            $messagingmodel = $this->application->getModel('Messaging');

            if ($user_rec['email'] != '') {

                $messagingmodel->sendRegistrationEmail($user_rec['id']);
            }
        }

        $redirecturl = $this->completeUserSignin($user_rec,$network,false,$_SESSION['lastreferrer']);

        return $redirecturl;
    }

    protected function getNetworkObject($network)
    {
        $options = array();

        if (is_array($this->application->getConfig('integrations')) &&
            is_array($this->application->getConfig('integrations')[$network])) {
            $options = $this->application->getConfig('integrations')[$network];
        }

        return \Gelembjuk\Auth\AuthFactory::getSocialLoginObject($network,$options);
    }

    public function logInWithCode($code)
    {
		$userid = $this->getUserFromAutologinCode($code);

		if ($userid > 0) {
			$this->completeUserSignin($userid,'site');
		}
	}
    public function registerUser($name,$email,$password,$subscribe)
    {
        $logindb = $this->application->getDBO('Login');

        if (trim($email) == '') {
            throw new FormException('email',$this->_('enteryouremail','account'));
        }

        $validator = new EmailValidator;

        if (!$validator->isValid($email)) {
            throw new FormException('email',$this->_('entervalidemail','account'));
        }

        if ($logindb->checkEmailUsed($email)) {
            throw new FormException('email',$this->_('emailnameisused','account'));
        }

        if (trim($name) == '') {
            throw new FormException('name',$this->_('enteryourname','account'));
        }

        if (trim($password) == '') {
            throw new FormException('password',$this->_('enterpassword','account'));
        }

        // all checks passed
        $passwordhash = $this->getPasswordHash($password);

        $userid = $logindb->addUser('site',0,$name,$email,$passwordhash);

        $profiledb = $this->application->getDBO('Profile');

        $profiledb->setSubscription($userid,$subscribe);

        // send activation email
        $messagingmodel = $this->application->getModel('Messaging');

        $activationcode = $this->getAutologinCode($userid,'', time() + 3600 * 48,$email);

        $messagingmodel->sendActivationEmail($userid, $activationcode);

        return true;
    }

    public function activateUser($code, $email)
    {
        $logindb = $this->application->getDBO('Login');

        $user_id = $this->getUserFromAutologinCode($code, $email, 3600 * 48);

        if ($user_id < 1) {
            throw new \Exception($this->_('activationcodenotfound','account'));
        }

        $user_rec = $logindb->getUser($user_id);

        if (!$user_rec) {
            throw new \Exception($this->_('activationcodenotfound','account'));
        }

        $logindb->activateUser($user_rec['id']);

        $messagingmodel = $this->application->getModel('Messaging');
        $messagingmodel->sendRegistrationEmail($user_rec['id']);

        // make this user to be loged in
        return $this->completeUserSignin($user_rec,'site','n','');
    }
    public function resendUserActivation($email,$newemail,$returnfinalemail = false)
    {
        $logindb = $this->application->getDBO('Login');

        $user_rec = $logindb->getUserByEmail($email);

        if (!$user_rec) {
            throw new \Exception($this->_('thisemailnotfound','account'));
        }

        if ($email != $newemail && $newemail != '') {

            // try to set new email address
            $validator = new EmailValidator;

            if (!$validator->isValid($newemail)) {
                throw new FormException('email',$this->_('entervalidemail','account'));
            }

            if ($logindb->checkEmailUsed($newemail)) {
                throw new FormException('email',$this->_('emailnameisused','account'));
            }

            $profiledb = $this->application->getDBO('Profile');
            $profiledb->updateUserEmail($user_rec['id'],$newemail);

            $email = $newemail;
        }

        $messagingmodel = $this->application->getModel('Messaging');

        $activationcode = $this->getAutologinCode($user_rec['id'],'', time() + 3600 * 48,$email);

        $messagingmodel->sendActivationEmail($user_rec['id'],$activationcode);

        if ($returnfinalemail) {
            return $email;
        }

        return true;
    }
    public function sendPasswordResetEmail($email) {
        if (trim($email) == '') {
            throw new \Exception($this->_('enteryouremail','account'));
        }

        $logindb = $this->application->getDBO('Login');

        $user_rec = $logindb->getUserByEmail($email);

        if (!$user_rec) {
            throw new \Exception($this->_('thisemailnotfound','account'));
        }

        $resetcode = $this->getPasswordResetCode($user_rec['email'],$user_rec['password'],$user_rec['id']);

        $messagingmodel = $this->application->getModel('Messaging');
        $messagingmodel->sendPasswordResetEmail($user_rec,$resetcode);

        return true;
    }
    public function resetPassword($code,$email,$password) {
        if (trim($password) == '') {
            throw new \Exception($this->_('enterpassword','account'));
        }
        $logindb = $this->application->getDBO('Login');

        $user_rec = $logindb->getUserByEmail($email);

        if (!$user_rec) {
            throw new \Exception($this->_('thisemailnotfound','account').'. '.$this->_('repeatprocess'));
        }

        if (!$this->checkPasswordResetCode($code,$user_rec['email'],$user_rec['password'],$user_rec['id'])) {
            throw new \Exception($this->_('resetcodeiswrong','account').'. '.$this->_('repeatprocess'));
        }

        if ($user_rec['logintype'] != 'site') {
            // update login type. it can be old user registered on MEP
            $logindb->updateUserLoginType($user_rec['id'],'site');
        }
        // update the password
        $logindb->updateUserPassword($user_rec['id'],$this->getPasswordHash($password));

        $messagingmodel = $this->application->getModel('Messaging');
        $messagingmodel->sendPasswordResetConfirmationEmail($user_rec);

        return true;
    }

    public function updatePassword($curpassword,$password)
    {
        $this->signinRequired();

        if (trim($password) == '' || trim($curpassword) == '') {
            throw new \Exception($this->_('enterpassword','account'));
        }

        $logindb = $this->application->getDBO('Login');

        $user_rec = $logindb->getUserRecord($this->getUserID());

        if ($user_rec['logintype'] != 'site') {
            // update login type. it can be old user registered on MEP
            $logindb->updateUserLoginType($user_rec['id'],'site');
        }

        if (!$this->checkPassword($curpassword,$user_rec['password'])) {
            throw new \Exception($this->_('curpassworddoesntmatch','account'));
        }

        if ($user_rec['active'] == '0') {
            throw new \Exception($this->_('accountisnotactive','account'));
        }

        $logindb->upgradePassword($user_rec['id'],$this->getPasswordHash($password));

        return true;
    }
    public function changeUserEmail($email) {
        $this->signinRequired();

        // check this email is used somewhere else
        $logindb = $this->application->getDBO('Login');

        // try to set new email address
        $validator = new EmailValidator;

        if (!$validator->isValid($email)) {
            throw new FormException('email',$this->_('entervalidemail','account'));
        }

        if ($logindb->checkEmailUsed($email)) {
            throw new FormException('email',$this->_('emailnameisused','account'));
        }

        // make confirm code
        $user_rec = $logindb->getUserRecord($this->getUserID());

        $confirmcode = $this->getAutologinCode($user_rec['id'],'', 0,$email);

        $messagingmodel = $this->application->getModel('Messaging');
        $messagingmodel->sendEmailChangeConfirmEmail($email,$user_rec,$confirmcode);

        return true;
    }
    public function changeUserEmailConfirm($email,$code) {
        $userid = $this->getUserFromAutologinCode($code,$email,10000);

        if ($userid < 1) {
            throw new \Exception($this->_('emailconfirmationfailedtryagain','account'));
        }

        $profiledb = $this->application->getDBO('Profile');
        // check if existent user

        $user_rec = $profiledb->getUserRecord($userid);

        if (!$user_rec) {
            throw new \Exception($this->_('usernotfound','account'));
        }

        $profiledb->updateUserEmail($userid,$email);

        return true;
    }

    public function setUserEmail($email) {
        $this->signinRequired();

        // try to set new email address
        $validator = new EmailValidator;

        if (!$validator->isValid($email)) {
            throw new FormException('email',$this->_('entervalidemail','account'));
        }

        $logindb = $this->application->getDBO('Login');

        if ($logindb->checkEmailUsed($email)) {
            throw new FormException('email',$this->_('emailnameisused','account'));
        }

        $profiledb = $this->application->getDBO('Profile');
        $profiledb->updateUserEmail($this->getUserID(),$email);

        $user_rec = $logindb->getUserRecord($this->getUserID());

        if ($user_rec['usertype'] == '') {
            return $this->application->makeUrlQ('login','','view','asktype');
        }

        return '';
    }
    protected function checkPasswordResetCode($code,$email,$currentpasshash,$userid)
    {
        if (!preg_match('!^(.+)-(.+)$!',$code,$m)) {
            return false;
        }

        $code = $m[1];
        $randomnumber = $m[2];

        if ($code == $this->getHashed($email.$currentpasshash.$userid.$randomnumber)) {
            return true;
        }
        return false;
    }
    protected function getPasswordResetCode($email,$currentpasshash,$userid)
    {
        $randomnumber = (string)rand(1000,9999);

        $code = $this->getHashed($email.$currentpasshash.$userid.$randomnumber);

        return $code.'-'.$randomnumber;
    }

    protected function upgradePassword($userid,$password)
    {
        if ($userid < 1) {
            return false;
        }

        $logindb = $this->application->getDBO('Login');

        $logindb->updateUserPassword($userid,
            $this->getPasswordHash($password));

        return true;
    }
    protected function checkPassword($password,$passwordhash, $userid = 0)
    {
        // try all possible combinations. as we have different salts for 2 sites
        if ($this->validatePassword($password,$passwordhash)) {
            return true;
        }

        if ($passwordhash == 'PLAIN:'.$password && $userid > 0) {
            $this->upgradePassword($userid,$password);
            return true;
        }
        return false;
    }
    protected function getHashed($string,$emptysalt = false,$salt = '') {
        if ($salt == '') {
            $salt = $this->application->getConfig('system_salt_general');
        }

        if ($emptysalt) {
            $salt = '';
        }

        $this->debug('get hash for '.$string.' and salt '.$salt);

        $hash = sha1($string.$salt);

        for ($i = 0;$i < 500;$i++) {
            $hash = md5($hash.$salt);
        }

        return $hash;
    }
    protected function getUserFromAutologinCode($autologincode,$extratext = '',$expirationtime = 0) {
        if (!preg_match('!^(.+)-(.+)-(.+)-(.+)$!',$autologincode,$m)) {
            return false;
        }

        $randomnumber = $m[2];
        $time = $m[3];
        $userid = $m[4];

        $this->logQ('check '.$autologincode);

        if ($autologincode == $this->getAutologinCode($userid,$randomnumber,$time,$extratext)) {

            if ($expirationtime == 0) {
                $expirationtime = $this->remembermecodetime;
            }

            if ($time < time() - $expirationtime) {
                return 0; // the code is too old
            }
            return $userid;
        }
        return 0;
    }

    protected function getAutologinCode($userid,$randomnumber = '', $time = 0,$extratext = '') {
        $logindb = $this->application->getDBO('Login');

        $user_rec = $logindb->getUserRecord($userid);

        if ($randomnumber == '') {
            $randomnumber = (string)rand(1000,9999);
            $time = time();
        }

        $autologincode = $user_rec['password'].$user_rec['created'].$user_rec['id'].$randomnumber.$time.$extratext;

        $this->logQ('gen hash from '.$autologincode,'login');

        $code = $this->getHashed($autologincode);

        return $code.'-'.$randomnumber.'-'.$time.'-'.$user_rec['id'];
    }
    public function getUserRecord($user_rec = 0) {
        if ($user_rec === 0) {
            $user_rec = $this->getUserID();
        }
        $userdb = $this->application->getDBO('User');

        $user_rec = $userdb->getUserRecord($user_rec);

        if (!$user_rec) {
            $user_rec = array('id' => 0);
        }
        return $user_rec;
    }

    protected function getPasswordHash($password)
    {
        return password_hash($password, PASSWORD_DEFAULT);
    }

    protected function validatePassword($password,$hashedpassword)
    {
        return password_verify ( $password, $hashedpassword );
    }
}


text:
namespace gfx {
class Rect;
}  // namespace gfx

namespace ui {

class InputMethodObserver;
class TextInputClient;

// A helper class providing functionalities shared among ui::InputMethod
// implementations.
class UI_EXPORT InputMethodBase : NON_EXPORTED_BASE(public InputMethod) {
 public:
  InputMethodBase();
  virtual ~InputMethodBase();

  // Overriden from InputMethod.
  virtual void SetDelegate(internal::InputMethodDelegate* delegate) OVERRIDE;
  virtual void Init(bool focused) OVERRIDE;
  // If a derived class overrides OnFocus()/OnBlur(), it should call parent's
  // implementation first, to make sure |system_toplevel_window_focused_| flag
  // can be updated correctly.
  virtual void OnFocus() OVERRIDE;
  virtual void OnBlur() OVERRIDE;
  virtual void SetFocusedTextInputClient(TextInputClient* client) OVERRIDE;
  virtual void SetStickyFocusedTextInputClient(
      TextInputClient* client) OVERRIDE;
  virtual void DetachTextInputClient(TextInputClient* client) OVERRIDE;
  virtual TextInputClient* GetTextInputClient() const OVERRIDE;

  // If a derived class overrides this method, it should call parent's
  // implementation.
  virtual void OnTextInputTypeChanged(const TextInputClient* client) OVERRIDE;

  virtual TextInputType GetTextInputType() const OVERRIDE;
  virtual TextInputMode GetTextInputMode() const OVERRIDE;
  virtual bool CanComposeInline() const OVERRIDE;

  virtual void AddObserver(InputMethodObserver* observer) OVERRIDE;
  virtual void RemoveObserver(InputMethodObserver* observer) OVERRIDE;

 protected:
  virtual void OnWillChangeFocusedClient(TextInputClient* focused_before,
                                         TextInputClient* focused) {}
  virtual void OnDidChangeFocusedClient(TextInputClient* focused_before,
                                        TextInputClient* focused) {}

  // Returns true if |client| is currently focused.
  bool IsTextInputClientFocused(const TextInputClient* client);

  // Checks if the focused text input client's text input type is
  // TEXT_INPUT_TYPE_NONE. Also returns true if there is no focused text
  // input client.
  bool IsTextInputTypeNone() const;

  // Convenience method to call the focused text input client's
  // OnInputMethodChanged() method. It'll only take effect if the current text
  // input type is not TEXT_INPUT_TYPE_NONE.
  void OnInputMethodChanged() const;

  // Convenience method to call delegate_->DispatchKeyEventPostIME().
  // Returns true if the event was processed
  bool DispatchKeyEventPostIME(const base::NativeEvent& native_event) const;

  // Convenience method to call delegate_->DispatchFabricatedKeyEventPostIME().
  // Returns true if the event was processed
  bool DispatchFabricatedKeyEventPostIME(EventType type,
                                         KeyboardCode key_code,
                                         int flags) const;

  // Convenience method to notify all observers of TextInputClient changes.
  void NotifyTextInputStateChanged(const TextInputClient* client);

  bool system_toplevel_window_focused() const {
    return system_toplevel_window_focused_;
  }

 private:
  void SetFocusedTextInputClientInternal(TextInputClient* client);

  internal::InputMethodDelegate* delegate_;
  TextInputClient* text_input_client_;
  bool is_sticky_text_input_client_;

  ObserverList<InputMethodObserver> observer_list_;

  bool system_toplevel_window_focused_;

  DISALLOW_COPY_AND_ASSIGN(InputMethodBase);
};

}  // namespace ui

#endif  // UI_BASE_IME_INPUT_METHOD_BASE_H_


text:
/*
 * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
 * Use is subject to license terms.
 */
/*
 * This file is part of Lustre, http://www.lustre.org/
 * Lustre is a trademark of Sun Microsystems, Inc.
 *
 * libcfs/include/libcfs/libcfs_time.h
 *
 * Time functions.
 *
 */

#ifndef __LIBCFS_TIME_H__
#define __LIBCFS_TIME_H__
/*
 * generic time manipulation functions.
 */

static inline unsigned long cfs_time_add(unsigned long t, long d)
{
	return (unsigned long)(t + d);
}

static inline unsigned long cfs_time_sub(unsigned long t1, unsigned long t2)
{
	return (unsigned long)(t1 - t2);
}

static inline int cfs_time_after(unsigned long t1, unsigned long t2)
{
	return time_before(t2, t1);
}

static inline int cfs_time_aftereq(unsigned long t1, unsigned long t2)
{
	return time_before_eq(t2, t1);
}

static inline unsigned long cfs_time_shift(int seconds)
{
	return cfs_time_add(cfs_time_current(), cfs_time_seconds(seconds));
}

static inline long cfs_timeval_sub(struct timeval *large, struct timeval *small,
				   struct timeval *result)
{
	long r = (long)(
		(large->tv_sec - small->tv_sec) * ONE_MILLION +
		(large->tv_usec - small->tv_usec));
	if (result != NULL) {
		result->tv_usec = r % ONE_MILLION;
		result->tv_sec = r / ONE_MILLION;
	}
	return r;
}

static inline void cfs_slow_warning(unsigned long now, int seconds, char *msg)
{
	if (cfs_time_after(cfs_time_current(),
			   cfs_time_add(now, cfs_time_seconds(15))))
		CERROR("slow %s "CFS_TIME_T" sec\n", msg,
		       cfs_duration_sec(cfs_time_sub(cfs_time_current(), now)));
}

#define CFS_RATELIMIT(seconds)				  \
({							      \
	/*						      \
	 * XXX nikita: non-portable initializer		 \
	 */						     \
	static time_t __next_message;		       \
	int result;					     \
								\
	if (cfs_time_after(cfs_time_current(), __next_message)) \
		result = 1;				     \
	else {						  \
		__next_message = cfs_time_shift(seconds);       \
		result = 0;				     \
	}						       \
	result;						 \
})

/*
 * helper function similar to do_gettimeofday() of Linux kernel
 */
static inline void cfs_fs_timeval(struct timeval *tv)
{
	struct timespec time;

	cfs_fs_time_current(&time);
	cfs_fs_time_usec(&time, tv);
}

/*
 * return valid time-out based on user supplied one. Currently we only check
 * that time-out is not shorted than allowed.
 */
static inline long cfs_timeout_cap(long timeout)
{
	if (timeout < CFS_TICK)
		timeout = CFS_TICK;
	return timeout;
}

#endif


text:
<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Proyectos;

/**
 * ProyectosSearch represents the model behind the search form about `app\models\Proyectos`.
 */
class ProyectosSearch extends Proyectos
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'id_programa','validacion','estado'], 'integer'],
            [['nombre', 'descripcion', 'colaboradores', 'fecha_inicio', 'fecha_fin'], 'safe'],
            [['presupuesto'], 'number'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Proyectos::find()->orderBy('id_programa,numeracion,id');

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'id_programa' => $this->id_programa,
            'presupuesto' => $this->presupuesto,
             'validacion' => $this->validacion,
             'estado' => $this->estado,
        ]);
        if (!empty($this->fecha_inicio)) {
            $query->andFilterWhere(['between', 'fecha_inicio', $this->fecha_inicio . '-01-01', $this->fecha_inicio . '-12-31']);
        }
        if (!empty($this->fecha_fin)) {
            $query->andFilterWhere(['between', 'fecha_fin', $this->fecha_fin . '-01-01', $this->fecha_fin . '-12-31']);
        }

        $query->andFilterWhere(['like', 'nombre', $this->nombre])
            ->andFilterWhere(['like', 'descripcion', $this->descripcion])
            ->andFilterWhere(['like', 'colaboradores', $this->colaboradores]);

        return $dataProvider;
    }
}


text:
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.twelvemonkeys</groupId>
        <artifactId>twelvemonkeys</artifactId>
        <version>3.5.1</version>
    </parent>
    <groupId>com.twelvemonkeys.common</groupId>
    <artifactId>common</artifactId>
    <packaging>pom</packaging>
    <name>TwelveMonkeys :: Common</name>
    <description>
        The TwelveMonkeys Common library. Contains common utility classes.
    </description>

    <modules>
        <module>common-lang</module>
        <module>common-io</module>
        <module>common-image</module>
    </modules>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>${project.groupId}</groupId>
                <artifactId>common-lang</artifactId>
                <version>${project.version}</version>
            </dependency>

            <dependency>
                <groupId>${project.groupId}</groupId>
                <artifactId>common-lang</artifactId>
                <version>${project.version}</version>
                <type>test-jar</type>
                <scope>test</scope>
            </dependency>

            <dependency>
                <groupId>${project.groupId}</groupId>
                <artifactId>common-io</artifactId>
                <version>${project.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.7</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>


text:
<?php

$_test_dir = realpath(dirname(__FILE__).'/..');

require_once(dirname(__FILE__).'/../../config/ProjectConfiguration.class.php');
$configuration = new ProjectConfiguration(realpath($_test_dir.'/..'));
include($configuration->getSymfonyLibDir().'/vendor/lime/lime.php');


text:
#ifndef ossimPlanetLatLonHud_HEADER
#define ossimPlanetLatLonHud_HEADER
#include <ossimPlanet/ossimPlanetLayer.h>
#include <osgText/Text>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/LineWidth>
#include <osg/Projection>
#include <osg/Camera>
#include <ossim/base/ossimString.h>
#include <ossimPlanet/ossimPlanetExport.h>
#include <ossimPlanet/ossimPlanetCompass.h>
#include <mutex>

class ossimPlanet;
namespace osg
{
   class LineWidth;
}
class OSSIMPLANET_EXPORT ossimPlanetLatLonHud : public ossimPlanetLayer
{
public:
   ossimPlanetLatLonHud();
   virtual void traverse(osg::NodeVisitor& nv);
   osg::Vec4 getCrossHairColor()const;
   osg::Vec4 getTextColor()const;
   void setCrosshairColor(const osg::Vec4& color);
   void setTextColor(const osg::Vec4& color);
   void setFont(const ossimString& fontFile);
   void setLatDisplayString(const ossimString& latDisplayString);
   void setLonDisplayString(const ossimString& lonDisplayString);
   void setCharacterSize(float size);
   void setViewport(osg::ref_ptr<osg::Viewport> viewport);
   void setAutoUpdateFlag(bool flag);
   void setCompassTexture(const ossimFilename& compass);
//   void setCompassTexture(const ossimFilename& ring,
//                          const ossimFilename& interior);

   virtual void execute(const ossimPlanetAction& action);

protected:
   void initialize();
   void updatePosition();
   osg::ref_ptr<osg::Camera> theCameraNode;
/*    osg::ref_ptr<osg::Projection> theProjection; */
   osg::ref_ptr<osgText::Text> thePositionText;

   osg::ref_ptr<osgText::Text> theLookText;
   osg::ref_ptr<osgText::Text> theEyeText;
   osg::ref_ptr<osgText::Text> theRangeText;

   osg::ref_ptr<osg::Geode> theGeode;
   osg::ref_ptr<osg::Viewport> theViewport;
   osg::ref_ptr<osg::Geometry> theCrosshair;
   osg::Vec3d theLineOfSiteLatLon;
   osg::Vec3d theNadirLatLon;
   double     theRange;
   double     theAltitude;
   osg::Vec4 theTextColor;
   osg::Vec4 theShadowTextColor;
   osg::Vec4 theCrosshairColor;
   osg::ref_ptr<osg::LineWidth> theCrosshairLineWidth;
   bool theAutoUpdateFlag;
   mutable bool theFontChanged;
   float theCharacterSize;
   bool theCharacterSizeDirtyFlag;
   ossimString theFontName;
   osg::ref_ptr<osgText::Font> theFont;

   ossimString theLookLabel;
   ossimString theEyeLabel;
   ossimString theRangeLabel;
   ossimString theLookDisplayString;
   ossimString theEyeDisplayString;

   ossimString theLatDisplayString;
   ossimString theLonDisplayString;

   bool theInitializedFlag;
   mutable std::recursive_mutex theMutex;
   bool theViewportChangedFlag;
   osg::ref_ptr<ossimPlanetCompass> theCompass;
};

#endif


text:
package org.jbpm.services.api;

public class ProcessDefinitionNotFoundException extends RuntimeException {

    private static final long serialVersionUID = 4139469799335673639L;

    public ProcessDefinitionNotFoundException(String message) {
        super(message);
    }

    public ProcessDefinitionNotFoundException(String message, Throwable t) {
        super(message, t);
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<widget
	xmlns="http://www.w3.org/ns/widgets"
	xmlns:rim="http://www.blackberry.com/ns/widgets"
	rim:header="RIM-Widget:rim/widget"
	xml:lang="en"
	id="localstorage7db657fe20749f1b97ca3a7f16e89a5"
	version="1.2.0.0">

	<name>localStorage</name>
	<description>How to use localStorage to make better bbUI apps</description>
	<author
		href="https://scrapps.org"
		rim:copyright="Copyright 2009-2013 SCrApps">
		SCrApps
	</author>

	<icon src="images/icon.png" />

	<rim:splash src="images/splashscreen-wide.jpg"/>
	<rim:splash src="images/splashscreen-tall.jpg"/>

	<content src="index.html" />

	<access uri="*" subdomains="true" />
	<feature id="blackberry.app">
		<param name="websecurity" value="disable" />
	</feature>

	<feature id="blackberry.app" />
	<feature id="blackberry.invoke" />
	<feature id="blackberry.invoke.card" />
	<feature id="blackberry.ui.toast" />
	<!--
	<feature id="blackberry.bbm.platform" />
	<feature id="blackberry.system" />
	<feature id="blackberry.pim.calendar" />
	-->

	<!--
	<feature id="blackberry.app">
		<param name="orientation" value="portrait" />
	</feature>
	-->

	<rim:permissions>
		<!--
		<rim:permit>bbm_connect</rim:permit>
		<rim:permit>access_pimdomain_calendars</rim:permit>
		<rim:permit>access_shared</rim:permit>
		<rim:permit>use_camera</rim:permit>
		<rim:permit>read_device_identifying_information</rim:permit>
		<rim:permit>read_geolocation</rim:permit>
		<rim:permit>record_audio</rim:permit>
		<rim:permit>_sys_use_consumer_push</rim:permit>
		<rim:permit>run_when_backgrounded</rim:permit>
		<rim:permit>access_location_services</rim:permit>
		<rim:permit>access_pimdomain_messages</rim:permit>
		<rim:permit>access_pimdomain_contacts</rim:permit>
		<rim:permit>access_pimdomain_notebooks</rim:permit>
		<rim:permit>post_notifications</rim:permit>
		<rim:permit>access_sms_mms</rim:permit>
		-->
	</rim:permissions>

  </widget>


text:
package ro.rural.booking.persistence;

import org.springframework.data.mongodb.repository.MongoRepository;
import ro.rural.booking.entities.Client;
import ro.rural.booking.entities.Reservation;

import java.util.List;

/**
 * Created by stefan.durla on 24/06/2017.
 */
public interface ReservationRepository extends MongoRepository<Reservation, String> {
}


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="whipsaw">
        <note>
            Frames file for 'whipsaw' based on sentences in wsj.  No Verbnet
            entry at the moment, and I'm not even entirely certain of the
            meaning.  Syntax is pretty straightforward, though.
        </note>

        <roleset id="whipsaw.01" name="move back and forth violently?" vncls="-">
            <roles>
                <role descr="mover" n="0"/>
                <role descr="thing moved" n="1"/>
            </roles>

            <example name="active">
                <inflection aspect="ns" form="full" person="ns" tense="present" voice="active"/>
                <text>
                    Political and currency gyrations can whipsaw the funds.
                </text>
                <arg n="0">Political and currency gyrations</arg>
                <arg f="MOD" n="M">can</arg>
                <rel>whipsaw</rel>
                <arg n="1">the funds</arg>
            </example>

            <example name="passive">
                <inflection aspect="progressive" form="participle" person="ns" tense="ns" voice="passive"/>
                <text>
                    After *trace*-1 being whipsawed *trace*-1 by a volatile stock market,
                    [Treasury bonds]-1 closed higher.
                </text>
                <rel>whipsawed</rel>
                <arg n="1">*trace*</arg>
                <arg n="0">by a volatile stock market</arg>
            </example>

            <note>
            </note>

        </roleset>
    </predicate>
</frameset>