text:
<?xml version="1.0" encoding="utf-8"?>
<Jobs>
  <ApplicationJob xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Guid="dcc0b457-9a13-468b-ad12-1a9a348a2428">
    <WebsiteUrl />
    <UserAgent />
    <UserNotes />
    <LastFileSize>15275278</LastFileSize>
    <LastFileDate>2016-02-04T19:41:13.2478348</LastFileDate>
    <IgnoreFileInformation>false</IgnoreFileInformation>
    <DownloadBeta>Default</DownloadBeta>
    <DownloadDate xsi:nil="true" />
    <CheckForUpdatesOnly>false</CheckForUpdatesOnly>
    <VariableChangeIndicator />
    <HashType>None</HashType>
    <CanBeShared>true</CanBeShared>
    <ShareApplication>false</ShareApplication>
    <ExclusiveDownload>false</ExclusiveDownload>
    <HttpReferer />
    <SetupInstructions />
    <Variables>
      <item>
        <key>
          <string>nopush</string>
        </key>
        <value>
          <UrlVariable>
            <RegexRightToLeft>false</RegexRightToLeft>
            <VariableType>Textual</VariableType>
            <Regex />
            <TextualContent>--nopush</TextualContent>
            <Name>nopush</Name>
          </UrlVariable>
        </value>
      </item>
      <item>
        <key>
          <string>cscript</string>
        </key>
        <value>
          <UrlVariable>
            <RegexRightToLeft>false</RegexRightToLeft>
            <VariableType>Textual</VariableType>
            <Regex />
            <TextualContent>2</TextualContent>
            <Name>cscript</Name>
          </UrlVariable>
        </value>
      </item>
      <item>
        <key>
          <string>url</string>
        </key>
        <value>
          <UrlVariable>
            <RegexRightToLeft>false</RegexRightToLeft>
            <VariableType>Textual</VariableType>
            <Regex />
            <TextualContent>http://www.eventghost.org/downloads/{getUrl}</TextualContent>
            <Name>url</Name>
          </UrlVariable>
        </value>
      </item>
      <item>
        <key>
          <string>getUrl</string>
        </key>
        <value>
          <UrlVariable>
            <RegexRightToLeft>false</RegexRightToLeft>
            <VariableType>RegularExpression</VariableType>
            <Regex>[^ "'<>\*]+\.exe</Regex>
            <Url>http://www.eventghost.org/downloads/</Url>
            <Name>getUrl</Name>
          </UrlVariable>
        </value>
      </item>
      <item>
        <key>
          <string>versionFull</string>
        </key>
        <value>
          <UrlVariable>
            <RegexRightToLeft>false</RegexRightToLeft>
            <VariableType>Textual</VariableType>
            <Regex />
            <TextualContent>{getUrl:regex:(?<=EventGhost_)[\d\.r]{3,\}(?=_)}</TextualContent>
            <Name>versionFull</Name>
          </UrlVariable>
        </value>
      </item>
      <item>
        <key>
          <string>version</string>
        </key>
        <value>
          <UrlVariable>
            <RegexRightToLeft>false</RegexRightToLeft>
            <VariableType>Textual</VariableType>
            <Regex />
            <TextualContent>{versionFull:replace:r:}</TextualContent>
            <Name>version</Name>
          </UrlVariable>
        </value>
      </item>
    </Variables>
    <ExecuteCommand />
    <ExecutePreCommand />
    <ExecuteCommandType>Batch</ExecuteCommandType>
    <ExecutePreCommandType>Batch</ExecutePreCommandType>
    <Category />
    <SourceType>FixedUrl</SourceType>
    <PreviousLocation>F:\exe\EventGhost_0.4.1.r1722_Setup.exe</PreviousLocation>
    <DeletePreviousFile>false</DeletePreviousFile>
    <Enabled>true</Enabled>
    <FileHippoId />
    <LastUpdated>2016-02-04T19:41:13.2478348</LastUpdated>
    <TargetPath>{workdir}\</TargetPath>
    <FixedDownloadUrl>{url}</FixedDownloadUrl>
    <Name>eventghost</Name>
  </ApplicationJob>
</Jobs>


text:
namespace syncer {

CommitRequestData::CommitRequestData() = default;

CommitRequestData::~CommitRequestData() = default;

CommitResponseData::CommitResponseData() = default;

CommitResponseData::CommitResponseData(const CommitResponseData& other) =
    default;

CommitResponseData::CommitResponseData(CommitResponseData&&) = default;

CommitResponseData& CommitResponseData::operator=(const CommitResponseData&) =
    default;

CommitResponseData& CommitResponseData::operator=(CommitResponseData&&) =
    default;

CommitResponseData::~CommitResponseData() = default;

FailedCommitResponseData::FailedCommitResponseData() = default;

FailedCommitResponseData::FailedCommitResponseData(
    const FailedCommitResponseData& other) = default;

FailedCommitResponseData::FailedCommitResponseData(FailedCommitResponseData&&) =
    default;

FailedCommitResponseData& FailedCommitResponseData::operator=(
    const FailedCommitResponseData&) = default;

FailedCommitResponseData& FailedCommitResponseData::operator=(
    FailedCommitResponseData&&) = default;

FailedCommitResponseData::~FailedCommitResponseData() = default;

UpdateResponseData::UpdateResponseData() = default;

UpdateResponseData::~UpdateResponseData() = default;

size_t EstimateMemoryUsage(const CommitRequestData& value) {
  using base::trace_event::EstimateMemoryUsage;
  size_t memory_usage = 0;
  memory_usage += EstimateMemoryUsage(value.entity);
  memory_usage += EstimateMemoryUsage(value.specifics_hash);
  return memory_usage;
}

size_t EstimateMemoryUsage(const UpdateResponseData& value) {
  using base::trace_event::EstimateMemoryUsage;
  size_t memory_usage = 0;
  memory_usage += EstimateMemoryUsage(value.entity);
  memory_usage += EstimateMemoryUsage(value.encryption_key_name);
  return memory_usage;
}

}  // namespace syncer

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd"
             version="2.2">

    <persistence-unit name="odpPersistenceUnit">
        <class>co.edu.sena.ejemplo.model.jpa.entities.AprendizEntity</class>
        <class>co.edu.sena.ejemplo.model.jpa.entities.ClienteEntity</class>
        <class>co.edu.sena.ejemplo.model.jpa.entities.ClienteHasRolEntity</class>
        <class>co.edu.sena.ejemplo.model.jpa.entities.CompetenciaEntity</class>
        <class>co.edu.sena.ejemplo.model.jpa.entities.EstadoFormacionEntity</class>
        <class>co.edu.sena.ejemplo.model.jpa.entities.FichaEntity</class>
        <class>co.edu.sena.ejemplo.model.jpa.entities.FichaHasListaEntity</class>
        <class>co.edu.sena.ejemplo.model.jpa.entities.GrupoProyectoEntity</class>
        <class>co.edu.sena.ejemplo.model.jpa.entities.InstructorFichaEntity</class>
        <class>co.edu.sena.ejemplo.model.jpa.entities.InstructorHasTrimestreEntity</class>
        <class>co.edu.sena.ejemplo.model.jpa.entities.ItemCheckerEntity</class>
        <class>co.edu.sena.ejemplo.model.jpa.entities.JornadaEntity</class>
        <class>co.edu.sena.ejemplo.model.jpa.entities.ListaChequeoEntity</class>
        <class>co.edu.sena.ejemplo.model.jpa.entities.LogAuditoriaEntity</class>
        <class>co.edu.sena.ejemplo.model.jpa.entities.LogErrorEntity</class>
        <class>co.edu.sena.ejemplo.model.jpa.entities.ObservacionGeneralEntity</class>
        <class>co.edu.sena.ejemplo.model.jpa.entities.ObservacionItemEntity</class>
        <class>co.edu.sena.ejemplo.model.jpa.entities.ProgramaEntity</class>
        <class>co.edu.sena.ejemplo.model.jpa.entities.RaeEntity</class>
        <class>co.edu.sena.ejemplo.model.jpa.entities.RaeHasTrimestreEntity</class>
        <class>co.edu.sena.ejemplo.model.jpa.entities.RespuestaGrupoEntity</class>
        <class>co.edu.sena.ejemplo.model.jpa.entities.RolEntity</class>
        <class>co.edu.sena.ejemplo.model.jpa.entities.ServidorCorreoElectronicoEntity</class>
        <class>co.edu.sena.ejemplo.model.jpa.entities.TipoDocumentoEntity</class>
        <class>co.edu.sena.ejemplo.model.jpa.entities.TipoInstructorEntity</class>
        <class>co.edu.sena.ejemplo.model.jpa.entities.TrimestreEntity</class>
        <class>co.edu.sena.ejemplo.model.jpa.entities.UsuarioEntity</class>
        <class>co.edu.sena.ejemplo.model.jpa.entities.ValoracionEntity</class>
        <properties>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:4306/jpa"/>
            <property name="javax.persistence.jdbc.user" value="root"/>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
            <property name="javax.persistence.jdbc.password" value="123456789"/>
            <property name="javax.persistence.schema-generation.database.action" value="create"/>
            <property name="eclipselink.logging.level.sql" value="ALL"/>
        </properties>
    </persistence-unit>
</persistence>


text:
// -----------------------------------------------------------------------
//  <copyright file="FunctionConfiguration.cs" company="">
//      Copyright (c) 2014-2015 OSky. All rights reserved.
//  </copyright>
//  <last-editor>Lmf</last-editor>
//  <last-date>2015-07-14 3:29</last-date>
// -----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using OSky.Core.Data.Entity;
using OSky.Core.Security;

namespace OSky.UI.ModelConfigurations.Security
{
    /// <summary>
    /// 实体映射类——功能信息
    /// </summary>
    public class FunctionConfiguration : EntityConfigurationBase<Function, Guid>
    { }
}


text:
from requestbuilder import Arg

from euca2ools.commands.elasticloadbalancing import ELBRequest

def _tag_key_only(key):
    return {'Key': key}

class RemoveTags(ELBRequest):
    DESCRIPTION = 'Remove one or more tags from a load balancer'
    ARGS = [Arg('LoadBalancerNames.member.1', metavar='ELB',
                help='name of the load balancer to untag (required)'),
            Arg('-t', '--tag', dest='Tags.member', required=True,
                action='append', metavar='KEY', type=_tag_key_only,
                help='name of each tag to add (required)')]


text:
case class A private (i: Int)
object A {
  def a = A(1).copy(2) // apply and copy are accessible in companion
}

case class B private (i: Int) { // no user-defined companion object, should compile
  def b = B(1).copy(2) // apply and copy are accessible
}

object qualified_private {
  case class A private[qualified_private] (i: Int)
  object A {
    def a = A(1).copy(2) // apply and copy are accessible in companion
  }

  def a = A(1).copy(2) // apply and copy are accessible in qualified_private object

  case class B private[qualified_private] (i: Int) { // no user-defined companion object, should compile
    def b = B(1).copy(2) // apply and copy are accessible
  }

  def b = B(1).copy(2) // apply and copy are accessible in qualified_private object
}

case class C protected (i: Int)
class CSub extends C(1) {
  def c = copy(2) // copy is accessible in subclass
}
object CTest {
  def c = C(1) // apply is public
}

object qualified_protected {
  case class C protected[qualified_protected] (i: Int)
  class CSub extends C(1) {
    def c = copy(2) // copy is accessible in subclass
  }
  object CTest {
    def c = C(1) // apply is public
    def checkExtendsFunction: Int => C = C // companion extends (Int  => C)
  }

  def c = C(1).copy(2)
}
object CQualifiedTest {
  def c = qualified_protected.C(1) // apply is public
}


text:
require 'sinatra/base'
require 'base64'
require 'cdo/db'
require 'cdo/rack/request'

class ChannelsApi < Sinatra::Base

  helpers do
    [
      'core.rb',
      'storage_apps.rb',
      'storage_id.rb',
    ].each do |file|
      load(CDO.dir('shared', 'middleware', 'helpers', file))
    end
  end

  if rack_env?(:staging) || rack_env?(:development)
    get '/v3/channels/debug' do
      dont_cache
      content_type :json
      JSON.pretty_generate({
        storage_id:storage_id('user'),
      })
    end
  end

  #
  #
  # CHANNELS
  #
  #

  #
  # GET /v3/channels
  #
  # Returns all of the channels registered to the current user
  #
  get '/v3/channels' do
    dont_cache
    content_type :json
    StorageApps.new(storage_id('user')).to_a.to_json
  end

  #
  # POST /v3/channels
  #
  # Create a channel.
  #
  post '/v3/channels' do
    unsupported_media_type unless request.content_type.to_s.split(';').first == 'application/json'
    unsupported_media_type unless request.content_charset.to_s.downcase == 'utf-8'

    begin
      data = JSON.parse(request.body.read)
    rescue JSON::ParserError
      bad_request
    end
    bad_request unless data.is_a? Hash

    timestamp = Time.now
    id = StorageApps.new(storage_id('user')).create(data.merge('createdAt' => timestamp, 'updatedAt' => timestamp), request.ip)

    redirect "/v3/channels/#{id}", 301
  end

  #
  # GET /v3/channels/<channel-id>
  #
  # Returns a channel by id.
  #
  get %r{/v3/channels/([^/]+)$} do |id|
    dont_cache
    content_type :json
    StorageApps.new(storage_id('user')).get(id).to_json
  end

  #
  # DELETE /v3/channels/<channel-id>
  #
  # Deletes a channel by id.
  #
  delete %r{/v3/channels/([^/]+)$} do |id|
    dont_cache
    StorageApps.new(storage_id('user')).delete(id)
    no_content
  end
  post %r{/v3/channels/([^/]+)/delete$} do |name|
    call(env.merge('REQUEST_METHOD'=>'DELETE', 'PATH_INFO'=>File.dirname(request.path_info)))
  end

  #
  # POST /v3/channels/<channel-id>
  #
  # Update an existing channel.
  #
  post %r{/v3/channels/([^/]+)$} do |id|
    unsupported_media_type unless request.content_type.to_s.split(';').first == 'application/json'
    unsupported_media_type unless request.content_charset.to_s.downcase == 'utf-8'

    value = JSON.parse(request.body.read)
    bad_request unless value.is_a? Hash
    value = value.merge('updatedAt' => Time.now)

    StorageApps.new(storage_id('user')).update(id, value, request.ip)

    dont_cache
    content_type :json
    value.to_json
  end
  patch %r{/v3/channels/([^/]+)$} do |id|
    call(env.merge('REQUEST_METHOD'=>'POST'))
  end
  put %r{/v3/channels/([^/]+)$} do |id|
    call(env.merge('REQUEST_METHOD'=>'PATCH'))
  end
end


text:
<?php

namespace Emayk\Ics\Repo\Orderstatus;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use \Response;
use \Input;

class OrderstatusEloquent implements OrderstatusInterface{
    protected $orderstatus;
    function __construct(Orderstatus $orderstatus)
    {
        $this->orderstatus = $orderstatus;
    }

    /**
    *
    * Mendapatkan Record Orderstatus berdasarkan ID yang diberikan
    * @param  int $id ID Record
    * @return Model Record Orderstatus
    **/

    public function find($id){
        return $this->orderstatus->find($id);
    }

    /**
     * Mendapatkan Semua Orderstatus
     * @return mixed
     */
    public function all()
    {
        $page = \Input::get('page');
			 $limit = \Input::get('limit',1);
			 $start = \Input::get('start',1);
        $orderstatus = $this->orderstatus
            ->orderBy('id','DESC')
            ->skip($start)
            ->take($limit)
            ->get()->toArray();
        $total = $this->orderstatus
            ->all()->count();

        $orderstatuss = array(
            'success' => true,
            'results' => $orderstatus,
            'total' => $total
        );

        return Response::json($orderstatuss)
            ->setCallback(\Input::get('callback'));

    }

    /**
     *
     * Proses Simpan Orderstatus
     *
     * @return mixed
     */
    public function store()
    {
        if (!$this->hasAccess()) {
            return Response::json(
                      array(
                        'success' => false,
                        'reason'  => 'Action Need Login First',
                        'results' => null
                        ))->setCallback();
        }
        /*==========  Sesuaikan dengan Field di table  ==========*/
        // $this->orderstatus->name = Input::get('name');
        // $this->orderstatus->info = Input::get('info');
        // $this->orderstatus->uuid = uniqid('New_');
        // $this->orderstatus->createby_id = \Auth::user()->id;
        // $this->orderstatus->lastupdateby_id = \Auth::user()->id;
        // $this->orderstatus->created_at = new Carbon();
        // $this->orderstatus->updated_at = new Carbon();
        $saved = $this->orderstatus->save() ? true : false ;
        return Response::json(array(
            'success' => $saved,
            'results' => $this->orderstatus->toArray()
        ))->setCallback();
    }

    /**
     * Menghapus Orderstatus
     *
     * @param $id
     * @return mixed
     *
     */
    public function delete($id)
    {

        if ($this->hasAccess())
        {
            $deleted = $this->orderstatus
                ->find($id)
                ->delete();

            return \Icsoutput::toJson(array(
                'results' => $deleted
            ),$deleted);

        }else{
            return \Icsoutput::toJson(array(
                'results' => false,
                'reason' => 'Dont Have Access to Delete '
            ),false);
        }
    }

    /**
     * Update Informasi [[cName]]
     *
     * @param $id
     * @return mixed
     */
    public function update($id)
    {
        $db = $this->orderstatus->find($id);
        /*==========  Sesuaikan  ==========*/
        // $db->name = Input::get('name');
        // $db->info = Input::get('info');
        $db->uuid = uniqid('Update_');
        return ($db->save())
            ? \Icsoutput::msgSuccess( $db->toArray() )
            : \Icsoutput::msgError(array('reason' => 'Cannot Update'));
    }

    /**
    *
    * Apakah Sudah Login
    *
    * @return boolean
    *
    **/
    protected function  hasAccess()
    {
        return (!Auth::guest());
    }

    /**
    *
    * Menampilkan Page Create data Orderstatus
    *
    **/

   public function create()
    {
        // TODO: Implement create() method.
    }

    /**
     * Menampilkan Resource
     *
     * @param  int  $id
     * @return Response
     */
   public function show($id)
    {
        // TODO: Implement show() method.
    }
    /**
     * Menampilkan Data Untuk di edit
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {
        // TODO: Implement edit() method.
    }

    /**
     * Remove Storage
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        return $this->delete($id);
    }

}


text:
<TITLE>Review for Ghost Dog: The Way of the Samurai (1999)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Ghost Dog: The Way of the Samurai (1999)

reviewed by
Ian Waldron-Mantgani

 Ghost Dog: The Way of the Samurai      ***

Rated on a 4-star scale
Screening venue: Cornerhouse (Manchester)
Released in the UK by Film Four on May 5, 2000; certificate 15; 116 minutes;
countries of origin France/Germany/Japan/USA; aspect ratio 1.85:1

Directed by Jim Jarmusch; produced by Richard Guay, Jim Jarmusch.
Written by Jim Jarmusch.
Photographed by Robby Müller; edited by Jay Rabinowitz.

CAST.....
Forest Whitaker..... Ghost Dog
John Tormey..... Louie Bonacelli
Cliff Gorman..... Sonny Valerio
Henry Silva..... Ray Vargo
Isaach de Bankolé..... Raymond
Tricia Vessey..... Louise Vargo
Victor Argo..... Vinny
Gene Ruffini..... old consigliere
Richard Portnow..... Handsome Frank
Camille Winbush..... Pearline, the little girl

The hit man has no name. People in the neighbourhood just call him 'ghost
dog'. He lives on the roof of a New York City apartment block, in an iron
shack, surrounded by pigeons. His only friend is a Haitian ice-cream vendor
who does not speak his language. Completely disconnected from reality, he
uses the code of ancient samurai warriors as a guide on how to conduct his
life and work.

"Ghost Dog: The Way of the Samurai" was written and directed by Jim Jarmusch,
the perfect and perhaps only filmmaker for this material. He's fascinated by
the quietly insane, or at least the quirky outsiders, of society. Think of
the layabouts in "Stranger Than Paradise", the mixed bag of oddballs in
"Mystery Train", the trio of plodding inept crooks in "Down By Law". Good old
Jim has dedicated his career to looking at nutcases with a tender grin.

In "Ghost Dog", he makes clear that the plot will contain no surprises, so he
can devote his attention to observing little details. The early scenes show
us that Ghost Dog (Forest Whitaker) does contract killings for a gang of
Italian mobsters. He feels indebted to one of their number for saving his
life when he was a kid. For reasons I wasn't really paying attention to, it
is decided that Ghost Dog himself must die, and by the end of the movie, of
course, this is what's going to happen.

As ever, Jarmusch's pace is slow, and his camera stays pretty much
stationary. Scenes are deliberately flat, lending a poignancy to the pathetic
atmosphere all the characters live in, and also a comedic contrast to the
topsy-turvy nature of the things going on. Realistic foibles are thrust onto
action-adventure set-ups: The film is full of little moments like the one in
which a pair of tough-talking gangsters sit around in serious, contemplative
confusion at why Ghost Dog communicates with them by carrier pigeon. Try to
imagine the scene in "Pulp Fiction" where the two guys are nitpicking about
how to clean their blood-drenched car, spun out to feature length.

COPYRIGHT(c) 2000 Ian Waldron-Mantgani
Please visit, and encourage others to visit, the UK Critic's website, which
is located at http://members.aol.com/ukcritic

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

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

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

Broken URLs inthe reviews are the responsibility of the author.

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

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


text:
package io.sip3.tapir.captain.util;

import org.pcap4j.packet.IpV4Packet;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by agafox.
 */
public class FragmentedPackets {

    private final Map<Integer, IpV4Packet> packets = new TreeMap<>();

    private boolean isLastPacketReceived;

    public void addPacket(IpV4Packet p) {
        packets.put(8 * p.getHeader().getFragmentOffset(), p);
        isLastPacketReceived = !p.getHeader().getMoreFragmentFlag();
    }

    public boolean isAllPacketsReceived() {
        if (!isLastPacketReceived) {
            return false;
        }
        int expectedOffset = 0;
        for (Map.Entry<Integer, IpV4Packet> entry : packets.entrySet()) {
            int offset = entry.getKey();
            if (offset != expectedOffset) {
                return false;
            }
            IpV4Packet p = entry.getValue();
            expectedOffset = offset + p.getHeader().getTotalLength() - 4 * p.getHeader().getIhl();
        }
        return true;
    }

    public List<IpV4Packet> getPackets() {
        return new ArrayList<>(packets.values());
    }
}


text:
<?php

namespace Drupal\Tests\ckeditor5\Kernel;

use Drupal\ckeditor5\Plugin\Editor\CKEditor5;
use Drupal\editor\Entity\Editor;
use Drupal\filter\Entity\FilterFormat;
use Drupal\KernelTests\KernelTestBase;
use Symfony\Component\Validator\ConstraintViolation;

/**
 * @covers \Drupal\ckeditor5\Plugin\CKEditor5PluginManager::getCKEditor5PluginConfig()
 * @group ckeditor5
 * @internal
 */
class WildcardHtmlSupportTest extends KernelTestBase {

  /**
   * {@inheritdoc}
   */
  protected static $modules = [
    'ckeditor5',
    'filter',
    'editor',
  ];

  /**
   * The manager for "CKEditor 5 plugin" plugins.
   *
   * @var \Drupal\ckeditor5\Plugin\CKEditor5PluginManagerInterface
   */
  protected $manager;

  /**
   * {@inheritdoc}
   */
  protected function setUp(): void {
    parent::setUp();
    $this->manager = $this->container->get('plugin.manager.ckeditor5.plugin');
  }

  /**
   * @covers \Drupal\ckeditor5\Plugin\CKEditor5Plugin\SourceEditing::getDynamicPluginConfig()
   * @covers \Drupal\ckeditor5\Plugin\CKEditor5PluginManager::getCKEditor5PluginConfig()
   * @dataProvider providerGhsConfiguration
   */
  public function testGhsConfiguration(string $filter_html_allowed, array $source_editing_tags, array $expected_ghs_configuration, ?array $additional_toolbar_items = []): void {
    FilterFormat::create([
      'format' => 'test_format',
      'name' => 'Test format',
      'filters' => [
        'filter_html' => [
          'status' => TRUE,
          'settings' => [
            'allowed_html' => $filter_html_allowed,
          ],
        ],
      ],
    ])->save();
    $editor_config = [
      'editor' => 'ckeditor5',
      'format' => 'test_format',
      'settings' => [
        'toolbar' => [
          'items' => array_merge(['sourceEditing'], $additional_toolbar_items),
        ],
        'plugins' => [
          'ckeditor5_sourceEditing' => [
            'allowed_tags' => $source_editing_tags,
          ],
        ],
      ],
      'image_upload' => [
        'status' => FALSE,
      ],
    ];
    if (in_array('alignment', $additional_toolbar_items, TRUE)) {
      $editor_config['settings']['plugins']['ckeditor5_alignment'] = [
        'enabled_alignments' => ['left', 'center', 'right', 'justify'],
      ];
    }

    $editor = Editor::create($editor_config);
    $editor->save();
    $this->assertSame([], array_map(
      function (ConstraintViolation $v) {
        return (string) $v->getMessage();
      },
      iterator_to_array(CKEditor5::validatePair(
        Editor::load('test_format'),
        FilterFormat::load('test_format')
      ))
    ));
    $config = $this->manager->getCKEditor5PluginConfig($editor);
    $ghs_configuration = $config['config']['htmlSupport']['allow'];
    // The first two entries in the GHS configuration are from the
    // `ckeditor5_globalAttributeDir` and `ckeditor5_globalAttributeLang`
    // plugins. They are out of scope for this test, so omit them.
    $ghs_configuration = array_slice($ghs_configuration, 2);
    $this->assertEquals($expected_ghs_configuration, $ghs_configuration);
  }

  public function providerGhsConfiguration(): array {
    return [
      'empty source editing' => [
        '

',
        [],
        [],
      ],
      'without wildcard' => [
        '

',
        ['
'],
        [
          [
            'name' => 'div',
            'attributes' => [
              [
                'key' => 'data-llama',
                'value' => TRUE,
              ],
            ],
          ],
        ],
        ['link', 'blockQuote'],
      ],
      '<$text-container> minimal configuration' => [
        '

',
        ['<$text-container data-llama>'],
        [
          [
            'name' => 'p',
            'attributes' => [
              [
                'key' => 'data-llama',
                'value' => TRUE,
              ],
            ],
          ],
        ],
      ],
      '<$text-container> from multiple plugins' => [
        '

',
        ['<$text-container data-llama>'],
        [
          [
            'name' => 'p',
            'attributes' => [
              [
                'key' => 'data-llama',
                'value' => TRUE,
              ],
            ],
            'classes' => [
              'regexp' => [
                'pattern' => '/^(text-align-left|text-align-center|text-align-right|text-align-justify)$/',
              ],
            ],
          ],
        ],
        ['alignment'],
      ],
      '<$text-container> with attribute from multiple plugins' => [
        '

',
        ['<$text-container data-llama>', '
'],
        [
          [
            'name' => 'p',
            'classes' => TRUE,
          ],
          [
            'name' => 'p',
            'attributes' => [
              [
                'key' => 'data-llama',
                'value' => TRUE,
              ],
            ],
            'classes' => [
              'regexp' => [
                'pattern' => '/^(text-align-left|text-align-center|text-align-right|text-align-justify)$/',
              ],
            ],
          ],
        ],
        ['alignment'],
      ],
      '<$text-container> realistic configuration' => [
        '

  ',
        ['<$text-container data-llama>', '
', '', ''],
        [
          [
            'name' => 'div',
          ],
          [
            'name' => 'mark',
          ],
          [
            'name' => 'abbr',
            'attributes' => [
              [
                'key' => 'title',
                'value' => TRUE,
              ],
            ],
          ],
          [
            'name' => 'p',
            'attributes' => [
              [
                'key' => 'data-llama',
                'value' => TRUE,
              ],
            ],
          ],
          [
            'name' => 'div',
            'attributes' => [
              [
                'key' => 'data-llama',
                'value' => TRUE,
              ],
            ],
          ],
        ],
        ['link', 'blockQuote'],
      ],
    ];
  }

}


text:
from builtins import object
class Module(object):

    def __init__(self, mainMenu, params=[]):

        # metadata info about the module, not modified during runtime
        self.info = {
            # name for the module that will appear in module menus
            'Name': 'SearchEmail',

            # list of one or more authors for the module
            'Author': ['@harmj0y'],

            # more verbose multi-line description of the module
            'Description': ("Searches for Mail .emlx messages, optionally only returning "
                            "messages with the specified SearchTerm."),

            'Software': '',

            'Techniques': ['T1114'],

            # True if the module needs to run in the background
            'Background' : False,

            # File extension to save the file as
            'OutputExtension' : "",

            # if the module needs administrative privileges
            'NeedsAdmin' : False,

            # True if the method doesn't touch disk/is reasonably opsec safe
            'OpsecSafe' : True,

            # the module language
            'Language' : 'python',

            # the minimum language version needed
            'MinLanguageVersion' : '2.6',

            # list of any references/other comments
            'Comments': [
                "https://davidkoepi.wordpress.com/2013/07/06/macforensics5/"
            ]
        }

        # any options needed by the module, settable during runtime
        self.options = {
            # format:
            #   value_name : {description, required, default_value}
            'Agent' : {
                # The 'Agent' option is the only one that MUST be in a module
                'Description'   :   'Agent to execute module on.',
                'Required'      :   True,
                'Value'         :   ''
            },
            'SearchTerm' : {
                # The 'Agent' option is the only one that MUST be in a module
                'Description'   :   "Term to grep for in email messages.",
                'Required'      :   False,
                'Value'         :   ''
            }
        }

        # save off a copy of the mainMenu object to access external functionality
        #   like listeners/agent handlers/etc.
        self.mainMenu = mainMenu

        # During instantiation, any settable option parameters
        #   are passed as an object set to the module and the
        #   options dictionary is automatically set. This is mostly
        #   in case options are passed on the command line
        if params:
            for param in params:
                # parameter format is [Name, Value]
                option, value = param
                if option in self.options:
                    self.options[option]['Value'] = value

    def generate(self, obfuscate=False, obfuscationCommand=""):

        searchTerm = self.options['SearchTerm']['Value']

        script = "cmd = \"find /Users/ -name *.emlx 2>/dev/null"

        if searchTerm != "":
            script += "|xargs grep -i '"+searchTerm+"'\""
        else:
            script += "\""

        script += "\nrun_command(cmd)"

        return script


text:
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <string name="app_name">OcrBall</string>
    <string name="button_camera_scan">Camera\nScan</string>
    <string name="button_select_image">Select\nImage</string>
    <string name="button_active_ocr">Active\nOcrball</string>
    <string name="default_prompt">OcrBall is a project to help recognise the characters in the picture!\n\nPlease select one image!</string>
    <string name="resault_title">The ocr resault is:</string>
    <string name="resault_content">This is content!</string>
    <string name="back">back</string>
    <string name="screenshot">screenshot</string>

    <string name="action_menu_platform_title">Platform - <xliff:g>%s</xliff:g></string>
    <string name="platform_td">Tesseract</string>
    <string name="platform_bd">Baidu</string>
    <string name="platform_google">Google</string>
    <string name="platform_dialog_title">Choce one platform for your OCR!</string>

    <string name="action_menu_language_title">Launuage - <xliff:g>%s</xliff:g></string>
    <string name="language_eng">eng</string>
    <string name="language_chi_sim">chi_sim</string>
    <string name="language_chi_tra">chi_tra</string>
    <string name="language_dialog_title">Choce one platform for your OCR!</string>

    <string name="title_activity_screen_shot">ScreenShotActivity</string>
    <string name="can_not_capture_under_5_0">System under 5.0 does not support screenshots</string>
    <string name="screen_capture_fail">Sorry for capturing screen fail</string>
    <string name="file_notexist">This screenshot file is not found!</string>
    <string name="file_savesuccess">"screenshot save success"</string>

</resources>


text:
using System.Reflection;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Tests")]
[assembly: AssemblyCulture("")]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7e62e485-0ebe-44c4-8449-4710dd98bfbe")]


text:
// See http://www.boost.org for most recent version.

#ifndef BOOST_SAFE_MJM012402_HPP
#define BOOST_SAFE_MJM012402_HPP

#include <Multiprocessing.h>

namespace boost {

namespace threads {

namespace mac {

namespace detail {

// these functions are used to wain in an execution context-independent manor.  All of these
//  functions are both MP- and ST-safe.

OSStatus safe_wait_on_semaphore(MPSemaphoreID pSemaphoreID, Duration lDuration);
OSStatus safe_enter_critical_region(MPCriticalRegionID pCriticalRegionID, Duration lDuration, MPCriticalRegionID pCriticalRegionCriticalRegionID = kInvalidID);
OSStatus safe_wait_on_queue(MPQueueID pQueueID, void **pParam1, void **pParam2, void **pParam3, Duration lDuration);
OSStatus safe_delay_until(AbsoluteTime *pWakeUpTime);

} // namespace detail

} // namespace mac

} // namespace threads

} // namespace boost

#endif // BOOST_SAFE_MJM012402_HPP


text:
package io.reactivex.internal.operators.mixed;

import java.util.concurrent.atomic.*;

import io.reactivex.*;
import io.reactivex.disposables.Disposable;
import io.reactivex.exceptions.Exceptions;
import io.reactivex.functions.Function;
import io.reactivex.internal.disposables.DisposableHelper;
import io.reactivex.internal.functions.ObjectHelper;
import io.reactivex.internal.fuseable.SimplePlainQueue;
import io.reactivex.internal.queue.SpscLinkedArrayQueue;
import io.reactivex.internal.util.*;
import io.reactivex.plugins.RxJavaPlugins;

/**
 * Maps each upstream item into a {@link SingleSource}, subscribes to them one after the other terminates
 * and relays their success values, optionally delaying any errors till the main and inner sources
 * terminate.
 * <p>History: 2.1.11 - experimental
 * @param <T> the upstream element type
 * @param <R> the output element type
 * @since 2.2
 */
public final class ObservableConcatMapSingle<T, R> extends Observable<R> {

    final Observable<T> source;

    final Function<? super T, ? extends SingleSource<? extends R>> mapper;

    final ErrorMode errorMode;

    final int prefetch;

    public ObservableConcatMapSingle(Observable<T> source,
            Function<? super T, ? extends SingleSource<? extends R>> mapper,
                    ErrorMode errorMode, int prefetch) {
        this.source = source;
        this.mapper = mapper;
        this.errorMode = errorMode;
        this.prefetch = prefetch;
    }

    @Override
    protected void subscribeActual(Observer<? super R> observer) {
        if (!ScalarXMapZHelper.tryAsSingle(source, mapper, observer)) {
            source.subscribe(new ConcatMapSingleMainObserver<T, R>(observer, mapper, prefetch, errorMode));
        }
    }

    static final class ConcatMapSingleMainObserver<T, R>
    extends AtomicInteger
    implements Observer<T>, Disposable {

        private static final long serialVersionUID = -9140123220065488293L;

        final Observer<? super R> downstream;

        final Function<? super T, ? extends SingleSource<? extends R>> mapper;

        final AtomicThrowable errors;

        final ConcatMapSingleObserver<R> inner;

        final SimplePlainQueue<T> queue;

        final ErrorMode errorMode;

        Disposable upstream;

        volatile boolean done;

        volatile boolean cancelled;

        R item;

        volatile int state;

        /** No inner SingleSource is running. */
        static final int STATE_INACTIVE = 0;
        /** An inner SingleSource is running but there are no results yet. */
        static final int STATE_ACTIVE = 1;
        /** The inner SingleSource succeeded with a value in {@link #item}. */
        static final int STATE_RESULT_VALUE = 2;

        ConcatMapSingleMainObserver(Observer<? super R> downstream,
                Function<? super T, ? extends SingleSource<? extends R>> mapper,
                        int prefetch, ErrorMode errorMode) {
            this.downstream = downstream;
            this.mapper = mapper;
            this.errorMode = errorMode;
            this.errors = new AtomicThrowable();
            this.inner = new ConcatMapSingleObserver<R>(this);
            this.queue = new SpscLinkedArrayQueue<T>(prefetch);
        }

        @Override
        public void onSubscribe(Disposable d) {
            if (DisposableHelper.validate(upstream, d)) {
                upstream = d;
                downstream.onSubscribe(this);
            }
        }

        @Override
        public void onNext(T t) {
            queue.offer(t);
            drain();
        }

        @Override
        public void onError(Throwable t) {
            if (errors.addThrowable(t)) {
                if (errorMode == ErrorMode.IMMEDIATE) {
                    inner.dispose();
                }
                done = true;
                drain();
            } else {
                RxJavaPlugins.onError(t);
            }
        }

        @Override
        public void onComplete() {
            done = true;
            drain();
        }

        @Override
        public void dispose() {
            cancelled = true;
            upstream.dispose();
            inner.dispose();
            if (getAndIncrement() == 0) {
                queue.clear();
                item = null;
            }
        }

        @Override
        public boolean isDisposed() {
            return cancelled;
        }

        void innerSuccess(R item) {
            this.item = item;
            this.state = STATE_RESULT_VALUE;
            drain();
        }

        void innerError(Throwable ex) {
            if (errors.addThrowable(ex)) {
                if (errorMode != ErrorMode.END) {
                    upstream.dispose();
                }
                this.state = STATE_INACTIVE;
                drain();
            } else {
                RxJavaPlugins.onError(ex);
            }
        }

        void drain() {
            if (getAndIncrement() != 0) {
                return;
            }

            int missed = 1;
            Observer<? super R> downstream = this.downstream;
            ErrorMode errorMode = this.errorMode;
            SimplePlainQueue<T> queue = this.queue;
            AtomicThrowable errors = this.errors;

            for (;;) {

                for (;;) {
                    if (cancelled) {
                        queue.clear();
                        item = null;
                        break;
                    }

                    int s = state;

                    if (errors.get() != null) {
                        if (errorMode == ErrorMode.IMMEDIATE
                                || (errorMode == ErrorMode.BOUNDARY && s == STATE_INACTIVE)) {
                            queue.clear();
                            item = null;
                            Throwable ex = errors.terminate();
                            downstream.onError(ex);
                            return;
                        }
                    }

                    if (s == STATE_INACTIVE) {
                        boolean d = done;
                        T v = queue.poll();
                        boolean empty = v == null;

                        if (d && empty) {
                            Throwable ex = errors.terminate();
                            if (ex == null) {
                                downstream.onComplete();
                            } else {
                                downstream.onError(ex);
                            }
                            return;
                        }

                        if (empty) {
                            break;
                        }

                        SingleSource<? extends R> ss;

                        try {
                            ss = ObjectHelper.requireNonNull(mapper.apply(v), "The mapper returned a null SingleSource");
                        } catch (Throwable ex) {
                            Exceptions.throwIfFatal(ex);
                            upstream.dispose();
                            queue.clear();
                            errors.addThrowable(ex);
                            ex = errors.terminate();
                            downstream.onError(ex);
                            return;
                        }

                        state = STATE_ACTIVE;
                        ss.subscribe(inner);
                        break;
                    } else if (s == STATE_RESULT_VALUE) {
                        R w = item;
                        item = null;
                        downstream.onNext(w);

                        state = STATE_INACTIVE;
                    } else {
                        break;
                    }
                }

                missed = addAndGet(-missed);
                if (missed == 0) {
                    break;
                }
            }
        }

        static final class ConcatMapSingleObserver<R>
        extends AtomicReference<Disposable>
        implements SingleObserver<R> {

            private static final long serialVersionUID = -3051469169682093892L;

            final ConcatMapSingleMainObserver<?, R> parent;

            ConcatMapSingleObserver(ConcatMapSingleMainObserver<?, R> parent) {
                this.parent = parent;
            }

            @Override
            public void onSubscribe(Disposable d) {
                DisposableHelper.replace(this, d);
            }

            @Override
            public void onSuccess(R t) {
                parent.innerSuccess(t);
            }

            @Override
            public void onError(Throwable e) {
                parent.innerError(e);
            }

            void dispose() {
                DisposableHelper.dispose(this);
            }
        }
    }
}


text:
package com.pronoia.camel.processor;

import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HL7AcknowlegementVerifier implements Processor {
  Logger log = LoggerFactory.getLogger(this.getClass());

  @Override
  public void process(Exchange exchange) throws Exception {
    Message message;
    if (exchange.hasOut()) {
      message = exchange.getOut();
    } else {
      message = exchange.getIn();
    }

    String acknowledgement = message.getHeader("CamelMllpAcknowledgement", String.class);
    if (null != acknowledgement) {
      if (acknowledgement.contains("\rMSA|AA|")) {
        log.trace("Received AA");
      } else if (acknowledgement.contains("\rMSA|AR|")) {
        log.warn("Received AR:\n\t{}", acknowledgement);
      } else if (acknowledgement.contains("\rMSA|AE|")) {
        log.error("Received AE:\n\r{}", acknowledgement);
      } else {
        log.error("Couldn't find acknowledgement in message: \n\t{}", acknowledgement.replace('\r', '\n'));
      }

    } else {
      log.warn("Message Body not found");
    }
  }
}


text:
layout: archive
author_profile: true
---

{% include base_path %}

{{ site.data.ui-text[site.locale].recent_posts | default: "Recent Posts" }}

{% for post in paginator.posts %}
  {% include archive-single.html %}
{% endfor %}

{% include paginator.html %}


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>to_message (OpenID::Extension)</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <link rel="stylesheet" href="../../.././rdoc-style.css" type="text/css" media="screen" />

# File lib/openid/extension.rb, line 21
    def to_message(message = nil)
      message = Message.new if message.nil?

      message.namespaces.add_alias(@ns_uri, @ns_alias)
      # XXX python ignores keyerror if m.ns.getAlias(uri) == alias

      message.update_args(@ns_uri, get_extension_args)
      return message
    end


text:
package com.affablebean.controller;

import com.affablebean.cart.ShoppingCart;
import com.affablebean.entity.Category;
import com.affablebean.entity.MsgFeedback;
import com.affablebean.entity.MsgSubject;
import com.affablebean.entity.Product;
import com.affablebean.json.JsonFactory;
import com.affablebean.session.CategoryFacade;
import com.affablebean.session.MsgFeedbackFacade;
import com.affablebean.session.MsgSubjectFacade;
import com.affablebean.session.OrderManager;
import com.affablebean.session.ProductFacade;
import com.affablebean.session.PromotionFacade;
import com.affablebean.validate.Validator;
import java.io.IOException;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;
import javax.ejb.EJB;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.*;

/**
 *
 * @author tgiunipero
 */
public final class CustCtrl extends HttpServlet {

	private String surcharge;
	@EJB
	private CategoryFacade categoryFacade;
	@EJB
	private MsgSubjectFacade subjectFacade;
	@EJB
	private MsgFeedbackFacade feedbackFacade;
	@EJB
	private OrderManager orderManager;
	@EJB
	private ProductFacade productFacade;
	@EJB
	private PromotionFacade promoFacade;

	@Override
	public void init(ServletConfig servletConfig) throws ServletException {
		super.init(servletConfig);

		// initialize servlet with configuration information
		surcharge = getServletContext().getInitParameter("deliverySurcharge");

		getServletContext().setAttribute("categories", categoryFacade.findAll());
		getServletContext().setAttribute("subjects", subjectFacade.findSubjects());
		getServletContext().setAttribute("sale", promoFacade.findSale());
		getServletContext().setAttribute("catProms", promoFacade.findCategories());
		getServletContext().setAttribute("prodProms", promoFacade.findProducts());
	}

	/**
	 * Handles the HTTP GET method.
	 *
	 * @param request servlet request
	 * @param response servlet response
	 * @throws ServletException if a servlet-specific error occurs
	 * @throws IOException if an I/O error occurs
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
					throws ServletException, IOException {

//		setSessionData(request); // pick up new static data without restart
		String userPath = request.getServletPath().substring(1);
		// true even if string reads "false"!
		boolean json = (request.getParameter("json") != null);

		// if category page is requested
		switch (userPath) {
			case "category":
				getCategoryProducts(request);

				if (json) {
					JsonFactory.categoryResponse(response.getWriter(), request.getSession(),
									getServletContext());
					return;
				}

				break;

			case "checkout":
				// forward to checkout page and switch to a secure channel
				break;

			case "chooseLanguage":
				userPath = setLanguage(request);
				break;

			case "viewCart":
				checkCart(request);

				if (json) {
					JsonFactory.cartResponse(response.getWriter(), request.getSession(),
									getServletContext());
					return;
				}

				userPath = "cart";
				break;

			default:
//				System.err.println("No request handler found for " + userPath);
		}

		dispatchRequest(userPath, request, response, json);
	}

	/**
	 * Handles the HTTP POST method.
	 *
	 * @param request servlet request
	 * @param response servlet response
	 * @throws ServletException if a servlet-specific error occurs
	 * @throws IOException if an I/O error occurs
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
					throws ServletException, IOException {

		// ensures that user input is interpreted as 8-bit Unicode (e.g., for
		// Czech characters)
		request.setCharacterEncoding("UTF-8");
		String userPath = request.getServletPath().substring(1);
		// true even if string reads "false"!
		boolean json = (request.getParameter("json") != null);

		switch (userPath) {
			case "addToCart":
				addToCart(request);

				if (json) {
					JsonFactory.cartResponse(response.getWriter(), request.getSession(),
									getServletContext());
					return;
				}

				userPath = "category";
				break;

			case "feedback":
				if (json) {
					boolean valid = saveFeedbackJson(request);

					if (valid) {
						JsonFactory.feedbackResponse(response.getWriter(), request);
					}

					return;
				}

				String fb = saveFeedback(request);

				if (!fb.isEmpty()) {
					userPath = fb;
				}
				break;

			case "purchase":
				if (json) {
					boolean valid = purchaseJson(request);

					if (valid) {
						JsonFactory.confResponse(response.getWriter(), request,
										getServletContext(), productFacade);
					}

					return;

				} else {
					boolean valid = purchase(request);

					if (valid) {
						int showJson = Integer.valueOf(
										getServletContext().getInitParameter("showJson"));

						if (showJson != 0) {
							JsonFactory.confResponse(response.getWriter(), request,
											getServletContext(), productFacade);
							return;
						}

						userPath = "confirmation";

					} else {
						userPath = "checkout";
					}
				}

				break;

			case "showJSON":
				showJSON(request, response.getWriter());
				return;

			case "updateCart":
				updateCart(request);

				if (json) {
					JsonFactory.cartResponse(response.getWriter(), request.getSession(),
									getServletContext());
					return;
				}

				userPath = "cart";
				break;

			default:
//				System.err.println("No action handler found for " + userPath);
		}

		dispatchRequest(userPath, request, response, json);
	}

	private void addToCart(HttpServletRequest request)
					throws NumberFormatException {

		HttpSession session = request.getSession();
		ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");

		// if user is adding item to cart for first time create cart object and
		// attach it to user session
		if (cart == null) {
			cart = new ShoppingCart();
			session.setAttribute("cart", cart);
		}

		// get user input from request
		String productId = request.getParameter("productId");

		if (!productId.isEmpty()) {
			Product product = productFacade.find(Integer.parseInt(productId));
			cart.addItem(product);
		}
	}

	private void checkCart(HttpServletRequest request) {
		boolean clear = (request.getParameter("clear") != null);

		if (clear) {
			HttpSession session = request.getSession();
			ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
			cart.clear();
		}
	}

	private void dispatchRequest(String userPath, HttpServletRequest request,
					HttpServletResponse response, boolean json)
					throws ServletException, IOException {

		String url;

		switch (userPath) {
			case "contact":
				if (json) {
					JsonFactory.subjectList(response.getWriter(), getServletContext());
					return;
				}

				url = "contact.jsp";
				break;

			case "index":
				if (json) {
					JsonFactory.indexResponse(response.getWriter(), getServletContext());
					return;
				}

				url = "index.jsp";
				break;

			case "privacy":
				url = "privacy.jsp";
				break;

			default:
				url = "/WEB-INF/view/" + userPath + ".jsp";
		}

		request.getRequestDispatcher(url).forward(request, response);
	}

	private void getCategoryProducts(HttpServletRequest request)
					throws NumberFormatException {

		// get categoryId from request
		String categoryId = request.getParameter("id");

		if (categoryId != null) {
			HttpSession session = request.getSession();
			Category selectedCategory
							= categoryFacade.find(Short.parseShort(categoryId));

			// place selected category in session scope
			session.setAttribute("selectedCategory", selectedCategory);

			// get all products for selected category and place them in session scope
			session.setAttribute("categoryProducts",
							selectedCategory.getProductCollection());
		}
	}

	private boolean purchase(HttpServletRequest request) {
		HttpSession session = request.getSession();
		ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");

		if (cart == null) {
			return false;
		}

		// extract user data from request
		String name = request.getParameter("name");
		String email = request.getParameter("email");
		String phone = request.getParameter("phone");
		String address = request.getParameter("address");
		String cityRegion = "1"; // dont'care
		String ccNumber = request.getParameter("creditcard");

		// validate user data
		boolean valid = Validator.validateCheckOutForm(request, name, email, phone,
						address, cityRegion, ccNumber);

		if (valid) {
			return saveOrder(request, name, email, phone, address, cityRegion,
							ccNumber);
		} else {
			request.setAttribute("validationErrorFlag", true);
			return false;
		}
	}

	private boolean purchaseJson(HttpServletRequest request) throws IOException {
		HttpSession session = request.getSession();
		ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");

		if (cart == null) {
			return false;
		}

		String name, email, phone, address, ccNumber;
		String cityRegion = "1"; // dont'care

		try (JsonReader jsonReader = Json.createReader(request.getInputStream())) {
			JsonObject data = jsonReader.readObject();
			name = data.getJsonString("name").toString();
			email = data.getJsonString("email").toString();
			phone = data.getJsonString("phone").toString();
			address = data.getJsonString("address").toString();
			ccNumber = data.getJsonString("creditcard").toString();
		}

		// validate user data
		boolean valid = Validator.validateCheckOutForm(request, name, email,
						phone, address, cityRegion, ccNumber);

		if (valid) {
			return saveOrder(request, name, email, phone, address, cityRegion, ccNumber);
		}

		return false;
	}

	private String saveFeedback(HttpServletRequest request) {
		String name, email, msg;

		name = request.getParameter("name");
		email = request.getParameter("email");
		msg = request.getParameter("msg");

		boolean valid = Validator.validateContactForm(request, name, email, msg);

		if (valid) {
			MsgSubject subject = null;

			try {
				int subjId = Integer.valueOf(request.getParameter("subject_sel"));
				subject = subjectFacade.find(subjId);
			} catch (NumberFormatException e) {
			}

			int id = feedbackFacade.save(name, email, msg, subject);

			if (id != 0) {
				return "index";
			}

		} else {
			request.setAttribute("validationErrorFlag", true);
		}

		return "contact";
	}

	private boolean saveFeedbackJson(HttpServletRequest request)
					throws IOException {

		try (JsonReader jsonReader = Json.createReader(request.getInputStream())) {
			JsonObject data = jsonReader.readObject();

			String name = data.getJsonString("name").toString();
			String email = data.getJsonString("email").toString();
			String msg = data.getJsonString("msg").toString();

			MsgSubject subject = null;

			try {
				int id = data.getJsonNumber("subject").intValue();
				subject = subjectFacade.find(id);
			} catch (NumberFormatException e) {
			}

			boolean valid = Validator.validateContactForm(request, name, email, msg);

			if (valid) {
				int id = feedbackFacade.save(name, email, msg, subject);
			}

			return valid;

		} catch (Exception e) {
			e.printStackTrace();
		}

		return false;
	}

	private boolean saveOrder(HttpServletRequest request, String... order) {
		HttpSession session = request.getSession();
		ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");

		// see method call for order element types
		int orderId = orderManager.placeOrder(cart, surcharge, order[0], order[1],
						order[2], order[3], order[4], order[5]);

		// if order processed successfully send user to confirmation page
		if (orderId != 0) {
			// in case language was set using toggle, get language choice before
			// destroying session
			Locale locale = (Locale) session.getAttribute(
							"javax.servlet.jsp.jstl.fmt.locale.session");
			String language = "";

			if (locale != null) {
				language = (String) locale.getLanguage();
			}

			// dissociate shopping cart from session
			cart = null;

			// end session
			session.invalidate();

			// if user changed language using the toggle, reset the language attribute
			// otherwise language will be switched on confirmation page!
			if (!language.isEmpty()) {
				request.setAttribute("language", language);
			}

			// get order details
			Map<String, Object> orderMap = orderManager.getOrderDetails(orderId);

			// place order details in request scope
			request.setAttribute("customer", orderMap.get("customer"));
			request.setAttribute("products", orderMap.get("products"));
			request.setAttribute("orderRecord", orderMap.get("orderRecord"));
			request.setAttribute("orderedProducts", orderMap.get("orderedProducts"));

			return true;

			// otherwise, send back to checkout page and display error
		} else {
			request.setAttribute("orderFailureFlag", true);
			return false;
		}
	}

	private void updateCart(HttpServletRequest request) throws
					NumberFormatException {

		// get input from request
		String productId = request.getParameter("productId");
		String quantity = request.getParameter("quantity");

		if (Validator.validateQuantity(productId, quantity)) {
			Product product = productFacade.find(Integer.parseInt(productId));
			HttpSession session = request.getSession();
			ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
			cart.update(product, quantity);
		}
	}

	private String setLanguage(HttpServletRequest request) {
		// get language choice
		String language = request.getParameter("language");
		// place in request scope
		request.setAttribute("language", language);

		HttpSession session = request.getSession();
		String userView = (String) session.getAttribute("view");
		String userPath;

		if ((userView != null) && (!userView.equals("/index"))) {
			// index.jsp exists outside 'view' folder so must be forwarded separately
			userPath = userView;
		} else {
			// if previous view is index or cannot be determined, send user to
			// welcome page
			userPath = "/index";
		}

		return userPath.substring(1);
	}

	private void setSessionData(HttpServletRequest request) {
		HttpSession session = request.getSession();

		// scope ordering rules should pick up updates here
		if (session.getAttribute("categories") == null) {
			session.setAttribute("categories", categoryFacade.findAll());
		}

		if (session.getAttribute("subjects") == null) {
			session.setAttribute("subjects", subjectFacade.findAll());
		}

		if (session.getAttribute("sale") == null) {
			session.setAttribute("sale", promoFacade.findSale());
		}
	}

	private void showJSON(HttpServletRequest request, Writer response) {
		HttpSession session = request.getSession();
		String source = (String) request.getParameter("src").substring(1);
		source = source.substring(source.lastIndexOf('/') + 1, source.lastIndexOf(".jsp"));

		switch (source) {
			case "cart":
				JsonFactory.cartResponse(response, session, getServletContext());
				break;

			case "category":
				JsonFactory.categoryResponse(response, session, getServletContext());
				break;

			case "index":
				JsonFactory.indexResponse(response, getServletContext());
				break;

			default:
		}
	}
}


text:
<?php

namespace Codeception;

use Codeception\Event\Suite;
use Codeception\Event\SuiteEvent;
use Codeception\Exception\ConfigurationException;
use Codeception\Exception\TestRuntimeException;
use Codeception\Lib\Di;
use Codeception\Lib\GroupManager;
use Codeception\Lib\ModuleContainer;
use Codeception\Lib\Notification;
use Codeception\Lib\TestLoader;
use Codeception\TestCase\Interfaces\ScenarioDriven;
use Symfony\Component\EventDispatcher\EventDispatcher;

class SuiteManager
{
    public static $environment;
    public static $name;

    /**
     * @var \PHPUnit_Framework_TestSuite
     */
    protected $suite = null;

    /**
     * @var null|\Symfony\Component\EventDispatcher\EventDispatcher
     */
    protected $dispatcher = null;

    /**
     * @var GroupManager
     */
    protected $groupManager;

    /**
     * @var TestLoader
     */
    protected $testLoader;

    /**
     * @var ModuleContainer
     */
    protected $moduleContainer;

    /**
     * @var Di
     */
    protected $di;

    protected $tests = [];
    protected $debug = false;
    protected $path = '';
    protected $printer = null;

    protected $env = null;
    protected $settings;

    public function __construct(EventDispatcher $dispatcher, $name, array $settings)
    {
        $this->settings = $settings;
        $this->dispatcher = $dispatcher;
        $this->di = new Di();
        $this->path = $settings['path'];
        $this->groupManager = new GroupManager($settings['groups']);
        $this->moduleContainer = new ModuleContainer($this->di, $settings);

        $modules = Configuration::modules($this->settings);
        foreach ($modules as $moduleName) {
            $this->moduleContainer->create($moduleName);
        }
        $this->moduleContainer->validateConflicts();
        if (isset($settings['current_environment'])) {
            $this->env = $settings['current_environment'];
        }
        $this->suite = $this->createSuite($name);
    }

    public function initialize()
    {
        $this->dispatcher->dispatch(Events::MODULE_INIT, new SuiteEvent($this->suite, null, $this->settings));
        foreach ($this->moduleContainer->all() as $module) {
            $module->_initialize();
        }
        if (!file_exists(Configuration::supportDir() . $this->settings['class_name'] . '.php')) {
            throw new Exception\ConfigurationException($this->settings['class_name'] . " class doesn't exist in suite folder.\nRun the 'build' command to generate it");
        }
        $this->dispatcher->dispatch(Events::SUITE_INIT, new SuiteEvent($this->suite, null, $this->settings));
        ini_set('xdebug.show_exception_trace', 0); // Issue https://github.com/symfony/symfony/issues/7646
    }

    public function loadTests($path = null)
    {
        $testLoader = new TestLoader($this->settings['path']);
        $path
            ? $testLoader->loadTest($path)
            : $testLoader->loadTests();

        $tests = $testLoader->getTests();
        if ($this->settings['shuffle']) {
            shuffle($tests);
        }
        foreach ($tests as $test) {
            $this->addToSuite($test);
        }
    }

    protected function addToSuite($test)
    {
        $this->configureTest($test);

        if ($test instanceof \PHPUnit_Framework_TestSuite_DataProvider) {
            foreach ($test->tests() as $t) {
                $this->configureTest($t);
            }
        }

        if ($test instanceof ScenarioDriven) {
            $test->preload();
        }
        if ($test instanceof TestCase) {
            $this->checkEnvironmentExists($test);
            if (!$this->isExecutedInCurrentEnvironment($test)) {
                return; // skip tests from other environments
            }
        }

        $groups = $this->groupManager->groupsForTest($test);
        $this->suite->addTest($test, $groups);

        if (!empty($groups) && $test instanceof TestCase\Interfaces\ScenarioDriven && null !== $test->getScenario()) {
            $test->getScenario()->group($groups);
        }
    }

    protected function createSuite($name)
    {
        $suite = new Lib\Suite();
        $suite->setBaseName($this->env ? substr($name, 0, strpos($name, '-' . $this->env)) : $name);
        if ($this->settings['namespace']) {
            $name = $this->settings['namespace'] . ".$name";
        }
        $suite->setName($name);
        $suite->setModules($this->moduleContainer->all());
        return $suite;
    }

    public function run(PHPUnit\Runner $runner, \PHPUnit_Framework_TestResult $result, $options)
    {
        $this->dispatcher->dispatch(Events::SUITE_BEFORE, new Event\SuiteEvent($this->suite, $result, $this->settings));
        $runner->doEnhancedRun($this->suite, $result, $options);
        $this->dispatcher->dispatch(Events::SUITE_AFTER, new Event\SuiteEvent($this->suite, $result, $this->settings));
    }

    /**
     * @return \Codeception\Lib\Suite
     */
    public function getSuite()
    {
        return $this->suite;
    }

    /**
     * @return ModuleContainer
     */
    public function getModuleContainer()
    {
        return $this->moduleContainer;
    }

    protected function getActor()
    {
        return $this->settings['namespace']
            ? rtrim($this->settings['namespace'], '\\') . '\\' . $this->settings['class_name']
            : $this->settings['class_name'];
    }

    protected function checkEnvironmentExists(\Codeception\TestCase $test)
    {
        $envs = $test->getEnvironment();
        if (empty($envs)) {
            return;
        }
        if (!isset($this->settings['env'])) {
            Notification::warning("Environments are not configured", TestCase::getTestFullName($test));
            return;
        }
        $availableEnvironments = array_keys($this->settings['env']);
        $listedEnvironments = explode(',', implode(',', $test->getEnvironment()));
        foreach ($listedEnvironments as $env) {
            if (!in_array($env, $availableEnvironments)) {
                Notification::warning("Environment $env was not configured but used in test", TestCase::getTestFullName($test));
            }
        }
    }

    protected function isExecutedInCurrentEnvironment(\Codeception\TestCase $test)
    {
        $envs = $test->getEnvironment();
        if (empty($envs)) {
            return true;
        }
        $currentEnvironments = explode(',', $this->env);
        foreach ($envs as $envList) {
            $envList = explode(',', $envList);
            if (count($envList) == count(array_intersect($currentEnvironments, $envList))) {
                return true;
            }
        }
        return false;
    }

    /**
     * @param $t
     * @throws Exception\InjectionException
     */
    protected function configureTest($t)
    {
        if (!$t instanceof TestCase\Interfaces\Configurable) {
            return;
        }
        $t->configDispatcher($this->dispatcher);
        $t->configActor($this->getActor());
        $t->configEnv($this->env);
        $t->configModules($this->moduleContainer);
        $t->configDi($this->di);
        $t->initConfig();
        $this->di->injectDependencies($t);
    }

}


text:
title: Unit Tests
localeTitle: Тесты модулей
---
## Тесты модулей

Модульное тестирование - это тип тестирования, который находится в нижней части пирамиды тестирования программного обеспечения. Это включает в себя разбивку кодовой базы на более мелкие части (или единицы) и тестирование их по отдельности. В зависимости от типа языка программирования (или парадигмы) это может быть против всего, что вы определяете как единицу, хотя наиболее распространенная практика - это функции.

### Почему?

*   **Защита** - Тестирование модулей защищает от введения новых или старых ошибок для защитного программирования
*   **Уверенность** - вы можете добавлять изменения или повторное использование или код рефакторинга (оба очень распространенные) и быть уверенным, что вы не добавили ошибку
*   **Документация** - модульное тестирование документирует поведение и поток кода, поэтому его легко понять, кто-то новый для кода, чтобы понять его
*   **Изоляция** - изолирует модуль от всей функции. Этот подход заставляет вас думать о модуле сам по себе и спрашивать, какова его работа?
*   **Качество.** Поскольку модульное тестирование заставляет вас думать и использовать свой собственный API, он обеспечивает хорошие / расширяемые интерфейсы и шаблоны. Он может указывать на какую-либо жесткую связь или чрезмерную сложность, которая должна быть решена. Плохой код обычно намного сложнее проверить
*   **Промышленный стандарт.** Единичное тестирование в наши дни является общей дисциплиной, и это требование для значительной части программных компаний
*   **Меньше ошибок.** Существенные исследования показывают, что применение теста к приложению может снизить плотность ошибок в производстве на 40% - 80%.

### Пример (в Javascript)

Предположим, что существует функция, написанная в файле **add.js**

```javascript
var add = function(number1, number2){
  return number1 + number2;
 }
```

Теперь, чтобы написать единичный тест этой конкретной функции, мы можем использовать инструменты тестирования, такие как [mocha](http://mochajs.org/)

```javascript
const mocha = require('mocha')
 const chai = require('chai')  // It is an assertion library
 describe('Test to check add function', function(){
  it('should add two numbers', function(){
    (add(2,3)).should.equal(5)  //Checking that 2+3 should equal 5 using the given add function
  });
 });
```

### Тестирование

Модульное тестирование является ключевой особенностью подхода разработки программного обеспечения (TDD) для разработки программного обеспечения. В этом подходе код для конкретных функций или функций записывается путем повторного использования очень короткого цикла. Во-первых, разработчик пишет набор автоматизированных модульных тестов и гарантирует, что они не сработают изначально. Затем разработчик реализует минимальный минимальный код, необходимый для прохождения тестовых примеров. После подтверждения того, что код ведет себя так, как ожидалось, разработчик затем возвращается и код рефакторинга придерживается любых соответствующих стандартов кодирования.

### Больше информации

Мартин Фаулер на [модульном](https://www.martinfowler.com/bliki/UnitTest.html) тестировании: [martinfowler.com](https://www.martinfowler.com/bliki/UnitTest.html)

Роберт Мартин aka «Доктор Боб» на TDD: [butunclebob.com](http://www.butunclebob.com/ArticleS.UncleBob.TheThreeRulesOfTdd)

Эрик Эллиот о модульных тестах и TDD: [средний](https://medium.com/javascript-scene/5-common-misconceptions-about-tdd-unit-tests-863d5beb3ce9)


text:
module Main where

import Control.Concurrent
import Foundation
import Yesod

-- | Normal production main.
main :: IO ()
main = do c <- newChan
          warpEnv (Piggies c)


text:
import * as React from 'react'
import { C_BLUE, SPACING_2, Link, Text } from '@opentrons/components'
import { TitledControl } from '../TitledControl'

import type { StyleProps } from '@opentrons/components'

const PREVIOUS_RELEASES_URL = 'https://github.com/Opentrons/opentrons/releases'

// NOTE(mc, 2020-10-09): `en/` intentionally omitted from URL
const UNINSTALL_SUPPORT_URL =
  'https://support.opentrons.com/articles/2393514-uninstall-the-opentrons-app'

// TOOD(mc, 2020-10-08): i18n
const RESTORE_A_DIFFERENT_VERSION = 'Restore Different Software Version'

const NEED_TO_RESTORE = (
  <>
    Need to restore a different version of Opentrons OT-2 or App software? While
    Opentrons does not recommend to reverting to older software versions, you
    can access{' '}
    <Link external href={PREVIOUS_RELEASES_URL} color={C_BLUE}>
      previous releases here
    </Link>
    .
  </>
)

const PERFORM_A_FULL_UNINSTALL = (
  <>
    For best results,{' '}
    <Link external href={UNINSTALL_SUPPORT_URL} color={C_BLUE}>
      uninstall the existing app and remove its configuration files
    </Link>{' '}
    before installing the older version.
  </>
)

export function DowngradeAppControl(props: StyleProps): React.Node {
  return (
    <TitledControl
      {...props}
      title={RESTORE_A_DIFFERENT_VERSION}
      description={
        <>
          <Text marginBottom={SPACING_2}>{NEED_TO_RESTORE}</Text>
          <Text>{PERFORM_A_FULL_UNINSTALL}</Text>
        </>
      }
    />
  )
}


text:
require 'spec_helper'
require 'puppet_spec/files'
require 'puppet_spec/compiler'

describe Puppet::Type.type(:user), '(integration)', :unless => Puppet.features.microsoft_windows? do
  include PuppetSpec::Files
  include PuppetSpec::Compiler

  context "when set to purge ssh keys from a file" do
    let(:tempfile) { file_containing('user_spec', "# comment\nssh-rsa KEY-DATA key-name\nssh-rsa KEY-DATA key name\n") }
    # must use an existing user, or the generated key resource
    # will fail on account of an invalid user for the key
    # - root should be a safe default
    let(:manifest) { "user { 'root': purge_ssh_keys => '#{tempfile}' }" }

    it "should purge authorized ssh keys" do
      apply_compiled_manifest(manifest)
      File.read(tempfile).should_not =~ /key-name/
    end

    it "should purge keys with spaces in the comment string" do
      apply_compiled_manifest(manifest)
      File.read(tempfile).should_not =~ /key name/
    end

    context "with other prefetching resources evaluated first" do
      let(:manifest) { "host { 'test': before => User[root] } user { 'root': purge_ssh_keys => '#{tempfile}' }" }

      it "should purge authorized ssh keys" do
        apply_compiled_manifest(manifest)
        File.read(tempfile).should_not =~ /key-name/
      end
    end
  end
end


text:
namespace mediapipe {

void CopyGlTexture(const GlTextureView& src, GlTextureView& dst) {
  glViewport(0, 0, src.width(), src.height());
  glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, src.target(),
                         src.name(), 0);

  glActiveTexture(GL_TEXTURE0);
  glBindTexture(dst.target(), dst.name());
  glCopyTexSubImage2D(dst.target(), 0, 0, 0, 0, 0, dst.width(), dst.height());

  glBindTexture(dst.target(), 0);
  glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, src.target(), 0,
                         0);
}

void FillGlTextureRgba(GlTextureView& view, float r, float g, float b,
                       float a) {
  glViewport(0, 0, view.width(), view.height());
  glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, view.target(),
                         view.name(), 0);
  glClearColor(r, g, b, a);
  glClear(GL_COLOR_BUFFER_BIT);
  glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, view.target(), 0,
                         0);
}

}  // namespace mediapipe


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="expend">
        <note>
            Frames file for 'expend' based on survey of sentences in the WSJ
            corpus.
        </note>

        <roleset id="expend.01" name="to spend, consume" vncls="-">
            <roles>
                <role descr="spender, agent" n="0"/>
                <role descr="entity expended" n="1"/>
                <role descr="entity expended on" n="2"/>
            </roles>

            <example name="passive">
                <inflection aspect="ns" form="participle" person="ns" tense="past" voice="passive"/>
                <text>
                    Mr. Good , who [*T*-1] documents these things as best he can [*?*] , provides an official explanation in the form of a memorandum from Chief of Staff George C. Marshall to President Roosevelt : `` [1,430 pounds of ammunition]-3 , '' he wrote his commander in chief [0] [*T*-2] , were expended [*-3] on `` unidentified aircraft , '' flying at speeds as slow as 200 mph and elevations between 9,000 and 18,000 feet .
                </text>
                <rel>expended</rel>
                <arg n="1">[*-3]</arg>
                <arg n="2">on `` unidentified aircraft , '' flying at speeds as slow as 200 mph and elevations between 9,000 and 18,000 feet</arg>
            </example>

        </roleset>
    </predicate>

    <note>
        frames created by Olga
    </note>

</frameset>


text:
<nz-card class="repo-item"
         [class.edit]="editMode"
         [nzTitle]="repo.name"
         [nzExtra]="extraTemplate">
  <ng-template #extraTemplate>

      <button nz-button
              nzSize="small"
              (click)="triggerEditMode()">

        Edit
      </button>

      <button nz-button
              nzType="primary"
              nzSize="small"
              [disabled]="!settingFormArray.valid"
              (click)="save()">

        Save
      </button>
      <button nz-button
              nzSize="small"
              (click)="cancel()">

        Cancel
      </button>

  </ng-template>

Setting

  <form nz-form>
    <nz-table nzTemplateMode nzSize="small">

        Name
        Value

        {{setting.name}}
        <ng-container *ngIf="!editMode">
          {{setting.selected}}
        </ng-container>
        <ng-container *ngIf="editMode">

            <input *ngIf="setting.type === 'INPUT'"
                   nzSize="small"
                   nz-input
                   [formControl]="settingFormArray.controls[i]">

            <nz-select *ngIf="setting.type === 'DROPDOWN'" [formControl]="settingFormArray.controls[i]">
              <nz-option
                *ngFor="let option of setting.value"
                [nzLabel]="option"
                [nzValue]="option">
              </nz-option>
            </nz-select>

        </ng-container>

    </nz-table>
  </form>

</nz-card>


text:
layout: kanji
v4: 432
v6: 463
kanji: 泣
keyword: cry
elements: cry, water, water droplets, water pistol, vase, stand up
strokes: 8
image: E6B3A3
on-yomi: キュウ
kun-yomi: な.く
permalink: /rtk/泣/
prev: 立
next: 章
---

1) [ruisu] 25-10-2007(104): Guys have two ways of watering when they are standing, the less common one is crying.

2) [AndamanIslander] 1-2-2008(71): She stood up to leave the room when her eyes started to water...

3) [vxnine] 20-1-2009(36): This won't make sense for anyone who hasn't played the game, but for those who have, it'll make this character very easy to remember. Just picture that one scene in Final Fantasy VII where Cloud is standing in the water about to let Aeris go... A very sad scene which can make anyone cry.

4) [phauna] 19-2-2008(28): I imagine Alice (in Wonderland) standing in a pool of her own making, crying to herself.

5) [salvw] 17-12-2008(25): If you cry really hard you can fill up a vase with the water from your tears.


text:
echo "Trying to autobuild IAT_patcher..."
git clone --recursive https://github.com/hasherezade/IAT_patcher.git
echo "[+] IAT_patcher cloned"
echo $$
cd IAT_patcher
sh build.sh


text:
package org.perfcake.idea.editor.dragndrop;

import javax.swing.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by miron on 7. 12. 2014.
 */
public class ComponentTransferHandler extends TransferHandler {

    private final Map<String, DropAction> prefixActionMap;

    public ComponentTransferHandler(Map<String, DropAction> prefixActionMap) {
        this.prefixActionMap = prefixActionMap;
    }

    public ComponentTransferHandler(String prefix, DropAction dropAction) {
        prefixActionMap = new HashMap<>();
        prefixActionMap.put(prefix, dropAction);
    }

    public boolean canImport(TransferSupport support) {
        if (!support.isDataFlavorSupported(DataFlavor.stringFlavor)) {
            return false;
        }
        Transferable t = support.getTransferable();
        String data;
        try {
            data = (String) t.getTransferData(DataFlavor.stringFlavor);
        } catch (Exception e) {
            return false;
        }
        String[] split = data.split("~");
        if (split.length != 2) {
            return false;
        }
        if (!prefixActionMap.keySet().contains(split[0])) {
            return false;
        }
        return true;
    }

    @Override
    public boolean importData(TransferSupport support) {
        Transferable t = support.getTransferable();
        String data;
        try {
            data = (String) t.getTransferData(DataFlavor.stringFlavor);
        } catch (Exception e) {
            return false;
        }
        String[] split = data.split("~");
        return prefixActionMap.get(split[0]).invoke(split[1]);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using csfm_android.Services;
using Android.Provider;
using csfm_android.Utils;

namespace csfm_android.Receivers
{
    /// <summary>
    /// Broadcast receiver used by the Scrobbling service. This receiver is specified in the manifest (via annotations below) and is therefore launched automatically on broadcasts listed on annotations below
    /// </summary>

    [BroadcastReceiver(Enabled = true, Exported = true)]
    [IntentFilter(new[] { Configuration.Music.ACTION_METACHANGED, Configuration.Music.ACTION_PLAYBACKCOMPLETE, Configuration.Music.ACTION_PLAYSTATECHANGED, Configuration.Music.ACTION_QUEUECHANGED })]
    public class MusicPlayingReceiver : BroadcastReceiver
    {
        /// <summary>
        /// On broadcast receive
        /// </summary>
        /// <param name="context"></param>
        /// <param name="intent"></param>
        public override void OnReceive(Context context, Intent intent)
        {
            if (intent.HasExtra(Configuration.Music.EXTRA_PLAYING)) //Music action
            {
                if (intent.GetBooleanExtra(Configuration.Music.EXTRA_PLAYING, false)) //Music is playing
                {
                    if (intent.GetPosition(1) == 0) //Music is at 00:00
                    {
                        ScrobblerService.SendScrobble(intent, context);
                    }
                }
                else //Music paused or continuing
                {
                    ScrobblerService.StopScrobble(context);
                }
            }
            else
            {
                //Not about music
            }
        }
    }
}


text:
require 'rspec_helper'
include Line

describe 'match_limits method' do
  before(:each) do
    @filt = Line::Filter.new
  end

  it 'An empty request should be ok' do
    expect(@filt.match_limits([], [])).to eq(false)
    expect(@filt.match_limits([nil], [])).to eq(false)
    expect(@filt.match_limits([nil], [nil, :next, :first])).to eq(false)
  end

  it 'A single matching request should be true' do
    expect(@filt.match_limits([:next], [nil, :next, :first])).to eq(true)
  end

  it 'A empty default should not match' do
    expect(@filt.match_limits([], [:next])).to eq(false)
  end

  it 'An array with multiple matches should be true' do
    expect(@filt.match_limits([:next], [nil, :next, :first])).to eq(true)
  end

  it 'An array with a non matching entry matches should be false' do
    expect(@filt.match_limits([:short], [nil, :next, :first])).to eq(false)
  end
end


text:
using namespace std;
using namespace demoloop;

const uint32_t CYCLE_LENGTH = 10;
const uint32_t arms = 7;
const uint32_t trisPerArm = 5;
const uint32_t numTris = arms * trisPerArm;
// const uint32_t numTris = 1;

glm::vec3 computeNormal(const Triangle &t) {
  glm::vec3 v1(t.a.x, t.a.y, t.a.z);
  glm::vec3 v2(t.b.x, t.b.y, t.b.z);
  glm::vec3 v3(t.c.x, t.c.y, t.c.z);
  return normalize(cross(v2 - v1, v3 - v1));
}

const float RADIUS = 0.18;
const float interval = DEMOLOOP_M_PI * 2 / 3;
const Triangle triangle = {
  {RADIUS * cosf(interval * 0), RADIUS * sinf(interval * 0), 0, 0, 0, 255, 255, 255, 255},
  {RADIUS * cosf(interval * 1), RADIUS * sinf(interval * 1), 0, 0, 1, 255, 255, 255, 255},
  {RADIUS * cosf(interval * 2), RADIUS * sinf(interval * 2), 0, 1, 0, 255, 255, 255, 255}
};
const Vertex peak = {0, 0, sqrtf(2) * RADIUS, 1, 1, 255, 255, 255, 255};
const Triangle tetrahedron[4] = {
  {triangle.a, triangle.c, triangle.b},
  {triangle.a, triangle.b, peak},
  {triangle.b, triangle.c, peak},
  {triangle.c, triangle.a, peak},
};
const uint32_t numVertices = 4 * 3;
const glm::vec3 normals[numVertices] = {
  computeNormal(tetrahedron[0]), computeNormal(tetrahedron[0]), computeNormal(tetrahedron[0]),
  computeNormal(tetrahedron[1]), computeNormal(tetrahedron[1]), computeNormal(tetrahedron[1]),
  computeNormal(tetrahedron[2]), computeNormal(tetrahedron[2]), computeNormal(tetrahedron[2]),
  computeNormal(tetrahedron[3]), computeNormal(tetrahedron[3]), computeNormal(tetrahedron[3]),
};

const static std::string shaderCode = R"===(
varying vec4 vpos;
varying vec3 vNorm;
varying vec4 vColor;

uniform mediump float cycle_ratio;

#define DEMOLOOP_M_PI 3.1459

#ifdef VERTEX
attribute mat4 modelViews;
attribute vec3 normals;
attribute vec4 colors;

vec4 position(mat4 transform_proj, mat4 model, vec4 vertpos) {
  vColor = colors;
  vNorm = normals;
  return transform_proj * modelViews * vertpos;
}
#endif

#ifdef PIXEL
vec4 effect(vec4 color, Image texture, vec2 tc, vec2 screen_coords) {
  float t = mod(cycle_ratio + vColor.r, 1.0);
  float r = 0.0, g = 0.0, b = 0.0;

  r += tc.x;
  g += tc.y;
  b += (1.0 - tc.x + 1.0 - tc.y) / 2.0;

  float maxTiers = 12.0;
  float numTiers = pow(sin(t * DEMOLOOP_M_PI), 2.0) * (maxTiers - 2.0) + 2.0;

  float lightScale = (1.0 - numTiers / maxTiers) * 0.4;
  r = floor(r * numTiers) / numTiers + lightScale;
  g = floor(g * numTiers) / numTiers + lightScale;
  b = floor(b * numTiers) / numTiers + lightScale;
  return vec4(r, g, b, vColor.a);
}
#endif
)===";

uint32_t bufferMatrixAttribute(const GLint location, const GLuint buffer, const float *data, const uint32_t num, GLenum usage) {
  uint32_t enabledAttribs = 0;
  glBindBuffer(GL_ARRAY_BUFFER, buffer);
  glBufferData(GL_ARRAY_BUFFER, num * sizeof(float) * 4 * 4, data, usage);

  for (int i = 0; i < 4; ++i) {
    enabledAttribs |= 1u << (uint32_t)(location + i);
    glVertexAttribPointer(location + i, 4, GL_FLOAT, GL_FALSE, sizeof(float) * 4 * 4, (void*)(sizeof(float) * (4 * i)));
    glVertexAttribDivisor(location + i, 1);
  }

  return enabledAttribs;
}

const float farPlane = 5;

class Loop048 : public Demoloop {
public:
  Loop048() : Demoloop(CYCLE_LENGTH, 150, 150, 150), shader({shaderCode, shaderCode}) {
    glm::mat4 perspective = glm::perspective(static_cast<float>(DEMOLOOP_M_PI) / 4.0f, (float)width / (float)height, 0.1f, farPlane);
    gl.getProjection() = perspective;

    glGenBuffers(1, &modelViewsBuffer);
    glGenBuffers(1, &normalsBuffer);
    glGenBuffers(1, &colorsBuffer);

    gl.bufferVertices((Vertex *)&tetrahedron, numVertices, GL_STATIC_DRAW);
    glVertexAttribPointer(ATTRIB_POS, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*) offsetof(Vertex, x));
    glVertexAttribPointer(ATTRIB_TEXCOORD, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*) offsetof(Vertex, s));
    glVertexAttribPointer(ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(Vertex), (GLvoid*) offsetof(Vertex, r));

    normalsLocation = shader.getAttribLocation("normals");
    glBindBuffer(GL_ARRAY_BUFFER, normalsBuffer);
    glBufferData(GL_ARRAY_BUFFER, numVertices * sizeof(glm::vec3), &normals[0].x, GL_STATIC_DRAW);
    glVertexAttribPointer(normalsLocation, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), 0);
  }

  void Update() {
    const float cycle_ratio = getCycleRatio();

    float eyeRot = 0;
    // eyeRot += cycle_ratio * DEMOLOOP_M_PI * 2 * 2;
    // eyeRot += DEMOLOOP_M_PI / 2;

    const glm::vec3 eye = glm::rotate(glm::vec3(0, 0, farPlane), eyeRot, glm::vec3(-0.3, 1, 0));
    // const glm::vec3 eye = glm::rotate(glm::vec3(0, 4, 40), eyeRot, glm::vec3(-0.3, 1, 0));
    const glm::vec3 up = glm::vec3(0, 1, 0);
    const glm::vec3 target = glm::vec3(0, 0, 0);
    glm::mat4 camera = glm::lookAt(eye, target, up);

    GL::TempTransform t1(gl);
    t1.get() = camera;

    const glm::vec3 twoDAxis = {0, 0, 1};
    for (uint32_t i = 0; i < numTris; ++i) {
      const float t = i;
      const float armIndex = i % arms;
      // const float indexInArm = floor(t / arms) / trisPerArm;
      // const float i_cycle_ratio = fmod(indexInArm + cycle_ratio, 1);
      const float i_cycle_ratio = fmod(t / numTris + cycle_ratio, 1);

      glm::mat4& m = matrices[i] = glm::mat4();
      m = glm::rotate(m, (float)DEMOLOOP_M_PI * 2 / arms * armIndex, twoDAxis);

      float x = 0, y = 0, z = 0;

      x += cosf(i_cycle_ratio * DEMOLOOP_M_PI * 2) * 0.3;

      y += sinf(i_cycle_ratio * DEMOLOOP_M_PI * 2) * 0.3;

      z += i_cycle_ratio * farPlane;
      m = glm::translate(m, {x, y, z});

      m = glm::rotate(m, i_cycle_ratio * (float)DEMOLOOP_M_PI * 2, {0, 0, 1});

      // colors[i] = hsl2rgbf(indexInArm, 1, 0.5);
      colors[i].r = armIndex / arms;
      colors[i].g = 0;
      colors[i].b = 0;
      // colors[i].a = 1;
      colors[i].a = 1 - pow(1 - i_cycle_ratio, 5);
    }

    shader.attach();
    shader.sendFloat("cycle_ratio", 1, &cycle_ratio, 1);

    uint32_t modelViewsLocation = shader.getAttribLocation("modelViews");
    uint32_t enabledAttribs = bufferMatrixAttribute(modelViewsLocation, modelViewsBuffer, &matrices[0][0][0], numTris, GL_STREAM_DRAW);

    gl.prepareDraw();

    uint32_t colorsLocation = shader.getAttribLocation("colors");
    glBindBuffer(GL_ARRAY_BUFFER, colorsBuffer);
    glBufferData(GL_ARRAY_BUFFER, numTris * sizeof(glm::vec4), &colors[0].x, GL_STREAM_DRAW);
    glVertexAttribPointer(colorsLocation, 4, GL_FLOAT, GL_FALSE, sizeof(glm::vec4), 0);
    glVertexAttribDivisor(colorsLocation, 1);

    enabledAttribs |= ATTRIBFLAG_POS |
                      ATTRIBFLAG_COLOR |
                      ATTRIBFLAG_TEXCOORD |
                      (1u << normalsLocation) |
                      (1u << colorsLocation);
    gl.useVertexAttribArrays(enabledAttribs);
    gl.drawArraysInstanced(GL_TRIANGLES, 0, numVertices, numTris);
    shader.detach();
  }

private:
  uint32_t normalsLocation;
  glm::mat4 matrices[numTris];
  glm::vec4 colors[numTris];
  Shader shader;
  GLuint modelViewsBuffer;
  GLuint normalsBuffer;
  GLuint colorsBuffer;
};

int main(int, char**){
  Loop048 test;
  test.Run();

  return 0;
}


text:
package och.comp.db.base.universal;

import och.comp.db.base.universal.CreateRow;

public class CreateUser extends CreateRow {

	public CreateUser(long id, String name) {
		super("user", new IdField(id), new NameField(name));
	}

}


text:
Closures as input parameters are possible so returning one should also be
possible. However, returning closure types are problematic because Rust
currently only supports returning concrete (non-generic) types. Anonymous
closure types are, by definition, unknown and so returning a closure is only
possible by making it concrete. This can be done via boxing.

The valid types for returns are slightly different than before:

* `Fn`: normal
* `FnMut`: normal
* `FnBox`: equivalent to `FnOnce` but specialized for this application
because `FnOnce` currently interacts badly with the type system.

Beyond this, the `move` keyword must be used which signals that all captures
occur by value. This is required because any captures by reference would be
dropped as soon as the function exited leaving invalid references in the
closure.

{output_parameters.play}

### See also:

[Boxing][box], [`Fn`][fn], [`FnMut`][fnmut], [`FnBox`][fnbox], and
[Generics][generics]

[box]: /std/box.html
[fn]: http://doc.rust-lang.org/std/ops/trait.Fn.html
[fnmut]: http://doc.rust-lang.org/std/ops/trait.FnMut.html
[fnbox]: http://doc.rust-lang.org/std/boxed/trait.FnBox.html
[generics]: /generics.html


text:
<?php

namespace StoryWator\Http\Controllers;

use Illuminate\Http\Request;

use StoryWator\Http\Requests;

use App;

use Log;

class HomeController extends Controller
{
    protected $storageRoot_;
    protected $locale_;
    protected $chapterOnce_;
    protected $animateNames_ = array();
    public function __construct() {
        $this->txtRoot_= '/opt/watorvapor/repository.wator/story';
        $this->locale_='zh';
        $this->chapterOnce_=45;
        $this->animateNames_[]= 'type';
        $this->animateNames_[]= 'type2';
        $this->animateNames_[]= 'type3';
        $this->animateNames_[]= 'type4';
        $this->animateNames_[]= 'type5';
        $this->animateNames_[]= 'type6';
        $this->animateNames_[]= 'type7';
        $this->animateNames_[]= 'type8';
        $this->animateNames_[]= 'read';
        $this->animateNames_[]= 'read2';
        $this->animateNames_[]= 'read3';
        $this->animateNames_[]= 'write';
        $this->animateNames_[]= 'think';
        $this->animateNames_[]= 'think2';
        $this->animateNames_[]= 'think3';
        $this->animateNames_[]= 'think4';
        $this->animateNames_[]= 'think5';
    }
    /**
    * Display a listing of the resource.
    *
    * @return \Illuminate\Http\Response
    */
    public function index($position = null)
    {
        //
        $index = rand(0,sizeof($this->animateNames_) -1);
        $animate = $this->animateNames_[$index];
        $data = ['animate'=>$animate];
        $cmd = 'find ' . $this->txtRoot_ . ' -mindepth 2 -maxdepth 2 -type d | sort -t / -k 7 -n';
        //Log::info($cmd);
        $output = shell_exec($cmd);
        //Log::info($output);
        $folders = explode("\n",$output);
        //Log::info($folders);
        $chaptersInfo = array();
        $chaptersCounter = 0;
        foreach ($folders as $value) {
            //Log::info('$value=<' . $value . '>');
            $titlePath = $value . '/title';
            //Log::info('$value=<' . $titlePath . '>');
            if( file_exists($titlePath) ) {
                //Log::info($value);
                $chapter = str_replace($this->txtRoot_ ,'',$value);
                $pieces = explode("/",$chapter);
                //Log::info($pieces);
                if($pieces[1] == $this->locale_) {
                    if($chaptersCounter >= $this->chapterOnce_) {
                        break;
                    }
                    $title = file_get_contents($titlePath);
                    //Log::info($title);
                    //Log::info($pieces[2]);
                    $chaptersInfo[$pieces[2]] = $title;
                    $chaptersCounter++;
                }
            }
        }
        //Log::info($chaptersInfo);
        $data['chapters'] = $chaptersInfo;
        return view('home',$data);
    }

    /**
    * Show the form for creating a new resource.
    *
    * @return \Illuminate\Http\Response
    */
    public function create()
    {
        //
    }

    /**
    * Store a newly created resource in storage.
    *
    * @param  \Illuminate\Http\Request  $request
    * @return \Illuminate\Http\Response
    */
    public function store(Request $request)
    {
        //
    }

    /**
    * Display the specified resource.
    *
    * @param  int  $id
    * @return \Illuminate\Http\Response
    */
    public function show($id)
    {
        //
    }

    /**
    * Show the form for editing the specified resource.
    *
    * @param  int  $id
    * @return \Illuminate\Http\Response
    */
    public function edit($id)
    {
        //
    }

    /**
    * Update the specified resource in storage.
    *
    * @param  \Illuminate\Http\Request  $request
    * @param  int  $id
    * @return \Illuminate\Http\Response
    */
    public function update(Request $request, $id)
    {
        //
    }

    /**
    * Remove the specified resource from storage.
    *
    * @param  int  $id
    * @return \Illuminate\Http\Response
    */
    public function destroy($id)
    {
        //
    }
}