text:
package at.ac.univie.mminf.luceneSKOS.queryparser.flexible.standard;

import java.io.IOException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.flexible.core.QueryNodeException;
import org.apache.lucene.queryparser.flexible.standard.StandardQueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import at.ac.univie.mminf.luceneSKOS.analysis.SKOSAnalyzer;
import at.ac.univie.mminf.luceneSKOS.analysis.SKOSAnalyzer.ExpansionType;
import at.ac.univie.mminf.luceneSKOS.analysis.tokenattributes.SKOSTypeAttribute.SKOSType;
import at.ac.univie.mminf.luceneSKOS.mock.SKOSEngineMock;
import at.ac.univie.mminf.luceneSKOS.util.TestUtil;

public class SKOSStandardQueryParserTest {

  protected final Version matchVersion = Version.LUCENE_45;

  protected IndexSearcher searcher;

  protected IndexWriter writer;

  protected SKOSEngineMock skosEngine;

  protected SKOSAnalyzer skosAnalyzer;

  protected Directory directory;

  @Before
  public void setUp() throws Exception {

    // adding some test data
    skosEngine = new SKOSEngineMock();

    skosEngine.addEntry("http://example.com/concept/1", SKOSType.PREF, "jumps");
    skosEngine.addEntry("http://example.com/concept/1", SKOSType.ALT, "leaps",
        "hops");

    skosEngine.addEntry("http://example.com/concept/2", SKOSType.PREF, "quick");
    skosEngine.addEntry("http://example.com/concept/2", SKOSType.ALT, "fast",
        "speedy");

    skosEngine.addEntry("http://example.com/concept/3", SKOSType.PREF, "over");
    skosEngine.addEntry("http://example.com/concept/3", SKOSType.ALT, "above");

    skosEngine.addEntry("http://example.com/concept/4", SKOSType.PREF, "lazy");
    skosEngine.addEntry("http://example.com/concept/4", SKOSType.ALT,
        "apathic", "sluggish");

    skosEngine.addEntry("http://example.com/concept/5", SKOSType.PREF, "dog");
    skosEngine.addEntry("http://example.com/concept/5", SKOSType.ALT, "canine",
        "pooch");

    skosEngine.addEntry("http://example.com/concept/6", SKOSType.PREF,
        "united nations");
    skosEngine.addEntry("http://example.com/concept/6", SKOSType.ALT, "UN");

    skosEngine.addEntry("http://example.com/concept/7", SKOSType.PREF,
        "lazy dog");
    skosEngine.addEntry("http://example.com/concept/7", SKOSType.ALT, "Odie");

    directory = new RAMDirectory();

    skosAnalyzer = new SKOSAnalyzer(matchVersion, skosEngine,
        ExpansionType.LABEL);

    writer = new IndexWriter(directory, new IndexWriterConfig(matchVersion,
        skosAnalyzer));

  }

  @After
  public void tearDown() throws Exception {

    if (writer != null) {
      writer.close();
    }

    if (searcher != null) {
      searcher.getIndexReader().close();
    }

  }

  @Test
  public void queryParserSearch() throws IOException, QueryNodeException {

    Document doc = new Document();
    doc.add(new Field("content", "The quick brown fox jumps over the lazy dog",
        TextField.TYPE_STORED));

    writer.addDocument(doc);

    searcher = new IndexSearcher(DirectoryReader.open(writer, false));

    Query query = new SKOSStandardQueryParser(skosAnalyzer).parse("\"fox jumps\"",
        "content");

    Assert.assertEquals(1, TestUtil.hitCount(searcher, query));

    Assert.assertEquals("content:\"fox (jumps hops leaps)\"", query.toString());
    Assert.assertEquals("org.apache.lucene.search.MultiPhraseQuery", query
        .getClass().getName());

    query = new StandardQueryParser(new StandardAnalyzer(matchVersion)).parse(
        "\"fox jumps\"", "content");
    Assert.assertEquals(1, TestUtil.hitCount(searcher, query));

    Assert.assertEquals("content:\"fox jumps\"", query.toString());
    Assert.assertEquals("org.apache.lucene.search.PhraseQuery", query
        .getClass().getName());

  }

  @Test
  public void queryParserSearchWithBoosts() throws IOException, QueryNodeException {

    Document doc = new Document();
    doc.add(new Field("content", "The quick brown fox jumps over the lazy dog",
        TextField.TYPE_STORED));

    writer.addDocument(doc);

    searcher = new IndexSearcher(DirectoryReader.open(writer, false));

    SKOSStandardQueryParser parser = new SKOSStandardQueryParser(skosAnalyzer);
    parser.setBoost(SKOSType.ALT, 0.5f);

    Query query = parser.parse("\"fox jumps\"", "content");

    Assert.assertEquals(1, TestUtil.hitCount(searcher, query));

    // boosts do not work in phrase queries
    Assert.assertEquals("content:\"fox (jumps hops leaps)\"", query.toString());
    Assert.assertEquals("org.apache.lucene.search.MultiPhraseQuery", query
        .getClass().getName());

    query = parser.parse("fox jumps", "content");

    Assert.assertEquals(1, TestUtil.hitCount(searcher, query));

    Assert.assertEquals("content:fox (content:jumps content:hops^0.5 content:leaps^0.5)", query.toString());
    Assert.assertEquals("org.apache.lucene.search.BooleanQuery", query
        .getClass().getName());

    query = new SKOSStandardQueryParser(new StandardAnalyzer(matchVersion)).parse(
        "fox jumps", "content");
    Assert.assertEquals(1, TestUtil.hitCount(searcher, query));

    Assert.assertEquals("content:fox content:jumps", query.toString());
    Assert.assertEquals("org.apache.lucene.search.BooleanQuery", query
        .getClass().getName());

  }

}


text:
from typing import List

import torch
from torch import nn
from torch.nn import functional as F

from src.modules.normalize import Normalize
from src.resnet.bottleneck_block_v2s4 import create_bottleneck_stage_v2s4
from src.resnet.shared import ResNet_Softmax, SoftmaxMode

class ResNetV2_4Stage_Softmax(ResNet_Softmax):
    normalize: Normalize
    conv1: nn.Conv2d
    bn1: nn.BatchNorm2d
    stage2: nn.Sequential
    stage3: nn.Sequential
    stage4: nn.Sequential
    stage5: nn.Sequential
    avgpool: nn.AdaptiveAvgPool2d
    fc: nn.Linear
    out_channels: int

    def __init__(self, stage_sizes: List[int], n_classes: int):
        super().__init__()

        if len(stage_sizes) != 4:
            raise ValueError("Stage_sizes must have length 4!")
        if n_classes <= 1:
            raise ValueError("N_classes must be greater than 1!")

        self.init_layers(stage_sizes, n_classes)
        self.reset_parameters()
        self.out_channels = n_classes

    def init_layers(self, stage_sizes: List[int], n_classes: int) -> None:
        self.normalize = Normalize(3)
        self.conv1 = nn.Conv2d(3, 64, 7, stride=2, padding=3, bias=False)
        self.bn1 = nn.BatchNorm2d(64)

        self.stage2 = create_bottleneck_stage_v2s4(stage_sizes[0], 64, 64, 256, 1)
        self.stage3 = create_bottleneck_stage_v2s4(stage_sizes[1], 256, 128, 512, 2)
        self.stage4 = create_bottleneck_stage_v2s4(stage_sizes[2], 512, 256, 1024, 2)
        self.stage5 = create_bottleneck_stage_v2s4(stage_sizes[3], 1024, 512, 2048, 2)

        self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
        self.fc = nn.Linear(2048, n_classes)

    def reset_parameters(self) -> None:
        for module in self.modules():
            if isinstance(module, (nn.Conv2d, nn.Linear)):
                nn.init.kaiming_normal_(module.weight, nonlinearity="relu")

    def forward(self, x: torch.Tensor, mode: SoftmaxMode) -> torch.Tensor:
        if x.shape[1:] != (3, 224, 224):
            raise ValueError("Input tensor must have shape [N, C=3, H=224, W=224]!")

        x = self.normalize(x)
        x = self.conv1(x)
        x = self.bn1(x)
        x = F.relu(x, inplace=True)

        x = F.max_pool2d(x, 3, stride=2, padding=1)

        x = self.stage2(x)
        x = self.stage3(x)
        x = self.stage4(x)
        x = self.stage5(x)

        x = self.avgpool(x)
        x = torch.flatten(x, 1)
        x = self.fc(x)

        if mode == SoftmaxMode.LOGITS:
            return x
        elif mode == SoftmaxMode.LOG_SOFTMAX:
            return F.log_softmax(x, dim=1)
        else:
            assert mode == SoftmaxMode.SOFTMAX
            return F.softmax(x, dim=1)

class ResNet50V2_Softmax(ResNetV2_4Stage_Softmax):
    def __init__(self, n_classes: int):
        super().__init__([3, 4, 6, 3], n_classes)

class ResNet101V2_Softmax(ResNetV2_4Stage_Softmax):
    def __init__(self, n_classes: int):
        super().__init__([3, 4, 23, 3], n_classes)

class ResNet152V2_Softmax(ResNetV2_4Stage_Softmax):
    def __init__(self, n_classes: int):
        super().__init__([3, 8, 36, 3], n_classes)

redpajama_set_name: RedPajamaGithub


text:
package com.conversantmedia.mapreduce.example;

import java.io.IOException;
import java.util.StringTokenizer;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;
import org.springframework.stereotype.Service;

import com.conversantmedia.mapreduce.tool.annotation.NamedOutput;

/**
 *
 *
 */
@Service
public class NamedOutputWordCountMapper extends Mapper<LongWritable, Text, Text, LongWritable> {

	private final static LongWritable ONE = new LongWritable(1);

	@NamedOutput("DEBUG")
	private MultipleOutputs<Text, Text> multiOut;

	private final Text word = new Text();

	@Override
	protected void map(LongWritable key, Text value, Context context)
			throws IOException, InterruptedException {
		String line = value.toString();
		StringTokenizer tokenizer = new StringTokenizer(line);
		while (tokenizer.hasMoreTokens()) {
			word.set(tokenizer.nextToken().replaceAll( "\\W", "" ));
			context.write(word, ONE);
		}

		// Debug output
		if (line.length() > 10) {
			multiOut.write("DEBUG", new Text(line.length() + ":"), value);
		}
	}
}


text:
ActiveRecord::Schema.define(version: 20141220204354) do

  create_table "books", force: true do |t|
    t.string   "author",     null: false
    t.string   "title",      null: false
    t.string   "sku",        null: false
    t.float    "price",      null: false
    t.integer  "stock",      null: false
    t.boolean  "reqopt",     null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  add_index "books", ["sku"], name: "index_books_on_sku", unique: true

  create_table "books_courses", id: false, force: true do |t|
    t.integer "book_id"
    t.integer "course_id"
  end

  create_table "courses", force: true do |t|
    t.string   "number",     null: false
    t.string   "section",    null: false
    t.string   "instructor", null: false
    t.string   "department", null: false
    t.string   "term",       null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  add_index "courses", ["department"], name: "index_courses_on_department"
  add_index "courses", ["instructor", "department", "number", "section", "term"], name: "by_course", unique: true
  add_index "courses", ["number"], name: "index_courses_on_number"
  add_index "courses", ["section"], name: "index_courses_on_section"

end


text:
module MachO
  # A generic Mach-O error in execution.
  class MachOError < RuntimeError
  end

  # Raised when a Mach-O file modification fails.
  class ModificationError < MachOError
  end

  # Raised when a Mach-O file modification fails but can be recovered when
  # operating on multiple Mach-O slices of a fat binary in non-strict mode.
  class RecoverableModificationError < ModificationError
    # @return [Integer, nil] The index of the Mach-O slice of a fat binary for
    #   which modification failed or `nil` if not a fat binary. This is used to
    #   make the error message more useful.
    attr_accessor :macho_slice

    # @return [String] The exception message.
    def to_s
      s = super.to_s
      s = "While modifying Mach-O slice #{@macho_slice}: #{s}" if @macho_slice
      s
    end
  end

  # Raised when a file is not a Mach-O.
  class NotAMachOError < MachOError
    # @param error [String] the error in question
    def initialize(error)
      super error
    end
  end

  # Raised when a file is too short to be a valid Mach-O file.
  class TruncatedFileError < NotAMachOError
    def initialize
      super "File is too short to be a valid Mach-O"
    end
  end

  # Raised when a file's magic bytes are not valid Mach-O magic.
  class MagicError < NotAMachOError
    # @param num [Integer] the unknown number
    def initialize(num)
      super "Unrecognized Mach-O magic: 0x#{"%02x" % num}"
    end
  end

  # Raised when a file is a Java classfile instead of a fat Mach-O.
  class JavaClassFileError < NotAMachOError
    def initialize
      super "File is a Java class file"
    end
  end

  # Raised when a fat binary is loaded with MachOFile.
  class FatBinaryError < MachOError
    def initialize
      super "Fat binaries must be loaded with MachO::FatFile"
    end
  end

  # Raised when a Mach-O is loaded with FatFile.
  class MachOBinaryError < MachOError
    def initialize
      super "Normal binaries must be loaded with MachO::MachOFile"
    end
  end

  # Raised when the CPU type is unknown.
  class CPUTypeError < MachOError
    # @param cputype [Integer] the unknown CPU type
    def initialize(cputype)
      super "Unrecognized CPU type: 0x#{"%08x" % cputype}"
    end
  end

  # Raised when the CPU type/sub-type pair is unknown.
  class CPUSubtypeError < MachOError
    # @param cputype [Integer] the CPU type of the unknown pair
    # @param cpusubtype [Integer] the CPU sub-type of the unknown pair
    def initialize(cputype, cpusubtype)
      super "Unrecognized CPU sub-type: 0x#{"%08x" % cpusubtype}" \
        " (for CPU type: 0x#{"%08x" % cputype})"
    end
  end

  # Raised when a mach-o file's filetype field is unknown.
  class FiletypeError < MachOError
    # @param num [Integer] the unknown number
    def initialize(num)
      super "Unrecognized Mach-O filetype code: 0x#{"%02x" % num}"
    end
  end

  # Raised when an unknown load command is encountered.
  class LoadCommandError < MachOError
    # @param num [Integer] the unknown number
    def initialize(num)
      super "Unrecognized Mach-O load command: 0x#{"%02x" % num}"
    end
  end

  # Raised when a load command can't be created manually.
  class LoadCommandNotCreatableError < MachOError
    # @param cmd_sym [Symbol] the uncreatable load command's symbol
    def initialize(cmd_sym)
      super "Load commands of type #{cmd_sym} cannot be created manually"
    end
  end

  # Raised when the number of arguments used to create a load command manually
  # is wrong.
  class LoadCommandCreationArityError < MachOError
    # @param cmd_sym [Symbol] the load command's symbol
    # @param expected_arity [Integer] the number of arguments expected
    # @param actual_arity [Integer] the number of arguments received
    def initialize(cmd_sym, expected_arity, actual_arity)
      super "Expected #{expected_arity} arguments for #{cmd_sym} creation," \
        " got #{actual_arity}"
    end
  end

  # Raised when a load command can't be serialized.
  class LoadCommandNotSerializableError < MachOError
    # @param cmd_sym [Symbol] the load command's symbol
    def initialize(cmd_sym)
      super "Load commands of type #{cmd_sym} cannot be serialized"
    end
  end

  # Raised when a load command string is malformed in some way.
  class LCStrMalformedError < MachOError
    # @param lc [MachO::LoadCommand] the load command containing the string
    def initialize(lc)
      super "Load command #{lc.type} at offset #{lc.view.offset} contains a" \
        " malformed string"
    end
  end

  # Raised when a change at an offset is not valid.
  class OffsetInsertionError < ModificationError
    # @param offset [Integer] the invalid offset
    def initialize(offset)
      super "Insertion at offset #{offset} is not valid"
    end
  end

  # Raised when load commands are too large to fit in the current file.
  class HeaderPadError < ModificationError
    # @param filename [String] the filename
    def initialize(filename)
      super "Updated load commands do not fit in the header of " \
        "#{filename}. #{filename} needs to be relinked, possibly with " \
        "-headerpad or -headerpad_max_install_names"
    end
  end

  # Raised when attempting to change a dylib name that doesn't exist.
  class DylibUnknownError < RecoverableModificationError
    # @param dylib [String] the unknown shared library name
    def initialize(dylib)
      super "No such dylib name: #{dylib}"
    end
  end

  # Raised when a dylib is missing an ID
  class DylibIdMissingError < RecoverableModificationError
    def initialize
      super "Dylib is missing a dylib ID"
    end
  end

  # Raised when attempting to change an rpath that doesn't exist.
  class RpathUnknownError < RecoverableModificationError
    # @param path [String] the unknown runtime path
    def initialize(path)
      super "No such runtime path: #{path}"
    end
  end

  # Raised when attempting to add an rpath that already exists.
  class RpathExistsError < RecoverableModificationError
    # @param path [String] the extant path
    def initialize(path)
      super "#{path} already exists"
    end
  end

  # Raised whenever unfinished code is called.
  class UnimplementedError < MachOError
    # @param thing [String] the thing that is unimplemented
    def initialize(thing)
      super "Unimplemented: #{thing}"
    end
  end
end


text:
file(REMOVE_RECURSE
  "CMakeFiles/matrix_square_root_5.dir/matrix_square_root.cpp.o"
  "matrix_square_root_5.pdb"
  "matrix_square_root_5"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/matrix_square_root_5.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()


text:
<?php

/**
 * @brief 概要テンプレートの解析器。
 */
class SrwSummaryTemplateParser {
  /** @brief テンプレートのソース。 */
  private $source;

  /**
   * @brief コンストラクタ。
   * @param string $source テンプレートのソース。
   */
  public function __construct($source) {
    $this->source = $source;
  }

  /**
   * @brief テンプレートのソースを解析し、テンプレートのインスタンスに変換する。
   * @return SrwSummaryTemplate|null テンプレートのインスタンス。変換に失敗した場合はnull。
   */
  public function parse() {
    if (!$this->source) {
      return null;
    }

    $parser = new Parser(['preprocessorClass' => 'Preprocessor_DOM']);
    $parser->mOptions = new ParserOptions();

    try {
      $dom = $parser->preprocessToDom($this->source, Parser::PTD_FOR_INCLUSION);
      $doc = $dom->node->ownerDocument;
      $xpath = new DOMXPath($doc);

      $summaryTemplateNode = $this->extractSummaryTemplateNode($xpath);
      if ($summaryTemplateNode === null) {
        return null;
      }

      $params = $this->extractTemplateParams($summaryTemplateNode, $xpath);
      $name = $params['name'];
      if (!$name) {
        return null;
      }

      $template = new SrwSummaryTemplate($name);
      $this->addItemsTo($template, $params);

      return $template;
    } catch (Exception $e) {
      return null;
    }
  }

  /**
   * @brief テンプレートのノードを抽出する。
   * @param DOMXPath $xpath XPathオブジェクト。
   * @return DOMNode|null テンプレートのノード。見つからなかった場合はnull。
   */
  private function extractSummaryTemplateNode(DOMXPath $xpath) {
    $templateNodes = $xpath->query('template');
    foreach ($templateNodes as $templateNode) {
      $titleNode = $xpath->query('title', $templateNode)->item(0);
      if ($titleNode !== null) {
        if (trim($titleNode->textContent) === 'Infobox') {
          return $templateNode;
        }
      }
    }

    return null;
  }

  /**
   * @brief テンプレートのパラメータを抽出する。
   * @param DOMNode $templateNode テンプレートのノード。
   * @param DOMXPath $xpath XPathオブジェクト。
   * @return array テンプレートのパラメータの連想配列。
   */
  private function extractTemplateParams(DOMNode $templateNode, DOMXPath $xpath) {
    $params = [];

    $partNodes = $xpath->query('part', $templateNode);
    foreach ($partNodes as $node) {
      list($key, $value) = explode('=', $node->textContent, 2);
      $trimmedKey = trim($key);

      if ($trimmedKey && $value !== null) {
        $params[strtolower($trimmedKey)] = trim($value);
      }
    }

    return $params;
  }

  /**
   * @brief 概要テンプレートに項目を追加する。
   *
   * labelN、dataNという名前のパラメータを探し、それを項目のインスタンスに
   * 変換してテンプレートに追加する。
   *
   * @param SrwSummaryTemplate $template 概要テンプレート。
   * @param array $params テンプレートのパラメータの連想配列。
   */
  private function addItemsTo($template, $params) {
    foreach ($params as $key => $value) {
      $matches = [];
      if (preg_match('/^label(\d+)$/', $key, $matches)) {
        $index = intval($matches[1]);
        $dataKey = "data{$index}";
        if (isset($params[$dataKey])) {
          $template->addItem(
            new SrwSummaryTemplateItem($index, $value, $params[$dataKey])
          );
        }
      }
    }
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mem. N. Y. bot. Gdn 263 (1972)

#### Original name
Psathyrella pratensis A.H. Sm.

### Remarks
null


text:
using namespace boost::spirit;

///////////////////////////////////////////////////////////////////////////////
//[wcl_static_generate_main
int main(int argc, char* argv[])
{
    // create the lexer object instance needed to invoke the generator
    word_count_lexer_tokens<lex::lexertl::actor_lexer<> > word_count; // the token definition

    // open the output file, where the generated tokenizer function will be
    // written to
    std::ofstream out(argc < 2 ? "word_count_lexer_static.hpp" : argv[1]);

    // invoke the generator, passing the token definition, the output stream
    // and the name prefix of the tokenizing function to be generated
    //
    // The suffix "wcl" used below results in a type lexertl::static_::lexer_wcl
    // to be generated, which needs to be passed as a template parameter to the
    // lexertl::static_lexer template (see word_count_lexer_static.cpp).
    return lex::lexertl::generate_static_dfa(word_count, out, "wcl") ? 0 : -1;
}
//]


text:
import os
from skimage import io

info_file = open('signs.info', 'w')
path = '../datasets/training_images/Final_Training/Images'
directories = [d for d in os.listdir(path)
               if os.path.isdir(os.path.join(path, d))]
for d in directories:
    temp_path = os.path.join(path, d)
    file_names = [os.path.join(temp_path, f)
                  for f in os.listdir(temp_path) if f.endswith(".ppm")]
    for item in file_names:
        h, w, channel = io.imread(item).shape
        info_file.write('{0} 1 0 0 {1} {2}\n'.format(item, w, h))

info_file.close()


text:
package services

import com.thoughtworks.xstream.converters._
import com.thoughtworks.xstream.converters.collections._
import com.thoughtworks.xstream._
import com.thoughtworks.xstream.mapper._
import com.thoughtworks.xstream.io._
import models.domain.Claim
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.reflect.ClassTag

/**
  * This class has been borrowed from the url below.
  * http://code.google.com/p/mixedbits-webframework/source/browse/trunk/src/main/scala/net.mixedbits.tools/XStreamConversions.scala
  * http://opensource.org/licenses/mit-license.php
  */
class XStreamListConverter( _mapper : Mapper ) extends AbstractCollectionConverter(_mapper) {
  def canConvert( clazz: Class[_]) = {
    // "::" is the name of the list class, also handle nil
    classOf[::[_]] == clazz || Nil.getClass == clazz
  }

  def marshal( value: Any, writer: HierarchicalStreamWriter, context: MarshallingContext) = {
    val list = value.asInstanceOf[List[_]]
    for ( item <- list ) {
      writeItem(item, context, writer)
    }
  }

  def unmarshal( reader: HierarchicalStreamReader, context: UnmarshallingContext ) = {
    val list = new scala.collection.mutable.ListBuffer[Any]()
    while (reader.hasMoreChildren()) {
      reader.moveDown()
      val item = readItem(reader, context, list)
      list += item
      reader.moveUp()
    }
    list.toList
  }
}
class XStreamSeqConverter[T <: Seq[Any]](fromSeq: Seq[Any] => T)(implicit manifest:ClassTag[T],_mapper:Mapper) extends AbstractCollectionConverter(_mapper) {
  val seqClass = manifest.runtimeClass
  def canConvert( clazz: Class[_]) = {
    seqClass == clazz
  }

  def marshal( value: Any, writer: HierarchicalStreamWriter, context: MarshallingContext) = {
    val list = value.asInstanceOf[Seq[_]]
    for ( item <- list ) {
      writeItem(item, context, writer)
    }
  }

  def unmarshal( reader: HierarchicalStreamReader, context: UnmarshallingContext ) = {
    val list = new ListBuffer[Any]()
    while (reader.hasMoreChildren()) {
      reader.moveDown()
      val item = readItem(reader, context, list)
      list += item
      reader.moveUp()
    }
    fromSeq(list)
  }
}
//class XStreamMapConverter[T <: Map[Any, Any]](fromMap: Seq[Any] => T)(implicit manifest:ClassTag[T],_mapper:Mapper) extends AbstractCollectionConverter(_mapper) {
//  val mapClass = manifest.runtimeClass
//  def canConvert( clazz: Class[_]) = {
//    mapClass == clazz
//  }
//
//  def marshal( value: Any, writer: HierarchicalStreamWriter, context: MarshallingContext) = {
//    val maps = value.asInstanceOf[Map[_, _]]
//    for ( map <- maps ) {
//      writeItem(map, context, writer)
//    }
//  }
//
//  def unmarshal( reader: HierarchicalStreamReader, context: UnmarshallingContext ) = {
//    val list = new ListBuffer[Any]()
//    while (reader.hasMoreChildren()) {
//      reader.moveDown()
//      val item = readItem(reader, context, list)
//      list += item
//      reader.moveUp()
//    }
//    fromMap(list)
//  }
//}
class XStreamTupleConverter( _mapper : Mapper ) extends AbstractCollectionConverter(_mapper) {

  def canConvert( clazz: Class[_]) = {
    clazz.getName.startsWith("scala.Tuple")
  }

  def marshal( value: Any, writer: HierarchicalStreamWriter, context: MarshallingContext) = {
    val product = value.asInstanceOf[Product]
    for ( item <- product.productIterator ) {
      writeItem(item, context, writer)
    }
  }

  def unmarshal( reader: HierarchicalStreamReader, context: UnmarshallingContext ) = {
    val list = new scala.collection.mutable.ListBuffer[AnyRef]()
    while (reader.hasMoreChildren()) {
      reader.moveDown()
      val item = readItem(reader, context, list)
      list += item
      reader.moveUp()
    }
    constructors(list.size).newInstance(list:_*)
  }

  val constructors = 0 to 22 map {
    case 0 => null
    case i => Class.forName("scala.Tuple"+i).getConstructors.head.asInstanceOf[java.lang.reflect.Constructor[AnyRef]]
  }
}

class XStreamSymbolConverter extends SingleValueConverter {
  def toString(value:Any) =
    value.asInstanceOf[Symbol].name

  def fromString(name:String) =
    Symbol(name)

  def canConvert(clazz:Class[_]) =
    classOf[Symbol] == clazz
}

object XStreamConversions {
  private lazy val jsonConverter = XStreamConversions(new XStream(new com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver()))
  def toJson(item:AnyRef) = jsonConverter.toXML(item)

  def fromJson(item:String) = jsonConverter.fromXML(item)

  private lazy val xmlConverter = XStreamConversions(new XStream())
  def toXml(item:AnyRef) = xmlConverter.toXML(item)

  def fromXml(item:String) = xmlConverter.fromXML(item)

  def apply( stream: XStream ):XStream = {
    implicit val mapper = stream.getMapper

    //list
    stream.alias("list", classOf[::[_]])
    stream.alias("list", Nil.getClass)
    stream.registerConverter( new XStreamListConverter(stream.getMapper) )

    //tuples
    for(i <- 1 to 22) stream.alias("tuple",Class.forName("scala.Tuple"+i))
    stream.registerConverter( new XStreamTupleConverter(stream.getMapper) )

    //symbols
    stream.alias("symbol", classOf[Symbol])
    stream.registerConverter( new XStreamSymbolConverter() )

    //various seq implementations
    stream.alias("arrayBuffer",classOf[scala.collection.mutable.ArrayBuffer[_]])
    stream.registerConverter(new XStreamSeqConverter[scala.collection.mutable.ArrayBuffer[Any]](x => new scala.collection.mutable.ArrayBuffer[Any] ++= x))

    stream.alias("listBuffer",classOf[scala.collection.mutable.ListBuffer[_]])
    stream.registerConverter(new XStreamSeqConverter[scala.collection.mutable.ListBuffer[Any]](x => new scala.collection.mutable.ListBuffer[Any] ++= x))

//    stream.alias("map",classOf[scala.collection.mutable.Map[_, _]])
//    stream.registerConverter(new XStreamMapConverter[scala.collection.mutable.Map[_, _]](x => new scala.collection.mutable.Map[_, _] ++= x))

//    stream.registerConverter(new OptionConverter(mapper))
//    stream.alias("claim", classOf[Claim])
    stream
  }
}


text:
using System;
using System.Linq;
using System.Reflection;
using NRules.Fluent;
using NRules.Fluent.Dsl;
using NRules.IntegrationTests.TestAssets;
using NRules.RuleModel;
using Xunit;

namespace NRules.IntegrationTests;

public class RulesLoadTest
{
    [Fact]
    public void Load_AssemblyWithoutRules_Empty()
    {
        //Arrange
        RuleRepository target = CreateTarget();

        //Act
        target.Load(x => x.From(typeof(string).Assembly));
        IRuleSet ruleSet = target.GetRuleSets().First();

        //Assert
        Assert.Empty(ruleSet.Rules);
    }

    [Fact]
    public void Load_InvalidTypes_Empty()
    {
        //Arrange
        RuleRepository target = CreateTarget();

        //Act
        target.Load(x => x.From(typeof(string)));
        IRuleSet ruleSet = target.GetRuleSets().First();

        //Assert
        Assert.Empty(ruleSet.Rules);
    }

    [Fact]
    public void Load_EmptyRule_Throws()
    {
        //Arrange
        RuleRepository target = CreateTarget();

        //Act - Assert
        var ex = Assert.Throws<RuleDefinitionException>(() => target.Load(x => x.NestedTypes().From(typeof(EmptyRule))));
        Assert.Equal(typeof(EmptyRule), ex.RuleType);
    }

    [Fact]
    public void Load_NoActionRule_Throws()
    {
        //Arrange
        RuleRepository target = CreateTarget();

        //Act - Assert
        var ex = Assert.Throws<RuleDefinitionException>(() => target.Load(x => x.NestedTypes().From(typeof(NoActionRule))));
        Assert.Equal(typeof(NoActionRule), ex.RuleType);
    }

    [Fact]
    public void Load_CannotActivateRule_Throws()
    {
        //Arrange
        RuleRepository target = CreateTarget();

        //Act - Assert
        var ex = Assert.Throws<RuleActivationException>(() => target.Load(x => x.NestedTypes().From(typeof(CannotActivateRule))));
        Assert.Equal(typeof(CannotActivateRule), ex.RuleType);
    }

    [Fact]
    public void Load_AssemblyWithRulesToNamedRuleSet_RuleSetNameMatches()
    {
        //Arrange
        RuleRepository target = CreateTarget();

        //Act
        target.Load(x => x
            .NestedTypes()
            .From(ThisAssembly)
            .Where(r => r.RuleType == typeof(ValidRule))
            .To("Test"));
        IRuleSet ruleSet = target.GetRuleSets().First();

        //Assert
        Assert.Equal("Test", ruleSet.Name);
    }

    [Fact]
    public void Load_AssemblyWithRulesToDefaultRuleSet_DefaultRuleSetName()
    {
        //Arrange
        RuleRepository target = CreateTarget();

        //Act
        target.Load(x => x
            .NestedTypes()
            .From(ThisAssembly)
            .Where(r => r.RuleType == typeof(ValidRule)));
        IRuleSet ruleSet = target.GetRuleSets().First();

        //Assert
        Assert.Equal("default", ruleSet.Name);
    }

    [Fact]
    public void Load_FilterRuleByName_MatchingRule()
    {
        //Arrange
        RuleRepository target = CreateTarget();

        //Act
        target.Load(x => x
            .NestedTypes()
            .From(ThisAssembly)
            .Where(r => r.Name.Contains("Valid")));
        IRuleSet ruleSet = target.GetRuleSets().First();

        //Assert
        Assert.Single(ruleSet.Rules);
        Assert.Equal(typeof(ValidRule).FullName, ruleSet.Rules.First().Name);
    }

    [Fact]
    public void Load_FilterRuleByTag_MatchingRule()
    {
        //Arrange
        RuleRepository target = CreateTarget();

        //Act
        target.Load(x => x
            .NestedTypes()
            .From(ThisAssembly)
            .Where(r => r.IsTagged("LoadTest")));
        IRuleSet ruleSet = target.GetRuleSets().First();

        //Assert
        Assert.Single(ruleSet.Rules);
        Assert.Equal("Rule with metadata", ruleSet.Rules.First().Name);
    }

    [Fact]
    public void Add_RuleInstanceInRuleSet_AddedToRepository()
    {
        //Arrange
        var rule = new ValidRule();

        var factory = new RuleDefinitionFactory();
        var ruleDefinition = factory.Create(rule);

        var ruleSet = new RuleSet("MyRuleSet");
        ruleSet.Add(ruleDefinition);

        RuleRepository target = CreateTarget();

        //Act
        target.Add(ruleSet);

        //Assert
        Assert.Single(ruleSet.Rules);
        Assert.Equal(typeof(ValidRule).FullName, ruleSet.Rules.First().Name);
    }

    private Assembly ThisAssembly => GetType().Assembly;

    public RuleRepository CreateTarget()
    {
        return new RuleRepository();
    }

    public class FactType
    {
    }

    public class CannotActivateRule : Rule
    {
        public CannotActivateRule()
        {
            throw new InvalidOperationException("Failed in ctor");
        }

        public override void Define()
        {
        }
    }

    public class EmptyRule : Rule
    {
        public override void Define()
        {
        }
    }

    public class NoActionRule : Rule
    {
        public override void Define()
        {
            When()
                .Match<FactType>();
        }
    }

    public class ValidRule : Rule
    {
        public override void Define()
        {
            When()
                .Match<FactType>();
            Then()
                .Do(ctx => ctx.NoOp());
        }
    }

    [Name("Rule with metadata")]
    [Tag("LoadTest")]
    public class TaggedRule : Rule
    {
        public override void Define()
        {
            When()
                .Match<FactType>();
            Then()
                .Do(ctx => ctx.NoOp());
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Aliso 19(2): 120 (2001)

#### Original name
Bordea thaxteri R.K. Benj.

### Remarks
null


text:
namespace service_manager {
class InterfaceRegistry;
}

namespace ui {

// Listens to DeviceDataManager for updates on input-devices and forwards those
// updates to any registered InputDeviceObserverMojo in other processes via
// Mojo IPC. This runs in the mus-ws process.
class InputDeviceServer
    : public service_manager::InterfaceFactory<mojom::InputDeviceServer>,
      public mojom::InputDeviceServer,
      public ui::InputDeviceEventObserver {
 public:
  InputDeviceServer();
  ~InputDeviceServer() override;

  // Registers this instance as a local observer with DeviceDataManager.
  void RegisterAsObserver();
  bool IsRegisteredAsObserver() const;

  // Adds interface with the connection registry so remote observers can
  // connect. You should have already called RegisterAsObserver() to get local
  // input-device event updates and checked it was successful by calling
  // IsRegisteredAsObserver().
  void AddInterface(service_manager::InterfaceRegistry* registry);

  // mojom::InputDeviceServer:
  void AddObserver(mojom::InputDeviceObserverMojoPtr observer) override;

  // ui::InputDeviceEventObserver:
  void OnKeyboardDeviceConfigurationChanged() override;
  void OnTouchscreenDeviceConfigurationChanged() override;
  void OnMouseDeviceConfigurationChanged() override;
  void OnTouchpadDeviceConfigurationChanged() override;
  void OnDeviceListsComplete() override;
  void OnStylusStateChanged(StylusState state) override;

 private:
  // Sends the current state of all input-devices to an observer.
  void SendDeviceListsComplete(mojom::InputDeviceObserverMojo* observer);

  // mojo::InterfaceFactory<mojom::InputDeviceServer>:
  void Create(const service_manager::Identity& remote_identity,
              mojom::InputDeviceServerRequest request) override;

  mojo::BindingSet<mojom::InputDeviceServer> bindings_;
  mojo::InterfacePtrSet<mojom::InputDeviceObserverMojo> observers_;

  // DeviceDataManager instance we are registered as an observer with.
  ui::DeviceDataManager* manager_ = nullptr;

  DISALLOW_COPY_AND_ASSIGN(InputDeviceServer);
};

}  // namespace ui

#endif  // SERVICES_UI_INPUT_DEVICES_INPUT_DEVICE_SERVER_H_


text:
/* Copyright (c) 2006, Sun Microsystems, Inc.
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
	  disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of Sun Microsystems nor the names of its contributors may be used to endorse or promote products derived
	  from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE

*/

#ifdef DELTA_COMPILER

// The zone implements the code cache for optimized methods and contains:
//   1) a lookup table:      "Lookup key -> nmethod"
//   2) the optimized methods (nmethods).

// Implementation:
//   - Each compiled method occupies one chunk of memory.
//   - Like the offset table in oldspace the zone has at table for
//     locating a method given a addess of an instruction.

class ScopeDesc;
class PcDesc;
class relocInfo;

class ZombieLink;

class zone: public CHeapObj {
 public:
  Heap*       methodHeap;     // Contains all nmethods
  Heap*       picHeap;        // Contains all compiled CompiledPICs
  codeTable*  methodTable;    // Hash table: LookupKey --> nmethod
  jumpTable   _jump_table;    // Contains all jump entries

 public:
  // returns the optimized method matching the lookup key, otherwise NULL
  nmethod* lookup(LookupKey* key) { return methodTable->lookup(key); }

 protected:
  nmethod* LRUhand;	// for LRU algorithm; sweeps through iZone

  bool _needsCompaction;
  bool _needsLRUSweep;
  bool _needsSweep;

  int compactTime;	// time of last compaction
  int compactDuration;  // duration of last compaction

  double minFreeFrac; 	// fraction of free space needed at compaction time

 public:
  zone(int& size);

  void* operator new(size_t size) 	{ return AllocateHeap(size, "nmethod zone header"); }

  void clear();

  int capacity() const			{ return methodHeap->capacity(); }

  jumpTable* jump_table() const		{ return (jumpTable*)&_jump_table; }

  void verify_if_often();

  int used();
  int numberOfNMethods() const 		{ return jump_table()->usedIDs; }

  nmethod* allocate(int size);

  void free(nmethod* m);
  void addToCodeTable(nmethod* nm);

  void compact(bool forced = false);
  bool needsCompaction() const 		{ return _needsCompaction; }
  bool needsWork() const 		{ return needsCompaction() || _needsSweep; }
  bool needsSweep() const 		{ return _needsSweep; }
  void doWork();
  void doSweep();
  void flush();
  void flushZombies();
  void flushUnused();

  // Clear all inline caches of all nmethods
  void clear_inline_caches();

  void cleanup_inline_caches();

  int findReplCandidates(int needed);

  bool isDeltaPC(void* p) const;
  bool contains(void *p) const 		{ return methodHeap->contains(p); }

  nmethod* findNMethod(void* start) const;
  nmethod* findNMethod_maybe(void* start) const;  	// slow!

  void nmethods_do(void f(nmethod* nm));
  void PICs_do(void f(PIC* pic));

  // Iterates over all oops is the zone
  void oops_do(void f(oop*));

  void switch_pointers(oop from, oop to);
  void verify();

  void print();

  void print_nmethod_histogram(int size);

  nmethod* first_nm() const 		{ return (nmethod*)(methodHeap->firstUsed()); }
  nmethod* next_nm(nmethod* p) const  	{ return (nmethod*)(methodHeap->nextUsed(p)); }

  PIC* first_pic() const 	{ return (PIC*)(picHeap->firstUsed()); }
  PIC* next_pic(PIC* p) const  	{ return (PIC*)(picHeap->nextUsed(p)); }

  char*    instsStart();
  int	   instsSize();
  int    LRU_time();
  int	   sweeper(int maxVisit, int maxReclaim,
		   int* nvisited = NULL, int* nbytesReclaimed = NULL);
  int    nextNMethodID();

 public:
   void mark_dependents_for_deoptimization();
   void mark_all_for_deoptimization();
   void unmark_all_for_deoptimization();
   void make_marked_nmethods_zombies();

 protected:
  void     print_helper(bool stats);
  void 	   adjustPolicy();
  int    flushNextMethod(int needed);
  inline nmethod* next_circular_nm(nmethod* nm);

  friend void moveInsts(char* from, char* to, int size);
  friend void printAllNMethods();
  friend void sweepTrigger();
};

// holds usage information for nmethods (or index of next free nmethod ID
// if not assigned to any nmethod)
class LRUcount : ValueObj {
 public:
  uint16 unused;	// nmethod prologue clears BOTH fields to 0
  uint16 lastUsed;	// time of last use

  LRUcount() 		{ ShouldNotCallThis(); } // shouldn't create
  void  set(int i) 	{ *(int*)this = i; }
};

extern LRUcount* LRUtable;	// for optimized methods
extern int* LRUflag;	// == LRUtable, just different type for convenience
#endif


text:
package com.emitrom.touch4j.client.ui;

import com.emitrom.touch4j.client.core.config.Event;
import com.emitrom.touch4j.client.core.config.XType;
import com.emitrom.touch4j.client.core.handlers.CallbackRegistration;
import com.emitrom.touch4j.client.core.handlers.nestedlist.NestedListBeforeLoadHandler;
import com.emitrom.touch4j.client.core.handlers.nestedlist.NestedListBeforeSelectHandler;
import com.emitrom.touch4j.client.core.handlers.nestedlist.NestedListChangeHandler;
import com.emitrom.touch4j.client.core.handlers.nestedlist.NestedListItemDoubleTapHandler;
import com.emitrom.touch4j.client.core.handlers.nestedlist.NestedListItemTapHandler;
import com.emitrom.touch4j.client.data.TreeStore;
import com.google.gwt.core.client.JavaScriptObject;

/**
 * NestedListDataView provides a miller column interface to navigate between
 * nested sets and provide a clean interface with limited screen real-estate.
 *
 */
public class NestedListDataView extends Container {

    private TreeStore store;

    protected NestedListDataView(JavaScriptObject config) {
        super(config);
    }

    @Override
    protected native void init()/*-{
		var c = new $wnd.Ext.dataview.NestedList();
		this.@com.emitrom.touch4j.client.core.Component::configPrototype = c.initialConfig;
    }-*/;

    @Override
    protected native JavaScriptObject create(JavaScriptObject config) /*-{
		return new $wnd.Ext.dataview.NestedList(config);
    }-*/;

    public NestedListDataView() {

    }

    public NestedListDataView(TreeStore store) {
        this.store = store;
        setStore(store.getJsObj());
    }

    public void setStore(TreeStore store) {
        setStore(store.getJsObj());
    }

    @Override
    public String getXType() {
        return XType.NESTEDLIST.getValue();
    }

    /**
     * Returns the value of allowDeselect.
     *
     * @return
     */
    public native boolean getAllowDeselect() /*-{
		var nestedlist = this.@com.emitrom.touch4j.client.core.Component::getOrCreateJsObj()();
		return nestedlist.getAllowDeselect();
    }-*/;

    /**
     * Returns the value of backText
     *
     * @return
     */
    public native String getBackText() /*-{
		var nestedlist = this.@com.emitrom.touch4j.client.core.Component::getOrCreateJsObj()();
		return nestedlist.getBackText();
    }-*/;

    /**
     * Returns the value of displayField.
     *
     * @return
     */
    public native String getDisplayField() /*-{
		var nestedlist = this.@com.emitrom.touch4j.client.core.Component::getOrCreateJsObj()();
		return nestedlist.getDisplayField();
    }-*/;

    /**
     * Returns the value of emptyText
     *
     * @return
     */
    public native String getEmptyText() /*-{
		var nestedlist = this.@com.emitrom.touch4j.client.core.Component::getOrCreateJsObj()();
		return nestedlist.getEmptyText();
    }-*/;

    /**
     * Returns the value of loadingText.
     *
     * @return
     */
    public native String getLoadingText() /*-{
		var nestedlist = this.@com.emitrom.touch4j.client.core.Component::getOrCreateJsObj()();
		return nestedlist.getLoadingText();
    }-*/;

    /**
     * Returns the value of title
     */
    public native String getTitle() /*-{
		var nestedlist = this.@com.emitrom.touch4j.client.core.Component::getOrCreateJsObj()();
		return nestedlist.getTitle();
    }-*/;

    /**
     * Returns the value of updateTitleText
     *
     * @return
     */
    public native boolean getUpdateTitleText() /*-{
		var nestedlist = this.@com.emitrom.touch4j.client.core.Component::getOrCreateJsObj()();
		return nestedlist.getUpdateTitleText();
    }-*/;

    /**
     * Returns the value of useTitleAsBackText
     *
     * @return
     */
    public native boolean getUseTitleAsBackText() /*-{
		var nestedlist = this.@com.emitrom.touch4j.client.core.Component::getOrCreateJsObj()();
		return nestedlist.getUseTitleAsBackText();
    }-*/;

    /**
     * Sets the value of allowDeselect.
     *
     * @param allowDeselect
     */
    public native void setAllowDeselect(boolean allowDeselect) /*-{
		var nestedlist = this.@com.emitrom.touch4j.client.core.Component::getOrCreateJsObj()();
		nestedlist.setAllowDeselect(allowDeselect);
    }-*/;

    /**
     * Sets the value of backText
     *
     * @param backText
     */
    public native void setBackText(String backText) /*-{
		var nestedlist = this.@com.emitrom.touch4j.client.core.Component::getOrCreateJsObj()();
		nestedlist.setBackText(backText);
    }-*/;

    /**
     * Sets the value of displayField
     *
     * @param displayField
     */
    public native void setDisplayField(String displayField) /*-{
		var nestedlist = this.@com.emitrom.touch4j.client.core.Component::getOrCreateJsObj()();
		nestedlist.setDisplayField(displayField);
    }-*/;

    /**
     * Sets the value of emptyText
     *
     * @param value
     */
    public native void setEmptyText(String value) /*-{
		var nestedlist = this.@com.emitrom.touch4j.client.core.Component::getOrCreateJsObj()();
		nestedlist.setEmptyText(value);
    }-*/;

    /**
     * Sets the value of loadingText
     *
     * @param value
     */
    public native void setLoadingText(String value) /*-{
		var nestedlist = this.@com.emitrom.touch4j.client.core.Component::getOrCreateJsObj()();
		nestedlist.setLoadingText(value);
    }-*/;

    /**
     * Sets the value of title
     */
    public native void setTitle(String value) /*-{
		var nestedlist = this.@com.emitrom.touch4j.client.core.Component::getOrCreateJsObj()();
		nestedlist.setTitle(value);
    }-*/;

    /**
     * Sets the value of toolbar
     *
     * @param toolbar
     */
    public native void setToolBar(ToolBar toolbar) /*-{
		var nestedlist = this.@com.emitrom.touch4j.client.core.Component::getOrCreateJsObj()();
		nestedlist
				.setToolBar(toolbar.@com.emitrom.touch4j.client.core.Component::getOrCreateJsObj()());
    }-*/;

    /**
     * Sets the value of toolbar
     *
     * @param toolbar
     */
    public native void setToolBar(boolean toolbar) /*-{
		var nestedlist = this.@com.emitrom.touch4j.client.core.Component::getOrCreateJsObj()();
		nestedlist.setToolBar(toolbar);
    }-*/;

    /**
     * Sets the value of updateTitleText
     *
     * @param value
     */
    public native void setUpdateTitleText(String value) /*-{
		var nestedlist = this.@com.emitrom.touch4j.client.core.Component::getOrCreateJsObj()();
		nestedlist.setUpdateTitleText(value);
    }-*/;

    /**
     * Sets the value of useTitleAsBackText.
     *
     * @param value
     */
    public native void setUseTitleAsBackText(boolean value) /*-{
		var nestedlist = this.@com.emitrom.touch4j.client.core.Component::getOrCreateJsObj()();
		nestedlist.setUseTitleAsBackText(value);
    }-*/;

    /**
     * return the store bounds to this nested list
     *
     * @return
     */
    public TreeStore getStore() {
        return this.store;
    }

    /**
     * Fires before a request is made for a new data object
     *
     * @param handler
     */
    public CallbackRegistration addBeforeLoadHandler(NestedListBeforeLoadHandler handler) {
        return this.addWidgetListener(Event.BEFORE_LOAD.getValue(), handler.getJsoPeer());
    }

    /**
     * Fires before a selection is made
     *
     * @param handler
     */
    public CallbackRegistration addBeforeSelectHandler(NestedListBeforeSelectHandler handler) {
        return this.addWidgetListener(Event.BEFORE_SELECT.getValue(), handler.getJsoPeer());
    }

    /**
     * Fires when the user taps a list item
     *
     * @param handler
     */
    public CallbackRegistration addListChangeHandler(NestedListChangeHandler handler) {
        return this.addWidgetListener(Event.LIST_CHANGE.getValue(), handler.getJsoPeer());
    }

    /**
     * Fires when a node is double tapped on
     *
     * @param handler
     */
    public CallbackRegistration addListItemDoubleTapHandler(NestedListItemDoubleTapHandler handler) {
        return this.addWidgetListener(Event.ITEM_DOUBLE_TAP.getValue(), handler.getJsoPeer());
    }

    /**
     * Fires when a node is tapped on
     *
     * @param handler
     */
    public CallbackRegistration addListItemTapHandler(NestedListItemTapHandler handler) {
        return this.addWidgetListener(Event.ITEM_TAP.getValue(), handler.getJsoPeer());
    }

    private native void setStore(JavaScriptObject value)/*-{
		var nestedlist = this.@com.emitrom.touch4j.client.core.Component::getOrCreateJsObj()();
		nestedlist.setStore(value);
    }-*/;

}


text:
Below are some of the amazing things built with Weacast or for the Weacast ecosystem.

## Production Applications

Submit yours by creating a pull request.

### XWind

The XWind application has been deployed at [Airbus](http://www.airbus.com/) to support Flight Testing. This application aims at helping users to plan flight tests optimally by quickly identify airport runways matching specific business conditions (such as [cross-wind](https://oppositelock.kinja.com/watch-the-airbus-a350xwb-demonstrate-extreme-crosswind-1601924648)) based on weather forecast data.

[Watch the video](https://drive.google.com/open?id=16_vEOtqmVVl-vE2bW9qYOLsF6Tar3t_S)

### Kano

The Kano application will be soon deployed at [IRSN](https://www.irsn.fr/EN/Pages/home.aspx) to support nuclear crisis management. This application aims at helping users to assess health risks optimally based on weather forecast data.

[Watch the video](https://drive.google.com/open?id=1gRgnhuBCADdSeWeYwoaKlHBAkjhlszKo)

## Starters, Examples and Tutorials

Submit yours by creating a pull request.


text:
package com.java.a35.newsapp.storage;

import android.provider.BaseColumns;

/**
 * Created by twd2 on 17/9/7.
 */

public final class HistoryData {
    private HistoryData() { }

    public static class HistoryEntry implements BaseColumns {
        public static final String TABLE_NAME = "history";
        public static final String COLUMN_NAME_NEWS_ID = "newsId";
        public static final String COLUMN_NAME_DATA = "data";
    }
}


text:
<button id="tombioReload">Reload</button><button id="tombioContinue">Continue</button>

                <select id="tombioVisualisation"></select>


text:
namespace System.Reflection.Metadata.Ecma335
{
    internal static class MetadataStreamConstants
    {
        internal const int SizeOfMetadataTableHeader = 24;
        internal const uint LargeTableRowCount = 0x00010000;
    }
}


text:
<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

// general home page
$app->get('/', function () use ($app) {
    // This was just testing to make sure the database works
    // $sql = "select * from account";
    // $rows = $app['db']->fetchAll($sql);
    // $app['monolog']->info(sprintf("found %d accounts.", count($rows)));

    $app['monolog']->info('[/] pre-token check');
    $token = $app['security.token_storage']->getToken();
    if ($token !== null) {
        $app['monolog']->info('[/] found a login');
        if ($app['security.authorization_checker']->isGranted('ROLE_ADMIN')) {
            $app['monolog']->info('[/] redirecting to admin');
            $app->redirect(url('admin'));
        }
    }

    return $app['twig']->render('index.html.twig');
})->bind('homepage');

// the admin home page
$app->get('/admin', function () use ($app) {
    $pending = $app['db']->fetchAll("select * from account where account.status = 1");
    $avg_gender = $app['db']->fetchAll("select gender,avg(value) as avg,stddev(value) as stddev from account,makes,transaction where account.type = 0 and account.id = makes.toacc and makes.tid = transaction.id and transaction.memo = 'Salary Payment' group by gender order by gender asc");
    $liked = $app['db']->fetchAll("select * from (select likes.smid, fromacc, toacc, text, count(distinct who) as count from likes,social_media_post,makes where likes.smid = social_media_post.id and likes.smid = makes.smid group by likes.smid, fromacc, toacc, text order by count(distinct who) desc) where ROWNUM <= 10");
    $salary_by_city = $app['db']->fetchAll("select address_city, address_state, avg(value) as avg, stddev(value) as stddev from account,makes,transaction where account.type = 0 and account.id = makes.toacc and makes.tid = transaction.id and transaction.memo = 'Salary Payment' group by account.address_city, account.address_state order by avg(value) desc");
    $friends = $app['db']->fetchAll("select * from (select friend1, count(distinct friend2) as count from is_friends_with group by friend1 order by count(distinct friend2) desc) where ROWNUM <= 10");
    $money = $app['db']->fetchAll("select * from (select fromacc, pos-neg as total from (select fromacc, sum(value) as neg from makes,transaction where makes.tid = transaction.id group by fromacc), (select toacc, sum(value) as pos from makes,transaction where makes.tid = transaction.id group by toacc) where fromacc = toacc and fromacc != 1337 order by pos-neg desc) where rownum <= 10");
    $year = $app['db']->fetchAll("select * from (select extract(year from dob) as year, avg(value) as avg from account,makes,transaction where account.id = makes.toacc and makes.tid = transaction.id and makes.toacc != 1337 and transaction.memo = 'Salary Payment' group by extract(year from dob) order by avg(value) desc) where rownum <= 10");
    $count = $app['db']->fetchAssoc("select c0+c1+c2+c3+c4+c5+c6+c7 as tot from (select count(*) as c0 from account),(select count(*) as c1 from is_friends_with),(select count(*) as c2 from reply),(select count(*) as c3 from social_media_post),(select count(*) as c4 from likes),(select count(*) as c5 from transaction),(select count(*) as c6 from posts),(select count(*) as c7 from makes)");
    return $app['twig']->render('admin_home.html.twig', array(
        $avg_gender[0]["GENDER"].'Count' => $avg_gender[0]["AVG"],
        $avg_gender[1]["GENDER"].'Count' => $avg_gender[1]["AVG"],
        'salarybycity' => $salary_by_city,
        'friends' => $friends,
        'likes' => $liked,
        'pending' => $pending,
        'money' => $money,
        'years' => $year,
        'count' => $count['TOT'],
    ));
})->bind('admin_home');

// admin search page
$app->get('/admin/search', function (Request $req) use ($app) {
    $qq = $req->query->get('q');
    if ($qq) {
        $results = $app['db']->fetchAll("select fromacc as id, pos-neg as money, name, email_address, dob, address_city, address_state from account,(select fromacc, sum(value) as neg from makes,transaction where makes.tid = transaction.id group by fromacc), (select toacc, sum(value) as pos from makes,transaction where makes.tid = transaction.id group by toacc) where fromacc = toacc and fromacc = account.id and fromacc != 1337 and (name like '%$qq%' or email_address like '%$qq%' or id like '%$qq%' or address_city like '%$qq%' or address_state like '%$qq%') order by id asc");
        return $app['twig']->render('admin_search.html.twig', array(
            'count' => count($results),
            'results' => $results,
        ));
    } else {
        return $app['twig']->render('admin_search.html.twig', array(
            'count' => 0,
            'results' => null,
        ));
    }
})->bind('admin_search');

// user home page
$app->get('/user', function () use ($app) {
    $token = $app['security.token_storage']->getToken();
    if (null !== $token) {
        $user = $token->getUser();
    }
    $topTen= $app['db']->fetchAll("select * from (select timestamp, type, value, ID from Transaction, Makes where (fromacc = 1337 or toacc= 1337) and transaction.id=makes.tid order by timestamp desc) where rownum <=10");
    $userID= $app['db'] -> fetchAssoc("select id,name from account where email_address = '$user'");
    $possibleFriends = $app['db']->fetchAll("select * from (select name, count(*) as count from is_friends_with ifw1, is_friends_with ifw2, account where ifw2.friend2 = account.id and ifw1.friend1 != ifw2.friend2 and ifw1.friend2 = ifw2.friend1 and ifw1.friend1 = ? and ifw2.friend2 not in (select friend2 from is_friends_with where friend1 = ?) group by name order by count(*) desc) where rownum <= 10", array($userID['ID'], $userID['ID']));
    return $app['twig']->render('user.html.twig', array(
        "topTen" => $topTen,
        "userID" => $userID,
        "possibleFriends" => $possibleFriends,
    ));
})->bind('user_home');

// user timeline
$app->get('/user/timeline', function () use ($app) {
    $token = $app['security.token_storage']->getToken();
    if (null !== $token) {
        $user = $token->getUser();
        $name = $app['db']->fetchAssoc("select name, id from account where email_address = '$user'");
        $posts = $app['db']->fetchAll("select makes.tid as tid,a1.name as fromname,a2.name as toname,transaction.value as value, transaction.timestamp as tstamp, social_media_post.text as text from social_media_post,makes,transaction,account a1,account a2 where a1.id = makes.fromacc and a2.id = makes.toacc and social_media_post.id = makes.smid and makes.tid = transaction.id and (makes.fromacc in (select friend2 from is_friends_with where friend1 = ?) or makes.toacc in (select friend2 from is_friends_with where friend1 = ?)) order by transaction.timestamp desc", array($name['ID'],$name['ID']));
        return $app['twig']->render('user_timeline.html.twig', array(
            'name' => $name['NAME'],
            'posts' => $posts,
        ));
    } else {
        $app->abort(403);
    }
})->bind('user_timeline');

$app->get('/user/timeline/{id}', function ($id) use ($app) {
    $token = $app['security.token_storage']->getToken();
    if (null !== $token) {
        $user = $token->getUser();
        $name = $app['db']->fetchAssoc("select name, id from account where email_address = '$user'");
        $tid = $app['db']->fetchAssoc("select transaction.id as tid,sm.id as smid,sm.text as text,transaction.value as value,transaction.timestamp as tstamp,transaction.memo as memo,a1.name as fromacc,a2.name as toacc,a1.id as fromaccid,a2.id as toaccid from social_media_post sm,transaction,makes,account a1,account a2 where sm.id = makes.smid and a1.id = makes.fromacc and a2.id = makes.toacc and transaction.id = $id and transaction.id = makes.tid and (makes.fromacc in (select friend2 from is_friends_with where friend1 = ?) or makes.toacc in (select friend2 from is_friends_with where friend1 = ?))", array($name['ID'], $name['ID']));
        $likes = $app['db']->fetchAssoc("select count(*) as likes from likes where likes.smid = ?", array($tid['SMID']));
        $comments = $app['db']->fetchAll("select * from reply,posts,account where posts.who = account.id and posts.sm_post = ? and reply.id = posts.message and (posts.who = ? or posts.who in (select friend2 from is_friends_with where friend1 = ?))", array($tid['SMID'], $name['ID'], $name['ID']));
        if (count($tid) <= 0)
            $app->abort(403);
        else
            return $app['twig']->render('user_timeline_id.html.twig', array(
                'tid' => $tid,
                'comments' => $comments,
                'likes' => $likes['LIKES'],
            ));
    } else {
        $app->abort(403);
    }
})->bind('user_timeline_id');

$app->post('/user/timeline/{id}', function ($id) use ($app) {
    $token = $app['security.token_storage']->getToken();
    if (null !== $token) {
        $user = $token->getUser();
        $name = $app['db']->fetchAssoc("select name, id from account where email_address = '$user'");
        $smid = $app['db']->fetchAssoc("select smid from makes where tid = $id");
        try {
            $liked = $app['db']->fetchAssoc("insert into likes values(?, ?)", array($name['ID'], $smid['SMID']));
        } catch (Exception $e) {}
        return $app->redirect('/user/timeline/'.$id);
    } else {
        $app->abort(403);
    }
});

$app->post('/user/comment/{smid}/{tid}/{id}', function ($smid, $tid, $id, Request $req) use ($app) {
    $token = $app['security.token_storage']->getToken();
    if (null !== $token) {
        $user = $token->getUser();
        $name = $app['db']->fetchAssoc("select name, id from account where email_address = '$user'");
        $info = $req->request->get('comment_text');
        $reply = $app['db']->fetchAssoc("insert into reply values(seq_reply.nextval, CURRENT_TIMESTAMP, ?)", array($info));
        $posts = $app['db']->fetchAssoc("insert into posts values(?, seq_reply.currval, ?)", array($name['ID'], $smid));
        return $app->redirect('/user/timeline/'.$tid);
    } else {
        $app->abort(403);
    }
})->bind('user_comment');

// user profile page
$app->get('/user/{id}', function ($id) use ($app) {
    $token = $app['security.token_storage']->getToken();
    if ($token !== null) {
        $user = $token->getUser();
        $name = $app['db']->fetchAssoc("select name, id from account where email_address = '$user'");
        $friends = $app['db']->fetchAssoc("select account.name from is_friends_with, account where friend1 = account.id and friend1 = ? and friend2 = ?", array($id, $name['ID']));
        if (!$friends && $name['ID'] != 1337)
            return $app->redirect('/user');

        $posts = $app['db']->fetchAll("select * from (select social_media_post.id, social_media_post.timestamp, text from social_media_post, account, makes where social_media_post.id = makes.smid and (makes.fromacc = account.id or makes.toacc = account.id) and account.id = ? order by timestamp desc) where rownum <= 10", array($id));
        if ($friends)
            $username = $friends['NAME'];
        else {
            $fname = $app['db']->fetchAssoc("select name from account where id = $id");
            $username = $fname['NAME'];
        }
        return $app['twig']->render('user_profile.html.twig', array(
            "username" => $username,
            "posts" => $posts
        ));
    } else {
        $app->abort(403);
    }
})->bind('user_profile');

// user edit page (can only view your own, or admin can view all)
$app->get('/user/edit/{id}', function ($id) use ($app) {
    return $app['twig']->render('index.html.twig');
})->bind('user_edit');

// login page
$app->get('/login', function (Request $request) use ($app) {
    return $app['twig']->render('login.html.twig', array(
        'error' => $app['security.last_error']($request),
        'last_username' => $app['session']->get('_security.last_username'),
    ));
})->bind('login');

// admin login page
$app->get('/secret/login', function (Request $request) use ($app) {
    return $app['twig']->render('secret_login.html.twig', array(
        'error' => $app['security.last_error']($request),
        'last_username' => $app['session']->get('_security.last_username'),
    ));
})->bind('secret_login');

// error handler
$app->error(function (\Exception $e, Request $request, $code) use ($app) {
    if ($app['debug']) {
        return;
    }

    // 404.html, or 40x.html, or 4xx.html, or error.html
    $templates = array(
        'errors/'.$code.'.html.twig',
        'errors/'.substr($code, 0, 2).'x.html.twig',
        'errors/'.substr($code, 0, 1).'xx.html.twig',
        'errors/default.html.twig',
    );

    return new Response($app['twig']->resolveTemplate($templates)->render(array('code' => $code)), $code);
});


text:
var Collection = module.exports = function() {
  this.artifacts = {};
};

Collection.prototype.add = function(artifact) {
  if (!this.artifacts.hasOwnProperty(artifact.name))
    this.artifacts[artifact.name] = {};
  this.artifacts[artifact.name][artifact.version] = artifact;
};

Collection.prototype.toJSON = function() {
 return this.artifacts;
};


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

using Microsoft.WindowsAzure.Commands.Utilities.Common;

namespace Microsoft.WindowsAzure.Commands.ServiceManagement.Model
{
    public class OSVersionsContext : ManagementOperationContext
    {
        public string Family { get; set; }

        public string FamilyLabel { get; set; }

        public bool IsActive { get; set; }

        public bool IsDefault { get; set; }

        public string Label { get; set; }

        public string Version { get; set; }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Web;
using System.Net.Mail;
using System.Configuration;
using System.Net;

namespace Aurora.Helpers
{
    public enum MailTypes {
        RegistrationRequest,
        RegistrationSuccessful,
        AccountConnected,
        RegisteredForPlacements,
        RequestPlacementRegistration,
        Notification,
        TestMail
    };

    public class Mailer
    {
        static string host = ConfigurationManager.AppSettings["EmailHost"];
        static string username = ConfigurationManager.AppSettings["Username"];
        static string password = ConfigurationManager.AppSettings["Password"];
        static int port = int.Parse(ConfigurationManager.AppSettings["Port"]);

        public static string LoadTemplate(MailTypes Type, Dictionary<string, string> Values)
        {
            string url = "";

            switch (Type)
            {
                case MailTypes.RegistrationRequest:
                    url = "EmailTemplates\\RegistrationRequest.html"; break;

                case MailTypes.RegistrationSuccessful:
                    url = "EmailTemplates\\RegistrationSuccessful.html"; break;

                case MailTypes.AccountConnected:
                    url = "EmailTemplates\\AccountConnected.html"; break;

                case MailTypes.RegisteredForPlacements:
                    url = "EmailTemplates\\RegisteredForPlacements.html"; break;

                case MailTypes.RequestPlacementRegistration:
                    url = "EmailTemplates\\RequestPlacementRegistration.html"; break;

                case MailTypes.Notification:
                    url = "EmailTemplates\\Notification.html"; break;

                case MailTypes.TestMail:
                    url = "EmailTemplates\\Test.html"; break;
            }

            var body = File.ReadAllText(url);
            foreach (var key in Values.Keys)
            {
                body = body.Replace("{{" + key + "}}", Values[key]);
            }

            return body;
        }

        public static void SendMail(string[] Recipients, string body, MailTypes Type)
        {
            var message = new MailMessage();
            message.IsBodyHtml = true;
            message.From = new MailAddress(username, "Support@CIR");
            message.Body = body;
            message.Subject = "No-Reply: " + Type.ToString();

            foreach (var recipient in Recipients)
            {
                message.To.Add(new MailAddress(recipient));
            }

            var mailer = new SmtpClient(host, port);
            mailer.EnableSsl = true;
            mailer.Credentials = new NetworkCredential(username, password);
            mailer.Send(message);
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project
        xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.whirlwin</groupId>
    <artifactId>guava-extras</artifactId>
    <version>1.0.0-SNAPSHOT</version>

    <properties>
        <jdk.version>1.8</jdk.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>

            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>${jdk.version}</source>
                    <target>${jdk.version}</target>
                </configuration>
            </plugin>

            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.17</version>
                <configuration>
                    <includes>
                        <include>**/*Test.java</include>
                    </includes>
                </configuration>
            </plugin>

        </plugins>
    </build>

    <licenses>
        <license>
            <name>The MIT License (MIT)</name>
            <url>https://raw.githubusercontent.com/whirlwin/guava-extras/master/LICENSE</url>
            <distribution>repo</distribution>
        </license>
    </licenses>

    <scm>
        <url>https://github.com/whirlwin/guava-extras</url>
        <connection>scm:git:https://github.com/whirlwin/guava-extras.git</connection>
        <developerConnection>scm:git:git@github.com:whirlwin/guava-extras.git</developerConnection>
      <tag>HEAD</tag>
  </scm>

</project>


text:
require 'bundler'
Bundler.require(:default, :development)


text:
<?php

namespace App\Repository;

use App\Entity\Item;
use App\Entity\Source;
use App\Entity\User;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\ORM\QueryBuilder;
use Doctrine\ORM\Tools\Pagination\Paginator;
use Exception;

/**
 * ItemRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class ItemRepository extends ServiceEntityRepository
{
    use PaginatorTrait;

    const EVENT_LIFETIME = 2;

    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Item::class);
    }

    /**
     * @param int $results
     * @return Item[]
     */
    public function findLast($results): array
    {
        return $this->createQueryBuilder('i')
            ->leftJoin('i.source', 's')
            ->addSelect('s')
            ->orderBy('i.publishedAt', 'DESC')
            ->setMaxResults($results)
            ->getQuery()
            ->getResult();
    }

    public function findMainPaginated(int $page, int $limit): Paginator
    {
        $query = $this->createQueryBuilder('i')
            ->leftJoin('i.source', 's')
            ->addSelect('s')
            ->where('s.visibility = :visibility')
            ->andWhere('s.isEnabled = true')
            ->setParameter('visibility', Source::VISIBILITY_MAIN)
            ->orderBy('i.publishedAt', 'DESC')
            ->getQuery();

        return $this->paginate($query, $page, $limit);
    }

    public function findUserFeedPaginated(User $user, int $page, int $limit): Paginator
    {
        $currentDate = new \DateTime;

        $qb = $this->createQueryBuilder('i');
        $qb->addSelect('s')
            ->leftJoin('i.source', 's')
            ->leftJoin('s.subscriptions', 'sb')
            ->where('sb.user = :user')
            ->andWhere('s.isEnabled = true')
            ->andWhere('sb.expireAt IS NULL OR sb.expireAt > :currentDate')
            ->setParameter('currentDate', $currentDate)
            ->setParameter('user', $user)
            ->orderBy('i.publishedAt', 'DESC');
        $this->applyVisibilityCriteria($qb, $user);

        return $this->paginate($qb->getQuery(), $page, $limit);
    }

    public function findPaginatedByTagId(int $id, int $page, int $limit, ?User $user): Paginator
    {
        $qb = $this->createQueryBuilder('i')
            ->leftJoin('i.source', 's')
            ->leftJoin('s.tags', 't')
            ->addSelect('s')
            ->where('t.id = :tag_id')
            ->andWhere('s.isEnabled = true')
            ->setParameter('tag_id', $id)
            ->orderBy('i.publishedAt', 'DESC');
        $this->applyVisibilityCriteria($qb, $user);

        return $this->paginate($qb->getQuery(), $page, $limit);
    }

    public function findEventsPaginated(int $page, int $limit, ?User $user): Paginator
    {
        $qb = $this->createQueryBuilder('i')
            ->leftJoin('i.source', 's')
            ->leftJoin('s.tags', 't')
            ->addSelect('s')
            ->where('i.startDate IS NOT NULL')
            ->andWhere('i.startDate > :date')
            ->andWhere('s.isEnabled = true')
            ->setParameter('date', new \DateTime(sprintf('-%s days', self::EVENT_LIFETIME)))
            ->orderBy('i.startDate', 'ASC');
        $this->applyVisibilityCriteria($qb, $user);

        return $this->paginate($qb->getQuery(), $page, $limit);
    }

    public function getQueryBuilderBySourceId(int $id): QueryBuilder
    {
        return $this->createQueryBuilder('i')
            ->leftJoin('i.source', 's')
            ->addSelect('s')
            ->where('s.id = :source_id')
            ->setParameter('source_id', $id);
    }

    /**
     * @param int $id
     * @return int
     * @throws Exception
     */
    public function getCountBySourceId(int $id): int
    {
        return $this->getQueryBuilderBySourceId($id)
            ->select('count(i.id)')
            ->getQuery()
            ->getSingleScalarResult();
    }

    public function findPaginatedBySourceId(int $id, int $page, int $limit): Paginator
    {
        $query = $this->getQueryBuilderBySourceId($id)
            ->orderBy('i.publishedAt', 'DESC')
            ->getQuery();

        return $this->paginate($query, $page, $limit);
    }

    public function findPaginatedByPhrase(string $phrase, int $page, int $limit, ?User $user): Paginator
    {
        $qb = $this->createQueryBuilder('i')
            ->leftJoin('i.source', 's')
            ->addSelect('s')
            ->orderBy('i.publishedAt', 'DESC');
        $this->applyVisibilityCriteria($qb, $user);

        foreach (explode(' ', $phrase) as $i => $word) {
            $qb->andWhere('i.title like :word_' . $i)
                ->setParameter('word_' . $i, '%' . $word . '%');
        }

        return $this->paginate($qb->getQuery(), $page, $limit);
    }

    public function deleteOld(): int
    {
        $result = $this->createQueryBuilder('i')
            ->select('i.id')
            ->join('i.source', 's')
            ->where("i.publishedAt < DATE_SUB(CURRENT_DATE(), (s.itemsDaysToLive - 1), 'day')")
            ->getQuery()->getArrayResult();

        $ids = array_column($result, "id");

        return $this->createQueryBuilder('i')
            ->delete()
            ->where("i.id IN(:ids)")
            ->setParameter('ids', $ids)
            ->getQuery()
            ->execute();
    }

    public function deleteBySource(Source $source): int
    {
        return $this->createQueryBuilder('i')
            ->delete()
            ->where('i.source = :source')
            ->setParameter('source', $source)
            ->getQuery()
            ->execute();
    }

    private function applyVisibilityCriteria(QueryBuilder $qb, ?User $user)
    {
        $exprForPrivate = null;
        $exprForProtected = null;
        $exprForPublic = $qb->expr()->in('s.visibility', ':public');

        if ($user) {
            $exprForPrivate = $qb->expr()->andX(
                $qb->expr()->eq('s.visibility', ':private'),
                $qb->expr()->eq('s.createdBy', ':user')
            );
            $exprForProtected = $qb->expr()->eq('s.visibility', ':protected');
            $qb->setParameter('user', $user)
                ->setParameter('private', Source::VISIBILITY_PRIVATE)
                ->setParameter('protected', Source::VISIBILITY_PROTECTED);
        }

        $qb->andWhere($qb->expr()->orX($exprForPublic, $exprForProtected, $exprForPrivate))
            ->setParameter('public', [
                Source::VISIBILITY_MAIN,
                Source::VISIBILITY_PUBLIC,
            ]);
    }
}


text:
using content::BrowserThread;

namespace browser_sync {

AutofillDataTypeController::AutofillDataTypeController(
    ProfileSyncComponentsFactory* profile_sync_factory,
    Profile* profile,
    ProfileSyncService* sync_service)
    : NewNonFrontendDataTypeController(
        profile_sync_factory, profile, sync_service) {
}

AutofillDataTypeController::~AutofillDataTypeController() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}

bool AutofillDataTypeController::PostTaskOnBackendThread(
    const tracked_objects::Location& from_here,
    const base::Closure& task) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  return BrowserThread::PostTask(BrowserThread::DB, from_here, task);
}

bool AutofillDataTypeController::StartModels() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK_EQ(MODEL_STARTING, state());

  web_data_service_ = profile()->GetWebDataService(Profile::IMPLICIT_ACCESS);
  if (web_data_service_->IsDatabaseLoaded()) {
    return true;
  } else {
    notification_registrar_.Add(
        this, chrome::NOTIFICATION_WEB_DATABASE_LOADED,
        content::Source<WebDataService>(web_data_service_.get()));
    return false;
  }
}

void AutofillDataTypeController::Observe(
    int notification_type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK_EQ(chrome::NOTIFICATION_WEB_DATABASE_LOADED, notification_type);
  DCHECK_EQ(MODEL_STARTING, state());
  notification_registrar_.RemoveAll();
  set_state(ASSOCIATING);
  if (!StartAssociationAsync()) {
    SyncError error(FROM_HERE, "Failed to post association task.", type());
    StartDoneImpl(ASSOCIATION_FAILED, DISABLED, error);
  }
}

void AutofillDataTypeController::StopModels() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(state() == STOPPING || state() == NOT_RUNNING || state() == DISABLED);
  DVLOG(1) << "AutofillDataTypeController::StopModels() : State = " << state();
  notification_registrar_.RemoveAll();
}

syncable::ModelType AutofillDataTypeController::type() const {
  return syncable::AUTOFILL;
}

browser_sync::ModelSafeGroup AutofillDataTypeController::model_safe_group()
    const {
  return browser_sync::GROUP_DB;
}

}  // namespace browser_sync


text:
namespace hana = boost::hana;

constexpr std::integer_sequence<int, 1, 2, 3, 4> xs{};
constexpr std::integer_sequence<long, 1, 2, 3, 4> ys{};
constexpr std::integer_sequence<long, 1, 2, 3, 4, 5> zs{};

BOOST_HANA_CONSTANT_CHECK(hana::equal(xs, ys));
BOOST_HANA_CONSTANT_CHECK(hana::not_equal(xs, zs));
BOOST_HANA_CONSTANT_CHECK(hana::not_equal(ys, zs));

int main() { }


text:
# Dockerfile that creates a container suitable to build dotnet-cli
FROM fedora:23

# Install the base toolchain we need to build anything (clang, cmake, make and the like)
# this does not include libraries that we need to compile different projects, we'd like
# them in a different layer.
RUN dnf install -y cmake \
        clang \
        make \
        which \
        tar \
        git \
        findutils && \
    dnf clean all

# Dependencies of CoreCLR and CoreFX.
RUN dnf install -y libicu \
        libuuid \
        libcurl \
        openssl-libs \
        libunwind \
        lttng-ust

RUN dnf upgrade -y nss

RUN dnf clean all

# Setup User to match Host User, and give superuser permissions
ARG USER_ID=0
RUN useradd -m code_executor -u ${USER_ID} -g wheel
RUN echo 'code_executor ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers

# With the User Change, we need to change permissions on these directories
RUN chmod -R a+rwx /usr/local
RUN chmod -R a+rwx /home

# Set user to the one we just created
USER ${USER_ID}

# Set working directory
WORKDIR /opt/code


text:
package org.lpw.ranch.snapshot;

import org.lpw.tephra.ctrl.context.Request;
import org.lpw.tephra.ctrl.execute.Execute;
import org.lpw.tephra.ctrl.validate.Validate;
import org.lpw.tephra.ctrl.validate.Validators;
import org.springframework.stereotype.Controller;

import javax.inject.Inject;

/**
 * @author lpw
 */
@Controller(SnapshotModel.NAME + ".ctrl")
@Execute(name = "/snapshot/", key = SnapshotModel.NAME, code = "119")
public class SnapshotCtrl {
    @Inject
    private Request request;
    @Inject
    private SnapshotService snapshotService;

    @Execute(name = "get", validates = {
            @Validate(validator = Validators.NOT_EMPTY, parameter = "ids", failureCode = 1),
            @Validate(validator = Validators.SIGN)
    })
    public Object get() {
        return snapshotService.get(request.getAsArray("ids"));
    }

    @Execute(name = "create", validates = {
            @Validate(validator = Validators.NOT_EMPTY, parameter = "data", failureCode = 2),
            @Validate(validator = Validators.SIGN)
    })
    public Object create() {
        return snapshotService.create(request.get("data"), request.get("content"));
    }
}