text:
package io.irontest.utils;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xmlunit.XMLUnitException;
import org.xmlunit.builder.DiffBuilder;
import org.xmlunit.diff.ComparisonResult;
import org.xmlunit.diff.Diff;
import org.xmlunit.diff.Difference;
import org.xmlunit.diff.DifferenceEvaluators;
import org.xmlunit.placeholder.PlaceholderDifferenceEvaluator;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Iterator;

public final class XMLUtils {
    /**
     * If the input string is well formed XML, return its pretty-print format. Otherwise, return it as is.
     * If the input is null, return null.
     * @param input
     * @return
     * @throws TransformerException
     */
    public static String prettyPrintXML(String input) throws TransformerException, XPathExpressionException {
        if (input == null) {
            return null;
        } else {
            Document doc;
            try {
                doc = XMLUtils.xmlStringToDOM(input);
            } catch (Exception e) {
                //  the input string is not well formed XML
                return input;
            }

            //  Remove blank text nodes from doc (if a blank text node is the only child of a parent node, leave it untouched. e.g. <c>    </c> will not become <c/>).
            //  A blank text node is a text node containing one or more whitespaces.
            //  This code block is used to mitigate a Transformer issue introduced since Java 9. Refer to http://java9.wtf/xml-transformer/.
            //      For Transformer since Java 9, text node that is sibling of element is treated like an element.
            //          e.g. ccc123 will be pretty printed as
            //
            //              ccc
            //              123
            //            .
            //      If such a text node is blank, the output xml will contain an empty/blank line.
            //          e.g.  123 will be pretty printed as
            //
            //
            //              123
            //
            XPathFactory xpathFactory = XPathFactory.newInstance();
            XPathExpression xpathExp = xpathFactory.newXPath().compile("//text()[normalize-space(.) = '']");
            NodeList blankTextNodes = (NodeList) xpathExp.evaluate(doc, XPathConstants.NODESET);
            for (int i = 0; i < blankTextNodes.getLength(); i++) {
                Node blankTextNode = blankTextNodes.item(i);
                if (blankTextNode.getNextSibling() != null || blankTextNode.getPreviousSibling() != null) {
                    blankTextNode.getParentNode().removeChild(blankTextNode);
                }
            }

            //  pretty print the xml
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
            if (input.startsWith("<?xml")) {
                transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "yes");  // add line break after xml declaration
            } else {
                transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            }
            StreamResult result = new StreamResult(new StringWriter());
            DOMSource source = new DOMSource(doc);
            transformer.transform(source, result);
            return result.getWriter().toString();
        }
    }

    public static String domNodeListToString(NodeList nodeList) throws TransformerException {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            sb.append(domNodeToString(node));
            // Below formatting will cause xpath assertion verification failure when
            // xpath evaluation result is of type NODESET.
            //sb.append(System.getProperty("line.separator"));
        }
        return sb.toString();
    }

    public static String domNodeToString(Node node) throws TransformerException {
        StringWriter writer = new StringWriter();
        if (node.getNodeType() == Node.TEXT_NODE) {
            writer.write(node.getTextContent());
        } else if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
            writer.write(node.getNodeValue());
        } else {  // this block of code will always transform text node or attribute node to empty string, so handle them separately
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.transform(new DOMSource(node), new StreamResult(writer));
        }

        return writer.toString();
    }

    /**
     * Parse input xml string into a DOM document, with namespace unaware.
     * @param xml
     * @return
     * @throws ParserConfigurationException
     * @throws IOException
     * @throws SAXException
     */
    public static Document xmlStringToDOM(String xml) throws ParserConfigurationException, IOException, SAXException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setErrorHandler(null);  //  prevent XML parser logging
        return builder.parse(new InputSource(new StringReader(xml)));
    }

    /**
     * Compare XML, with namespace aware.
     * @param control
     * @param test
     * @return differences found, in a format for print
     */
    public static String compareXML(String control, String test) {
        return compareXML(control, test, true);
    }

    /**
     * @param control
     * @param test
     * @param namespaceAware
     * @return differences found, in a format for print
     */
    public static String compareXML(String control, String test, boolean namespaceAware) {
        Object controlObject = control;
        Object testObject = test;

        //  by default XMLUnit parses control and test XML string with namespace aware, and below code can not alter this behavior
        //      DocumentBuilderFactory factory = ...;
        //      factory.setNamespaceAware(false);
        //      DiffBuilder.withDocumentBuilderFactory(factory);
        if (!namespaceAware) {
            try {
                controlObject = xmlStringToDOM(control);
                testObject = xmlStringToDOM(test);
            } catch (Exception e) {
                throw new RuntimeException(e.getCause().getMessage(), e);
            }
        }

        StringBuilder differencesSB = new StringBuilder();
        Diff diff;
        try {
            diff = DiffBuilder
                    .compare(controlObject)
                    .withTest(testObject)
                    .normalizeWhitespace()
                    //  Use custom DifferenceEvaluator in combination with the default DifferenceEvaluator, to utilize
                    //  the default DifferenceEvaluator's feature which turns some DIFFERENT comparison results into
                    //  SIMILAR, such as for different namespace prefixes.
                    .withDifferenceEvaluator(DifferenceEvaluators.chain(
                            DifferenceEvaluators.Default, new PlaceholderDifferenceEvaluator("#\\{", null)))
                    .build();
        } catch (XMLUnitException e) {
            throw new RuntimeException(e.getCause().getMessage(), e);
        }
        if (diff.hasDifferences()) {
            Iterator it = diff.getDifferences().iterator();
            while (it.hasNext()) {
                Difference difference = (Difference) it.next();
                if (difference.getResult() == ComparisonResult.DIFFERENT) {   //  ignore SIMILAR comparison results
                    if (differencesSB.length() > 0) {
                        differencesSB.append("\n");
                    }
                    differencesSB.append(difference.getComparison().toString());
                }
            }
        }
        return differencesSB.toString();
    }
}


text:
master nodes

- etcd
- api server
- scheduler
- controller manager

wording nodes

- kubelet
- kube proxy
- container runtime

Acess k8s cluster

- GUI
- API
- kebectl

Configs are in `~/.kube/config` or
```
$ kubectl config view
```

```
$ kubectl cluster-info
$ kubectl dashboard
```

Get all apis

- run `kubectl proxy` and get `http://localhost://8081`
- use token to visit api server

redpajama_set_name: RedPajamaGithub


text:
import os

def automock(param, default, prod=None, stage=None, test=None, dev=None):
    def inner_decorator(func):
        def new_function(*args, **kwargs):

            # print('dec: %s,%s,%s' % (default, test, server.config['TESTING']))
            # print('dec3: prod %s stage %s test %s %s dev %s' % (prod is not None, stage is not None, test is not None, os.environ['STATUS'], dev is not None,))
            param_value = default
            if 'STATUS' in os.environ:
                if prod is not None and os.environ['STATUS'] == 'PRODUCTION':
                    print('prod case')
                    param_value = prod
                elif stage is not None and os.environ['STATUS'] == 'STAGING':
                    print('stage case')
                    param_value = stage
                elif test is not None and os.environ['STATUS'] == 'TESTING':
                    print('inside param value to tests')
                    param_value = test
                elif dev is not None and os.environ['STATUS'] == 'DEVELOPMENT':
                    print('dev case')
                    param_value = dev
                else:
                    print('default case')
                    param_value = default
            kwargs[param] = param_value
            return func(*args, **kwargs)
        new_function.__name__ = func.__name__
        return new_function
    inner_decorator.__name__ = 'automock'
    return inner_decorator


text:
<!doctype html>

    <meta charset="utf-8">
    <title>Le Bitcoin: l'avènement d'une monnaie virtuelle</title>
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">
    <link rel="stylesheet" href="/static/css/reveal.css">
    <link rel="stylesheet" href="/static/css/default.css" id="theme">
    <link rel="stylesheet" href="/static/css/theme/sky.css">

Le Bitcoin: l'avènement d'une monnaie virtuelle

M1 CMI SID

Axel Bellec

Alexis Conan

Max Halford


text:
.. _cement.ext.ext_logging:

:mod:`cement.ext.ext_logging`
------------------------------

.. automodule:: cement.ext.ext_logging
    :members:
    :show-inheritance:


text:
This is a fork of [Jordan Gensler's Vanilla Pinch NPM Package](https://www.npmjs.com/package/vanillapinch)
# VanillaPinchZoom

VanillaPinchZoom is a fork of PinchZoom.js with no jQuery dependency. The library provides multi touch gestures for zooming and dragging on any DOM element.

Finally, you are free of the shackles of jQuery! All you need is a [modern browser](http://caniuse.com/use-strict).

## Usage

The library exports a CommonJS module, and is designed for use with Browserify. For your conveience, a built version of VanillaPinchZoom is included in `dist/`, which is a standalone Browserify bundle that assigns `VanillaPinchZoom` on the global object.

```Javascript

var VanillaPinchZoom = require('vanillapinchzoom');

var myVanillaPinchZoom = new VanillaPinchZoom(document.querySelector('#your-element'), options);

```

### Options

```Text

tapZoomFactor:      The zoom factor a double tap zooms to. (default 2)
zoomOutFactor:      Resizes to original size when zoom factor is below the configured value. (default 1.3)
animationDuration:  The animation duration in milliseconds. (default 300)
maxZoom:            The maximum zoom factor. (default 4)
minZoom:            The minimum zoom factor. (default 0.5)
lockDragAxis        Locks panning of the element to a single axis. (default false)

```

# Events

Pinchzoom emits some custom events you can listen to

```Text

pz_zoomstart  Started to zoom
pz_zoomend    Stopped zooming
pz_dragstart  Started to drag the element
pz_dragend    Stopped to drag the element
pz_doubletap  Resetting the zoom with doubletab

```

### Methods

```Text

enable:             Enables all gesture capturing (default)
disable:            Disables all gesture capturing

```


text:
layout: page
title: Hancock Company Party
date: 2016-05-24
author: Harry Cochran
tags: weekly links, java
status: published
summary: Donec velit est, facilisis non lorem non, condimentum vestibulum felis.
banner: images/banner/leisure-05.jpg
booking:
  startDate: 07/30/2016
  endDate: 08/03/2016
  ctyhocn: ADEGAHX
  groupCode: HCP
published: true
---
Vivamus sed imperdiet lacus. Aliquam pellentesque pellentesque dui, nec tempus ipsum tempus at. Fusce fermentum odio et quam blandit, vel euismod odio pharetra. Ut in ligula nulla. Donec elementum risus ac ipsum tincidunt, at cursus nisl condimentum. Integer dapibus, urna nec suscipit pulvinar, turpis tellus dapibus nisl, id varius libero sapien vel nisi. Cras tincidunt egestas lorem, quis ultricies metus sodales quis. Aliquam erat volutpat. Nam nec tortor dictum, auctor ipsum id, aliquet sem. Praesent sit amet laoreet tellus, non pharetra eros. Sed consequat aliquam magna, at blandit lorem fermentum ac. Integer tincidunt in nisl ut mattis. Mauris arcu lectus, interdum ac luctus vitae, ultricies in ante. Aliquam gravida felis eget nisl mattis, eget pellentesque dui commodo. Integer semper nec nibh consequat blandit.

1 Vestibulum facilisis nibh in erat ultrices vehicula
1 Vestibulum id ligula sit amet purus efficitur maximus et et massa
1 Sed ut nisi eu nibh vehicula euismod
1 Donec molestie justo in felis sodales consectetur
1 Quisque maximus tortor eget tellus vulputate venenatis a a urna
1 Cras vestibulum neque sit amet lectus faucibus maximus.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla facilisi. Vestibulum bibendum mollis nulla. Nullam at facilisis odio. Nunc iaculis libero et dui suscipit, sit amet euismod tellus tincidunt. Nunc semper velit ut elit bibendum suscipit. Phasellus nec pulvinar felis.
Vivamus sed tincidunt dui, sit amet tempor tortor. Aenean aliquet nisl at nisl fringilla vulputate. Pellentesque sed nulla dictum, porttitor leo at, lacinia sem. Integer rhoncus volutpat velit eu faucibus. Nulla facilisi. Proin ex erat, tincidunt sit amet aliquam vitae, tristique a leo. Proin elementum ut turpis eu mattis.


text:
#include "orc/Common.hh"
#include "orc/OrcFile.hh"

#include "ColumnWriter.hh"
#include "Timezone.hh"

#include <memory>

namespace orc {

  struct WriterOptionsPrivate {
    uint64_t stripeSize;
    uint64_t compressionBlockSize;
    uint64_t rowIndexStride;
    CompressionKind compression;
    CompressionStrategy compressionStrategy;
    MemoryPool* memoryPool;
    double paddingTolerance;
    std::ostream* errorStream;
    FileVersion fileVersion;
    double dictionaryKeySizeThreshold;
    bool enableIndex;
    std::set<uint64_t> columnsUseBloomFilter;
    double bloomFilterFalsePositiveProb;
    BloomFilterVersion bloomFilterVersion;
    std::string timezone;

    WriterOptionsPrivate() :
                            fileVersion(FileVersion::v_0_12()) { // default to Hive_0_12
      stripeSize = 64 * 1024 * 1024; // 64M
      compressionBlockSize = 64 * 1024; // 64K
      rowIndexStride = 10000;
      compression = CompressionKind_ZLIB;
      compressionStrategy = CompressionStrategy_SPEED;
      memoryPool = getDefaultPool();
      paddingTolerance = 0.0;
      errorStream = &std::cerr;
      dictionaryKeySizeThreshold = 0.0;
      enableIndex = true;
      bloomFilterFalsePositiveProb = 0.05;
      bloomFilterVersion = UTF8;
      //Writer timezone uses "GMT" by default to get rid of potential issues
      //introduced by moving timestamps between different timezones.
      //Explictly set the writer timezone if the use case depends on it.
      timezone = "GMT";
    }
  };

  WriterOptions::WriterOptions():
    privateBits(std::unique_ptr<WriterOptionsPrivate>
                (new WriterOptionsPrivate())) {
    // PASS
  }

  WriterOptions::WriterOptions(const WriterOptions& rhs):
    privateBits(std::unique_ptr<WriterOptionsPrivate>
                (new WriterOptionsPrivate(*(rhs.privateBits.get())))) {
    // PASS
  }

  WriterOptions::WriterOptions(WriterOptions& rhs) {
    // swap privateBits with rhs
    privateBits.swap(rhs.privateBits);
  }

  WriterOptions& WriterOptions::operator=(const WriterOptions& rhs) {
    if (this != &rhs) {
      privateBits.reset(new WriterOptionsPrivate(*(rhs.privateBits.get())));
    }
    return *this;
  }

  WriterOptions::~WriterOptions() {
    // PASS
  }
  RleVersion WriterOptions::getRleVersion() const {
    if(privateBits->fileVersion == FileVersion::v_0_11())
    {
      return RleVersion_1;
    }

    return RleVersion_2;
  }

  WriterOptions& WriterOptions::setStripeSize(uint64_t size) {
    privateBits->stripeSize = size;
    return *this;
  }

  uint64_t WriterOptions::getStripeSize() const {
    return privateBits->stripeSize;
  }

  WriterOptions& WriterOptions::setCompressionBlockSize(uint64_t size) {
    privateBits->compressionBlockSize = size;
    return *this;
  }

  uint64_t WriterOptions::getCompressionBlockSize() const {
    return privateBits->compressionBlockSize;
  }

  WriterOptions& WriterOptions::setRowIndexStride(uint64_t stride) {
    privateBits->rowIndexStride = stride;
    privateBits->enableIndex = (stride != 0);
    return *this;
  }

  uint64_t WriterOptions::getRowIndexStride() const {
    return privateBits->rowIndexStride;
  }

  WriterOptions& WriterOptions::setDictionaryKeySizeThreshold(double val) {
    privateBits->dictionaryKeySizeThreshold = val;
    return *this;
  }

  double WriterOptions::getDictionaryKeySizeThreshold() const {
    return privateBits->dictionaryKeySizeThreshold;
  }

  WriterOptions& WriterOptions::setFileVersion(const FileVersion& version) {
    // Only Hive_0_11 and Hive_0_12 version are supported currently
    if (version.getMajor() == 0 && (version.getMinor() == 11 || version.getMinor() == 12)) {
      privateBits->fileVersion = version;
      return *this;
    }
    throw std::logic_error("Unsupported file version specified.");
  }

  FileVersion WriterOptions::getFileVersion() const {
    return privateBits->fileVersion;
  }

  WriterOptions& WriterOptions::setCompression(CompressionKind comp) {
    privateBits->compression = comp;
    return *this;
  }

  CompressionKind WriterOptions::getCompression() const {
    return privateBits->compression;
  }

  WriterOptions& WriterOptions::setCompressionStrategy(
    CompressionStrategy strategy) {
    privateBits->compressionStrategy = strategy;
    return *this;
  }

  CompressionStrategy WriterOptions::getCompressionStrategy() const {
    return privateBits->compressionStrategy;
  }

  bool WriterOptions::getAlignedBitpacking() const {
    return privateBits->compressionStrategy == CompressionStrategy ::CompressionStrategy_SPEED;
  }

  WriterOptions& WriterOptions::setPaddingTolerance(double tolerance) {
    privateBits->paddingTolerance = tolerance;
    return *this;
  }

  double WriterOptions::getPaddingTolerance() const {
    return privateBits->paddingTolerance;
  }

  WriterOptions& WriterOptions::setMemoryPool(MemoryPool* memoryPool) {
    privateBits->memoryPool = memoryPool;
    return *this;
  }

  MemoryPool* WriterOptions::getMemoryPool() const {
    return privateBits->memoryPool;
  }

  WriterOptions& WriterOptions::setErrorStream(std::ostream& errStream) {
    privateBits->errorStream = &errStream;
    return *this;
  }

  std::ostream* WriterOptions::getErrorStream() const {
    return privateBits->errorStream;
  }

  bool WriterOptions::getEnableIndex() const {
    return privateBits->enableIndex;
  }

  bool WriterOptions::getEnableDictionary() const {
    return privateBits->dictionaryKeySizeThreshold > 0.0;
  }

  WriterOptions& WriterOptions::setColumnsUseBloomFilter(
    const std::set<uint64_t>& columns) {
    privateBits->columnsUseBloomFilter = columns;
    return *this;
  }

  bool WriterOptions::isColumnUseBloomFilter(uint64_t column) const {
    return privateBits->columnsUseBloomFilter.find(column) !=
           privateBits->columnsUseBloomFilter.end();
  }

  WriterOptions& WriterOptions::setBloomFilterFPP(double fpp) {
    privateBits->bloomFilterFalsePositiveProb = fpp;
    return *this;
  }

  double WriterOptions::getBloomFilterFPP() const {
    return privateBits->bloomFilterFalsePositiveProb;
  }

  // delibrately not provide setter to write bloom filter version because
  // we only support UTF8 for now.
  BloomFilterVersion WriterOptions::getBloomFilterVersion() const {
    return privateBits->bloomFilterVersion;
  }

  const Timezone& WriterOptions::getTimezone() const {
    return getTimezoneByName(privateBits->timezone);
  }

  const std::string& WriterOptions::getTimezoneName() const {
    return privateBits->timezone;
  }

  WriterOptions& WriterOptions::setTimezoneName(const std::string& zone) {
    privateBits->timezone = zone;
    return *this;
  }

  Writer::~Writer() {
    // PASS
  }

  class WriterImpl : public Writer {
  private:
    std::unique_ptr<ColumnWriter> columnWriter;
    std::unique_ptr<BufferedOutputStream> compressionStream;
    std::unique_ptr<BufferedOutputStream> bufferedStream;
    std::unique_ptr<StreamsFactory> streamsFactory;
    OutputStream* outStream;
    WriterOptions options;
    const Type& type;
    uint64_t stripeRows, totalRows, indexRows;
    uint64_t currentOffset;
    proto::Footer fileFooter;
    proto::PostScript postScript;
    proto::StripeInformation stripeInfo;
    proto::Metadata metadata;

    static const char* magicId;
    static const WriterId writerId;

  public:
    WriterImpl(
               const Type& type,
               OutputStream* stream,
               const WriterOptions& options);

    std::unique_ptr<ColumnVectorBatch> createRowBatch(uint64_t size)
                                                            const override;

    void add(ColumnVectorBatch& rowsToAdd) override;

    void close() override;

    void addUserMetadata(const std::string name, const std::string value) override;

  private:
    void init();
    void initStripe();
    void writeStripe();
    void writeMetadata();
    void writeFileFooter();
    void writePostscript();
    void buildFooterType(const Type& t, proto::Footer& footer, uint32_t& index);
    static proto::CompressionKind convertCompressionKind(
                                                  const CompressionKind& kind);
  };

  const char * WriterImpl::magicId = "ORC";

  const WriterId WriterImpl::writerId = WriterId::ORC_CPP_WRITER;

  WriterImpl::WriterImpl(
                         const Type& t,
                         OutputStream* stream,
                         const WriterOptions& opts) :
                         outStream(stream),
                         options(opts),
                         type(t) {
    streamsFactory = createStreamsFactory(options, outStream);
    columnWriter = buildWriter(type, *streamsFactory, options);
    stripeRows = totalRows = indexRows = 0;
    currentOffset = 0;

    // compression stream for stripe footer, file footer and metadata
    compressionStream = createCompressor(
                                  options.getCompression(),
                                  outStream,
                                  options.getCompressionStrategy(),
                                  1 * 1024 * 1024, // buffer capacity: 1M
                                  options.getCompressionBlockSize(),
                                  *options.getMemoryPool());

    // uncompressed stream for post script
    bufferedStream.reset(new BufferedOutputStream(
                                            *options.getMemoryPool(),
                                            outStream,
                                            1024, // buffer capacity: 1024 bytes
                                            options.getCompressionBlockSize()));

    init();
  }

  std::unique_ptr<ColumnVectorBatch> WriterImpl::createRowBatch(uint64_t size)
                                                                         const {
    return type.createRowBatch(size, *options.getMemoryPool());
  }

  void WriterImpl::add(ColumnVectorBatch& rowsToAdd) {
    if (options.getEnableIndex()) {
      uint64_t pos = 0;
      uint64_t chunkSize = 0;
      uint64_t rowIndexStride = options.getRowIndexStride();
      while (pos < rowsToAdd.numElements) {
        chunkSize = std::min(rowsToAdd.numElements - pos,
                             rowIndexStride - indexRows);
        columnWriter->add(rowsToAdd, pos, chunkSize, nullptr);

        pos += chunkSize;
        indexRows += chunkSize;
        stripeRows += chunkSize;

        if (indexRows >= rowIndexStride) {
          columnWriter->createRowIndexEntry();
          indexRows = 0;
        }
      }
    } else {
      stripeRows += rowsToAdd.numElements;
      columnWriter->add(rowsToAdd, 0, rowsToAdd.numElements, nullptr);
    }

    if (columnWriter->getEstimatedSize() >= options.getStripeSize()) {
      writeStripe();
    }
  }

  void WriterImpl::close() {
    if (stripeRows > 0) {
      writeStripe();
    }
    writeMetadata();
    writeFileFooter();
    writePostscript();
    outStream->close();
  }

  void WriterImpl::addUserMetadata(const std::string name, const std::string value){
    proto::UserMetadataItem* userMetadataItem = fileFooter.add_metadata();
    userMetadataItem->set_name(name);
    userMetadataItem->set_value(value);
  }

  void WriterImpl::init() {
    // Write file header
    const static size_t magicIdLength = strlen(WriterImpl::magicId);
    outStream->write(WriterImpl::magicId, magicIdLength);
    currentOffset += magicIdLength;

    // Initialize file footer
    fileFooter.set_headerlength(currentOffset);
    fileFooter.set_contentlength(0);
    fileFooter.set_numberofrows(0);
    fileFooter.set_rowindexstride(
                          static_cast<uint32_t>(options.getRowIndexStride()));
    fileFooter.set_writer(writerId);

    uint32_t index = 0;
    buildFooterType(type, fileFooter, index);

    // Initialize post script
    postScript.set_footerlength(0);
    postScript.set_compression(
                  WriterImpl::convertCompressionKind(options.getCompression()));
    postScript.set_compressionblocksize(options.getCompressionBlockSize());

    postScript.add_version(options.getFileVersion().getMajor());
    postScript.add_version(options.getFileVersion().getMinor());

    postScript.set_writerversion(WriterVersion_ORC_135);
    postScript.set_magic("ORC");

    // Initialize first stripe
    initStripe();
  }

  void WriterImpl::initStripe() {
    stripeInfo.set_offset(currentOffset);
    stripeInfo.set_indexlength(0);
    stripeInfo.set_datalength(0);
    stripeInfo.set_footerlength(0);
    stripeInfo.set_numberofrows(0);

    stripeRows = indexRows = 0;
  }

  void WriterImpl::writeStripe() {
    if (options.getEnableIndex() && indexRows != 0) {
      columnWriter->createRowIndexEntry();
      indexRows = 0;
    } else {
      columnWriter->mergeRowGroupStatsIntoStripeStats();
    }

    // dictionary should be written before any stream is flushed
    columnWriter->writeDictionary();

    std::vector<proto::Stream> streams;
    // write ROW_INDEX streams
    if (options.getEnableIndex()) {
      columnWriter->writeIndex(streams);
    }
    // write streams like PRESENT, DATA, etc.
    columnWriter->flush(streams);

    // generate and write stripe footer
    proto::StripeFooter stripeFooter;
    for (uint32_t i = 0; i < streams.size(); ++i) {
      *stripeFooter.add_streams() = streams[i];
    }

    std::vector<proto::ColumnEncoding> encodings;
    columnWriter->getColumnEncoding(encodings);

    for (uint32_t i = 0; i < encodings.size(); ++i) {
      *stripeFooter.add_columns() = encodings[i];
    }

    stripeFooter.set_writertimezone(options.getTimezoneName());

    // add stripe statistics to metadata
    proto::StripeStatistics* stripeStats = metadata.add_stripestats();
    std::vector<proto::ColumnStatistics> colStats;
    columnWriter->getStripeStatistics(colStats);
    for (uint32_t i = 0; i != colStats.size(); ++i) {
      *stripeStats->add_colstats() = colStats[i];
    }
    // merge stripe stats into file stats and clear stripe stats
    columnWriter->mergeStripeStatsIntoFileStats();

    if (!stripeFooter.SerializeToZeroCopyStream(compressionStream.get())) {
      throw std::logic_error("Failed to write stripe footer.");
    }
    uint64_t footerLength = compressionStream->flush();

    // calculate data length and index length
    uint64_t dataLength = 0;
    uint64_t indexLength = 0;
    for (uint32_t i = 0; i < streams.size(); ++i) {
      if (streams[i].kind() == proto::Stream_Kind_ROW_INDEX ||
          streams[i].kind() == proto::Stream_Kind_BLOOM_FILTER_UTF8) {
        indexLength += streams[i].length();
      } else {
        dataLength += streams[i].length();
      }
    }

    // update stripe info
    stripeInfo.set_indexlength(indexLength);
    stripeInfo.set_datalength(dataLength);
    stripeInfo.set_footerlength(footerLength);
    stripeInfo.set_numberofrows(stripeRows);

    *fileFooter.add_stripes() = stripeInfo;

    currentOffset = currentOffset + indexLength + dataLength + footerLength;
    totalRows += stripeRows;

    columnWriter->reset();

    initStripe();
  }

  void WriterImpl::writeMetadata() {
    if (!metadata.SerializeToZeroCopyStream(compressionStream.get())) {
      throw std::logic_error("Failed to write metadata.");
    }
    postScript.set_metadatalength(compressionStream.get()->flush());
  }

  void WriterImpl::writeFileFooter() {
    fileFooter.set_contentlength(currentOffset - fileFooter.headerlength());
    fileFooter.set_numberofrows(totalRows);

    // update file statistics
    std::vector<proto::ColumnStatistics> colStats;
    columnWriter->getFileStatistics(colStats);
    for (uint32_t i = 0; i != colStats.size(); ++i) {
      *fileFooter.add_statistics() = colStats[i];
    }

    if (!fileFooter.SerializeToZeroCopyStream(compressionStream.get())) {
      throw std::logic_error("Failed to write file footer.");
    }
    postScript.set_footerlength(compressionStream->flush());
  }

  void WriterImpl::writePostscript() {
    if (!postScript.SerializeToZeroCopyStream(bufferedStream.get())) {
      throw std::logic_error("Failed to write post script.");
    }
    unsigned char psLength =
                      static_cast<unsigned char>(bufferedStream->flush());
    outStream->write(&psLength, sizeof(unsigned char));
  }

  void WriterImpl::buildFooterType(
                                   const Type& t,
                                   proto::Footer& footer,
                                   uint32_t & index) {
    proto::Type protoType;
    protoType.set_maximumlength(static_cast<uint32_t>(t.getMaximumLength()));
    protoType.set_precision(static_cast<uint32_t>(t.getPrecision()));
    protoType.set_scale(static_cast<uint32_t>(t.getScale()));

    switch (t.getKind()) {
    case BOOLEAN: {
      protoType.set_kind(proto::Type_Kind_BOOLEAN);
      break;
    }
    case BYTE: {
      protoType.set_kind(proto::Type_Kind_BYTE);
      break;
    }
    case SHORT: {
      protoType.set_kind(proto::Type_Kind_SHORT);
      break;
    }
    case INT: {
      protoType.set_kind(proto::Type_Kind_INT);
      break;
    }
    case LONG: {
      protoType.set_kind(proto::Type_Kind_LONG);
      break;
    }
    case FLOAT: {
      protoType.set_kind(proto::Type_Kind_FLOAT);
      break;
    }
    case DOUBLE: {
      protoType.set_kind(proto::Type_Kind_DOUBLE);
      break;
    }
    case STRING: {
      protoType.set_kind(proto::Type_Kind_STRING);
      break;
    }
    case BINARY: {
      protoType.set_kind(proto::Type_Kind_BINARY);
      break;
    }
    case TIMESTAMP: {
      protoType.set_kind(proto::Type_Kind_TIMESTAMP);
      break;
    }
    case TIMESTAMP_INSTANT: {
      protoType.set_kind(proto::Type_Kind_TIMESTAMP_INSTANT);
      break;
    }
    case LIST: {
      protoType.set_kind(proto::Type_Kind_LIST);
      break;
    }
    case MAP: {
      protoType.set_kind(proto::Type_Kind_MAP);
      break;
    }
    case STRUCT: {
      protoType.set_kind(proto::Type_Kind_STRUCT);
      break;
    }
    case UNION: {
      protoType.set_kind(proto::Type_Kind_UNION);
      break;
    }
    case DECIMAL: {
      protoType.set_kind(proto::Type_Kind_DECIMAL);
      break;
    }
    case DATE: {
      protoType.set_kind(proto::Type_Kind_DATE);
      break;
    }
    case VARCHAR: {
      protoType.set_kind(proto::Type_Kind_VARCHAR);
      break;
    }
    case CHAR: {
      protoType.set_kind(proto::Type_Kind_CHAR);
      break;
    }
    default:
      throw std::logic_error("Unknown type.");
    }

    for (auto& key : t.getAttributeKeys()) {
      const auto& value = t.getAttributeValue(key);
      auto protoAttr = protoType.add_attributes();
      protoAttr->set_key(key);
      protoAttr->set_value(value);
    }

    int pos = static_cast<int>(index);
    *footer.add_types() = protoType;

    for (uint64_t i = 0; i < t.getSubtypeCount(); ++i) {
      // only add subtypes' field names if this type is STRUCT
      if (t.getKind() == STRUCT) {
        footer.mutable_types(pos)->add_fieldnames(t.getFieldName(i));
      }
      footer.mutable_types(pos)->add_subtypes(++index);
      buildFooterType(*t.getSubtype(i), footer, index);
    }
  }

  proto::CompressionKind WriterImpl::convertCompressionKind(
                                      const CompressionKind& kind) {
    return static_cast<proto::CompressionKind>(kind);
  }

  std::unique_ptr<Writer> createWriter(
                                       const Type& type,
                                       OutputStream* stream,
                                       const WriterOptions& options) {
    return std::unique_ptr<Writer>(
                                   new WriterImpl(
                                            type,
                                            stream,
                                            options));
  }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Acta Phytopath. 9: 254 (1974)

#### Original name
Botryoblastoconidiaceae Vörös & Léránth

### Remarks
null


text:
/**
 */
#ifndef THREAD_BEACON_LIB_H_
#define THREAD_BEACON_LIB_H_

#include "ns_types.h"

/** Beacon version number shift
 *
 */
#define THREAD_BEACON_VERSION_SHIFT                 4

/** Joining bit location
 *
 */
#define THREAD_BEACON_JOINING_PERMITTED_BIT         0x01

/** Native commissioner bit
 *
 */
#define THREAD_BEACON_NATIVE_COMMISSIONER_BIT       0x08

/** Calculate bloom filter
 * @param bloom_filter_ptr 		Pointer to array with bloom filter
 * @param bloom_filter_length   Bloom filter length
 * @param joiner_id_ptr             Joiner ID array
 * @param joiner_id_length         Joiner ID array length
 */
uint8_t *thread_beacon_calculate_bloom_filter(uint8_t *bloom_filter_ptr,uint8_t bloom_filter_length, uint8_t *joiner_id_ptr, int joiner_id_length);

#endif /* THREAD_BEACON_LIB_H_ */


text:
package org.laladev.moneyjinn.core.rest.model.report;

import java.sql.Date;
import java.util.List;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import org.laladev.moneyjinn.core.rest.model.AbstractResponse;
import org.laladev.moneyjinn.core.rest.model.transport.PostingAccountTransport;

@XmlRootElement(name = "showReportingFormResponse")
public class ShowReportingFormResponse extends AbstractResponse {
	@XmlElement(name = "postingAccountTransport")
	private List<PostingAccountTransport> postingAccountTransports;
	@XmlElement(name = "postingAccountIdsNo")
	private List<Long> postingAccountIds;
	private Date minDate;
	private Date maxDate;

	public final Date getMinDate() {
		return this.minDate;
	}

	public final void setMinDate(final Date minDate) {
		this.minDate = minDate;
	}

	public final Date getMaxDate() {
		return this.maxDate;
	}

	public final void setMaxDate(final Date maxDate) {
		this.maxDate = maxDate;
	}

	public final List<PostingAccountTransport> getPostingAccountTransports() {
		return this.postingAccountTransports;
	}

	public final void setPostingAccountTransports(final List<PostingAccountTransport> postingAccountTransports) {
		this.postingAccountTransports = postingAccountTransports;
	}

	public final List<Long> getPostingAccountIds() {
		return this.postingAccountIds;
	}

	public final void setPostingAccountIds(final List<Long> postingAccountIds) {
		this.postingAccountIds = postingAccountIds;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = super.hashCode();
		result = prime * result + ((this.maxDate == null) ? 0 : this.maxDate.hashCode());
		result = prime * result + ((this.minDate == null) ? 0 : this.minDate.hashCode());
		result = prime * result + ((this.postingAccountIds == null) ? 0 : this.postingAccountIds.hashCode());
		result = prime * result
				+ ((this.postingAccountTransports == null) ? 0 : this.postingAccountTransports.hashCode());
		return result;
	}

	@Override
	public boolean equals(final Object obj) {
		if (this == obj) {
			return true;
		}
		if (!super.equals(obj)) {
			return false;
		}
		if (this.getClass() != obj.getClass()) {
			return false;
		}
		final ShowReportingFormResponse other = (ShowReportingFormResponse) obj;
		if (this.maxDate == null) {
			if (other.maxDate != null) {
				return false;
			}
		} else if (!this.maxDate.equals(other.maxDate)) {
			return false;
		}
		if (this.minDate == null) {
			if (other.minDate != null) {
				return false;
			}
		} else if (!this.minDate.equals(other.minDate)) {
			return false;
		}
		if (this.postingAccountIds == null) {
			if (other.postingAccountIds != null) {
				return false;
			}
		} else if (!this.postingAccountIds.equals(other.postingAccountIds)) {
			return false;
		}
		if (this.postingAccountTransports == null) {
			if (other.postingAccountTransports != null) {
				return false;
			}
		} else if (!this.postingAccountTransports.equals(other.postingAccountTransports)) {
			return false;
		}
		return true;
	}

	@Override
	public String toString() {
		final StringBuilder builder = new StringBuilder();
		builder.append("ShowReportingFormResponse [postingAccountTransports=");
		builder.append(this.postingAccountTransports);
		builder.append(", postingAccountIds=");
		builder.append(this.postingAccountIds);
		builder.append(", minDate=");
		builder.append(this.minDate);
		builder.append(", maxDate=");
		builder.append(this.maxDate);
		builder.append("]");
		return builder.toString();
	}

}


text:
/*************************************************************
Represent a video frame or image with MomVop structure used in MPEG-7 XM
aim: decrease the memory allocation deallocation for each frame during video processing
	 allocation, deallocation, setting the image is done only once and the Frame object can be
	 used to extract all the features (color/shape/texture)

author : mb
date: 07.07.2008
update: 02.02.2011 (upgrade to OpenCV 2.2, Mat)
**************************************************************/

#ifndef __FRAME__H__
#define __FRAME__H__

#include "core.hpp"

#include "AddressLib/vopio.h"

using namespace cv;

class Frame
{
public:

	Frame( int width, int height, bool imgFlag = true, bool grayFlag = true, bool maskFlag = true );
	/// allocates and sets the image (this->image <= src)
	Frame( Mat& src, bool imgFlag = true, bool grayFlag = true, bool maskFlag = true  );
	~Frame();

    // allocate this->image, this->gray, this->mask (depending on the flags)
	void allocate(int width, int height, bool imgFlag = true, bool grayFlag = true, bool maskFlag = true );
    // resize the images in the frame, if the new size is different
    // mask is reset (ResetMaskAll()) if it exists
    void resize(int width, int height);

	/// this->image <= src (if this->image != 0 && src != 0 )
	void setImage( Mat& src );
	/// this->gray <= gray (if this->gray != 0 && gray != 0 )
	void setGray( Mat& gray );

	// set the alpha channel (mask) to the arbitrary shape
	void setMask( Mat& mask, int rid, int fg = 255, int bg = 0 );

	// set all the values in the mask to val, and attach this mask to image and gray as their a_chan
	// this  is required by Scalable Color Descriptor extraction!
	void setMaskValue( int val = 255);

	// set the alpha channel (mask) to the arbitrary shape AND point the alpha channels (a_chan) of image and gray to a_chan of mask
	// use this to extract color and grayscale features of arbitrary shapes
	void setMaskAll( Mat& mask, int rid, int fg = 255, int bg = 0 );
    // set the mask only for this->image
    void setMaskImage( Mat& mask, int rid, int fg = 255, int bg = 0 );
    // set the mask only for this->gray
    void setMaskGray( Mat& mask, int rid, int fg, int bg);

	//point a_chan of image (mask) and gray to 0 again (as initiated) - to extract feature from the whole frame
	void resetMaskAll();
	void resetMaskImage();
	void resetMaskGray();

	/// data
	// width-height of the frame
	int width;
	int height;

    /// MomVop is the data structure to store image data in MPEG-7 Reference software
    /// see AddressLib/vopio.h

	// 3-channel color image (3x8 bit)
	MomVop* image;

	// single channel grayscale image (8 bit)
	MomVop* gray;

	// single channel mask for arbitrary shape (8 bit)
	MomVop* mask;

};

#endif


text:
<META http-equiv="content-type" content="text/html;charset=iso-8859-9"/><meta name="viewport" content="width=device-width, initial-scale=1"><title>ac</title> <link rel="stylesheet"  href="css/jquery.mobile-1.2.0.css" />

ABDULLAH BÝN EBU HUZEYL EL-ANEZÝ

Geri

Tâbiîn devri âlim ve evliyâsýndan. Ýsmi Abdullah bin Ebû Huzeyl el-Anezî olup
künyesiEbü'l-Mugîre'dir. Doðum ve vefât yeri ve târihi bilinmemektedir.

Abdullah bin Huzeyl, hadîs-i þerîf rivâyeti ilminde üstün bir derecede idi. Hazret-i Ebû Bekr,
hazret-i Ömer, hazret-i Ali, Ammâr, Übeyy, Ýbn-i Mes'ûd, Habbâb, Ebû Hureyre ve baþka
sahâbîlerden, radýyallahü anhüm, hadîs-i þerîf rivâyetinde bulundu. Vâsýl el-Ahdeb, Ebü't-Tâc
ed-Dubeî, Ýsmail bin Recâ, Seclah el-Kindî, Selm bin Atiyye, Atâ bin Sâib, Ayam bin Havþeb
gibi hadîs âlimleri kendisinden hadîs-i þerîf nakletmiþlerdir.

Abdullah bin Huzeyl, vaktin büyük nîmet olduðunu bilir ve zamanýn boþa geçirilmesini
istemezdi. Ebû Ferve anlatýr:

Abdullah bin Hüzeyl ile oturuyorduk. Birisi gelip insanlarýn kendi aralarýnda konuþtuðu
þeylerden söyledi. Bunun üzerine Abdullah bin Huzeyl; "Ey Allah'ýn kulu biz bunlarý
konuþarak vaktimizi öldürmek için yaratýlmadýk." diyerek onu susturdu.

Medhedilmekten hoþlanmaz þöhretten kaçardý. Bir gün bulunduðu yerde imâm olmasýný teklif
ettiler. Kabûl etmedi. Sebebini sorduklarýnda; "Buradan geçen birisi bu adam hayýrlý ve
muhterem bir zât da, onun için imâm yapmýþlar diye düþünür." dedi.

Ýnsanlarýn en çok neden sakýnmasý gerektiði sorulduðunda; "Yâ Rabbî! Faydasýz ilimden,
ürperip yumuþamayan kalbten, kabûl olmayan duâdan, doymayan nefisten sana
sýðýnýrým." diyerek Peygamber efendimizin hadîs-i þerîfi ile cevap verdi.

1) Hilye; c.4, s.358

2) A'lâm-ün Nübelâ; c.4, s. 170


text:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using YC.Models;

namespace YC.Service
{
    public class ImportService
    {
        public List<Station> FindStations(string xmlPath)
        {
            List<Station> stations = new List<Station>();
            var xml = XElement.Load(xmlPath);
            XNamespace gml = @"http://www.opengis.net/gml/3.2";
            XNamespace twed = @"http://twed.wra.gov.tw/twedml/opendata";
            var stationsNode = xml.Descendants(twed + "RiverStageObservatoryProfile").ToList();
            stationsNode
                .Where(x => !x.IsEmpty).ToList()
                .ForEach(stationNode =>
                {
                    var BasinIdentifier = stationNode.Element(twed + "BasinIdentifier").Value.Trim();
                    var ObservatoryName = stationNode.Element(twed + "ObservatoryName").Value.Trim();
                    var LocationAddress = stationNode.Element(twed + "LocationAddress").Value.Trim();

                    var LocationByTWD67pos = stationNode.Element(twed + "LocationByTWD67").Descendants(gml + "pos").FirstOrDefault().Value.Trim();
                    var LocationByTWD97pos = stationNode.Element(twed + "LocationByTWD97").Descendants(gml + "pos").FirstOrDefault().Value.Trim();
                    Station stationData = new Station();
                    stationData.ID = BasinIdentifier;
                    stationData.LocationAddress = LocationAddress;
                    stationData.LocationByTWD67 = LocationByTWD67pos;
                    stationData.ObservatoryName = ObservatoryName;
                    stationData.CreateTime = DateTime.Now;
                    stations.Add(stationData);

                });

            return stations;

        }
        public List<Record> CreateRecordsFromJson()
        {
            var URL = @"http://data.wra.gov.tw/Service/OpenData.aspx?id=2D09DB8B-6A1B-485E-88B5-923A462F475C&format=json";
            List<Record> result = new List<Record>();

            var stationDb = new YC.Repository.StationRepository();
            var recordDb = new YC.Repository.RecordRepository();
            var jsonString = "";
            using (var webClient = new System.Net.WebClient())
            {
                jsonString = webClient.DownloadString(URL);
            }

            var stations = stationDb.FindAllStations()
                .ToDictionary(x => x.ID, x => x);
            var json = JsonConvert.DeserializeObject<JObject>(jsonString);
            var jsonDatas = json.Property("RealtimeWaterLevel_OPENDATA").Values().ToList();

            jsonDatas.ForEach(item =>
            {
                var recordObj = item as JObject;
                var StationIdentifier = recordObj.Property("StationIdentifier").Value.ToString().Trim();
                if (!stations.ContainsKey(StationIdentifier))
                {
                    return;
                }
                var station = stations[StationIdentifier];
                var RecordTime = recordObj.Property("RecordTime").Value.ToString().Trim();
                var WaterLevel = recordObj.Property("WaterLevel").Value.ToString().Trim();
                var recordTime = DateTime.Parse(RecordTime);
                var waterLevel = double.Parse(WaterLevel);

                Record newRecord = new Record();
                newRecord.CreateTime = DateTime.Now;
                newRecord.StationID = station.ID;
                newRecord.RecordTime = recordTime;
                newRecord.WaterLevel = waterLevel;
                newRecord.Station = station;
                //判斷是否已經存在此筆紀錄,不存在時存檔Record並更新Station
                var isExist = recordDb.IsExist(newRecord);
                if (!isExist)
                {
                    station.LastRecordTime = newRecord.RecordTime;
                    station.LastRecordWaterLevel = newRecord.WaterLevel;
                    stationDb.UpdateLastRecord(station);
                    result.Add(newRecord);

                }
            });
            recordDb.Create(result);
            return result;
        }

    }
}


text:
desolver.utilities package
==========================

Submodules
----------

desolver.utilities.interpolation module
---------------------------------------

.. automodule:: desolver.utilities.interpolation
   :members:
   :undoc-members:
   :show-inheritance:

desolver.utilities.optimizer module
-----------------------------------

.. automodule:: desolver.utilities.optimizer
   :members:
   :undoc-members:
   :show-inheritance:

desolver.utilities.utilities module
-----------------------------------

.. automodule:: desolver.utilities.utilities
   :members:
   :undoc-members:
   :show-inheritance:

Module contents
---------------

.. automodule:: desolver.utilities
   :members:
   :undoc-members:
   :show-inheritance:


text:
package pokefenn.totemic.handler;

import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.ai.goal.target.NearestAttackableTargetGoal;
import net.minecraft.world.entity.monster.Skeleton;
import net.minecraftforge.event.entity.EntityJoinLevelEvent;
import pokefenn.totemic.entity.Buffalo;

public final class EntityHandler {
    public static void onEntityJoin(EntityJoinLevelEvent event) {
        if(event.getEntity().getType() == EntityType.SKELETON) {
            Skeleton entity = (Skeleton) event.getEntity();
            entity.targetSelector.addGoal(10, new NearestAttackableTargetGoal<>(entity, Buffalo.class, true));
        }
    }
}


text:
import {
  findElmById,
  invokeVmMethod,
  invokeVmMethodWithoutArgs
} from '../util'

class LivePusherContext {
  constructor (id, ctx) {
    this.id = id
    this.ctx = ctx
  }

  start (cbs) {
    return invokeVmMethodWithoutArgs(this.ctx, 'start', cbs)
  }

  stop (cbs) {
    return invokeVmMethodWithoutArgs(this.ctx, 'stop', cbs)
  }

  pause (cbs) {
    return invokeVmMethodWithoutArgs(this.ctx, 'pause', cbs)
  }

  resume (cbs) {
    return invokeVmMethodWithoutArgs(this.ctx, 'resume', cbs)
  }

  switchCamera (cbs) {
    return invokeVmMethodWithoutArgs(this.ctx, 'switchCamera', cbs)
  }

  snapshot (cbs) {
    return invokeVmMethodWithoutArgs(this.ctx, 'snapshot', cbs)
  }

  toggleTorch (cbs) {
    return invokeVmMethodWithoutArgs(this.ctx, 'toggleTorch', cbs)
  }

  playBGM (args) {
    return invokeVmMethod(this.ctx, 'playBGM', args)
  }

  stopBGM (cbs) {
    return invokeVmMethodWithoutArgs(this.ctx, 'stopBGM', cbs)
  }

  pauseBGM (cbs) {
    return invokeVmMethodWithoutArgs(this.ctx, 'pauseBGM', cbs)
  }

  resumeBGM (cbs) {
    return invokeVmMethodWithoutArgs(this.ctx, 'resumeBGM', cbs)
  }

  setBGMVolume (cbs) {
    return invokeVmMethod(this.ctx, 'setBGMVolume', cbs)
  }

  startPreview (cbs) {
    return invokeVmMethodWithoutArgs(this.ctx, 'startPreview', cbs)
  }

  stopPreview (args) {
    return invokeVmMethodWithoutArgs(this.ctx, 'stopPreview', args)
  }
}

export function createLivePusherContext (id, vm) {
  if (!vm) {
    return console.warn('uni.createLivePusherContext: 2 arguments required, but only 1 present')
  }
  const elm = findElmById(id, vm)
  if (!elm) {
    return console.warn('Can not find `' + id + '`')
  }
  return new LivePusherContext(id, elm)
}


text:
export class LoginRequestController {
    constructor(User) {
        User.getOAuthLoginData().then((response) => {
            this.links = response;
        });
    }
}


text:
<?php

/**
 * @file
 * Definition of Drupal\taxonomy\Plugin\views\field\LinkEdit.
 */

namespace Drupal\taxonomy\Plugin\views\field;

use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\ViewExecutable;
use Drupal\Component\Annotation\PluginID;

/**
 * Field handler to present a term edit link.
 *
 * @ingroup views_field_handlers
 *
 * @PluginID("term_link_edit")
 */
class LinkEdit extends FieldPluginBase {

  /**
   * Overrides Drupal\views\Plugin\views\field\FieldPluginBase::init().
   */
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);

    $this->additional_fields['tid'] = 'tid';
    $this->additional_fields['vid'] = 'vid';
  }

  protected function defineOptions() {
    $options = parent::defineOptions();

    $options['text'] = array('default' => '', 'translatable' => TRUE);

    return $options;
  }

  public function buildOptionsForm(&$form, &$form_state) {
    $form['text'] = array(
      '#type' => 'textfield',
      '#title' => t('Text to display'),
      '#default_value' => $this->options['text'],
    );
    parent::buildOptionsForm($form, $form_state);
  }

  public function query() {
    $this->ensureMyTable();
    $this->addAdditionalFields();
  }

  public function render($values) {
    // Check there is an actual value, as on a relationship there may not be.
    if ($tid = $this->getValue($values, 'tid')) {
      // Mock a term object for taxonomy_term_access(). Use machine name and
      // vid to ensure compatibility with vid based and machine name based
      // access checks. See http://drupal.org/node/995156
      $term = entity_create('taxonomy_term', array(
        'vid' => $values->{$this->aliases['vid']},
      ));
      if ($term->access('update')) {
        $text = !empty($this->options['text']) ? $this->options['text'] : t('edit');
        return l($text, 'taxonomy/term/'. $tid . '/edit', array('query' => drupal_get_destination()));
      }
    }
  }

}


text:
  Névache est
       un village
       situé dans le département des Hautes-Alpes en Provence-Alpes-Côte d'Azur. Elle comptait 321 habitants en 2008.

Si vous pensez venir habiter à Névache, vous pourrez facilement trouver une maison à vendre.

Le parc d'habitations, à Névache, se décomposait en 2011 en 293 appartements et 432 maisons soit
 un marché plutôt équilibré.

La ville compte de nombreux  équipements, elle dispose, entre autres, de un terrain de tennis, deux domaines skiables, un terrain de sport et six boucles de randonnée.

À proximité de Névache sont situées les villes de
La Salle-les-Alpes à 8 km, 891 habitants,
Villar-Saint-Pancrace localisée à 16 km, 1 459 habitants,
Le Monêtier-les-Bains localisée à 9 km, 1 062 habitants,
Puy-Saint-Pierre localisée à 14 km, 478 habitants,
Montgenèvre à 13 km, 471 habitants,
Saint-Chaffrey localisée à 10 km, 1 706 habitants,
 entre autres. De plus, Névache est située à seulement treize km de Briançon.


text:
package org.sqinstest

import org.sqins._
import org.sqins.Implicits._

/**
 * Test the syntax of everything listed in the docs.
 */
object DocCompilationText {
  case class MyType(wrapped: String)

  object MyTypeMappings {
    implicit object MyTypeMapping extends TypeMapping[MyType] {
      def _get(rs: java.sql.ResultSet, position: Int) =
        Extraction(MyType(rs.getString(position)), 1)

      def _set(ps: java.sql.PreparedStatement, position: Int, value: MyType) =
        ps.setString(position, value.wrapped)
    }

    // Option types can usually be mapped by just wrapping
    // the regular TypeMapping with an OptionTypeMapping
    implicit val OptionMyTypeMapping = new OptionTypeMapping(MyTypeMapping)
  }

  // To use our new type mappings, just import them
  import MyTypeMappings._

  db.inTransaction { implicit conn =>
    val insertedInvoiceId = (
        INSERT INTO db.i(db.i.description)
        VALUES (?("A new invoice"))
        RETURNING db.i.id)

    for (i <- 1 to 5) {
        val newLineItem = new LineItem(invoice_id = insertedInvoiceId, amount = 5 * i)
        INSERT INTO db.li VALUES (newLineItem) go
      }
  }

  db.withConnection { implicit conn =>
      val query = (
        SELECT (db.i.*, db.li.*)
        FROM (db.i INNER_JOIN db.li ON db.i.id == db.li.invoice_id)
        WHERE (db.i.description == ?("A new invoice")))

      query foreach { row =>
        println(row._1.id)
        println(row._1.description)
        println(row._2.id)
        println(row._2.invoice_id)
        println(row._2.amount)
        println(row._2.ts)
      }
    }

  var query = SELECT(db.invoice.id) FROM (db.invoice)

  db.withConnection { conn =>
    val result: Iterable[Long] = query(conn);

    // You can only iterate over result while the Connection is still open
    result.foreach { row =>
      println(row * 5)
    }

    // To return everything, you could have done this:
    result.toList

    // The resulting list doesn't depend on the database Connection
  }

  query = SELECT(db.invoice.id) FROM db.invoice

  db.withConnection { implicit conn =>
    val result: Iterable[Long] = query go
  }

  db.withConnection { implicit conn =>
    query.foreach { row =>
      println(row * 5)
    }
  }

  val query2 = SELECT(db.invoice.id, db.invoice.description, db.invoice.image) FROM db.invoice

  db.withConnection { implicit conn =>
    query2.foreach { row: Tuple3[Long, String, Option[Array[Byte]]] =>
      println(row._1 * 5)
      println(row._2 + " more string")
      println(row._3)
    }
  }

  val query3 = SELECT(db.invoice.*) FROM db.invoice

  db.withConnection { implicit conn =>
    query3.foreach { row: Invoice =>
      println(row.id * 5)
      println(row.description + " more string")
      println(row.image)
    }
  }

  val query4 = (
    SELECT(db.i.*, db.li.*)
    FROM (db.i INNER_JOIN db.li ON db.i.id == db.li.invoice_id))

  db.withConnection { implicit conn =>
    query4.foreach { row: Tuple2[Invoice, LineItem] =>
      println(row._1.id * 5)
      println(row._1.description + " more string")
      println(row._1.image)
      println(row._2.id * 4)
      println(row._2.invoice_id)
      println(row._2.amount)
      println(row._2.ts)
    }
  }

  val query5 = (
    SELECT(db.i.id, db.li.amount)
    FROM (db.i INNER_JOIN db.li ON db.i.id == db.li.invoice_id))

  db.withConnection { implicit conn =>
    query5.foreach { row: Tuple2[Long, BigDecimal] =>
      println(row._1)
      println(row._2)
    }
  }

  (SELECT(db.i.id, db.li.amount)
    FROM (db.i INNER_JOIN db.li ON db.i.id == db.li.invoice_id)
    WHERE (db.li.amount > db.li.id))

  (SELECT(db.i.id, db.li.amount)
    FROM (db.i INNER_JOIN db.li ON db.i.id == db.li.invoice_id && db.li.id <> db.i.id)
    WHERE (db.li.amount > db.li.id || db.li.amount == db.li.amount))

  (SELECT(db.i.id, db.li.amount)
    FROM (db.i INNER_JOIN db.li ON db.i.id == db.li.invoice_id)
    WHERE (db.li.amount > db.li.id && NOT(db.li.amount <> db.li.amount)))

  val query6: SelectQuery[Tuple2[Long, BigDecimal]] = (
    SELECT(db.i.id, MAX(db.li.amount))
    FROM (db.i INNER_JOIN db.li ON db.i.id == db.li.invoice_id)
    GROUP_BY (db.i.id))

  val invoiceId = 5

  val query7 = (
    SELECT(db.i.id, db.li.amount)
    FROM (db.i INNER_JOIN db.li ON db.i.id == db.li.invoice_id)
    WHERE (db.i.id == ?(invoiceId)))

  (SELECT(db.i.id, db.li.amount)
    FROM (db.i INNER_JOIN db.li ON db.i.id == db.li.invoice_id)
    WHERE (db.i.id == ?(5) || db.i.id == ?(5 * 35 + 3)))

  // TODO: write actual test for this
  (SELECT(db.i.id, db.li.amount)
    FROM (db.i INNER_JOIN db.li ON EXPR("db.i.id funky_database_operator db.li.invoice_id")))

  (SELECT(db.i.id, VEXPR[BigDecimal]("db.li.amount * 5"))
    FROM (db.i INNER_JOIN db.li ON db.i.id == db.li.invoice_id))

  (SELECT(db.i.id)
    FROM db.i
    WHERE FN("lower")(db.i.description) == ?("my lowercase description"))

  val query8: SelectQuery[Tuple2[Long, BigDecimal]] = (
    SELECT(db.i.id, FN("SPECIAL_AGGREGATE")(db.li.amount))
    FROM (db.i INNER_JOIN db.li ON db.i.id == db.li.invoice_id)
    GROUP_BY (db.i.id))

  object MyImplicits {
    implicit def SPECIAL_AGGREGATE = FN("SPECIAL_AGGREGATE")
  }

  import MyImplicits._

  val query9: SelectQuery[Tuple2[Long, BigDecimal]] = (
    SELECT(db.i.id, SPECIAL_AGGREGATE(db.li.amount))
    FROM (db.i INNER_JOIN db.li ON db.i.id == db.li.invoice_id)
    GROUP_BY (db.i.id))

  db.withConnection { implicit conn =>
    val rowsInserted: Int = INSERT INTO db.invoice(db.invoice.description) VALUES (?("My Description"))
  }

  val newInvoice = new Invoice(description = "My Description")

  db.withConnection { implicit conn =>
    val rowsInserted: Int = INSERT INTO db.invoice VALUES (newInvoice)
  }

  db.withConnection { implicit conn =>
    val insertedKey: Long = INSERT INTO db.invoice(db.invoice.description) VALUES (?("My Description")) RETURNING db.invoice.id
  }

  db.withConnection { implicit conn =>
    val numberOfInsertedRows: Int = (
      INSERT INTO db.invoice(db.invoice.description)
      SELECT (db.invoice.description) FROM db.invoice)
  }

  db.withConnection { implicit conn =>
    val insertedIds: SelectResult[Long] = (
      INSERT INTO db.invoice(db.invoice.description)
      SELECT (db.invoice.description) FROM db.invoice
      RETURNING db.invoice.id)
  }

  db.withConnection { implicit conn =>
    val numberOfUpdatedRows: Int = (
      UPDATE(db.invoice)
      SET (db.invoice.description := ?("New description")))
  }

  val updatedInvoice = new Invoice(id = 5, description = "New description")

  db.withConnection { implicit conn =>
    val numberOfUpdatedRows = (
      UPDATE(db.invoice)
      SET (updatedInvoice))
  }

  (UPDATE(db.invoice)
    SET (db.invoice.description := db.invoice.description || ?(" with additional text")))

  db.withConnection { implicit conn =>
    val numberOfUpdatedRows: Int = (
      UPDATE(db.invoice)
      SET (db.invoice.description := ?("New description"))
      WHERE (db.invoice.id <= ?(5)))
  }

  db.withConnection { implicit conn =>
    val updatedRows: SelectResult[Invoice] = (
      UPDATE(db.invoice)
      SET (db.invoice.description := ?("New description"))
      WHERE (db.invoice.id <= ?(5))
      RETURNING db.invoice.*)
  }

  db.withConnection { implicit conn =>
    val numberOfUpdatedRows: Int = (
      DELETE FROM db.invoice
      WHERE (db.invoice.id <= ?(5)))
  }

  db.withConnection { implicit conn =>
    val updatedIds: SelectResult[Long] = (
      DELETE FROM db.invoice
      WHERE (db.invoice.id <= ?(5))
      RETURNING db.invoice.id)
  }

  (
    SELECT(db.i.id, (SELECT(MAX(db.li.id)) FROM db.li WHERE db.li.invoice_id == db.i.id))
    FROM (db.i)
    WHERE (db.i.id == (SELECT(MAX(db.li.invoice_id)) FROM db.li)))

  db.withConnection { implicit conn =>
    val ps: java.sql.PreparedStatement = SQL("DELETE FROM invoice WHERE id <= ?", ?(5)).executeUpdate
    val rowsInserted: Int = ps.getUpdateCount()
  }

  db.withConnection { implicit conn =>
    val ps: java.sql.PreparedStatement = SQL("SELECT * FROM invoice").executeQuery
    val rs: java.sql.ResultSet = ps.getResultSet()
  }

  db.withConnection { implicit conn =>
    val query = (
      SELECT(db.i.*)
      FROM db.i
      WHERE (db.i.id IN ?(Seq(1, 2, 3))))
  }

  db.withConnection { implicit conn =>
    val query = (
      SELECT(db.i.*)
      FROM (db.i)
      WHERE EXISTS(SELECT(db.i2.id)
        FROM (db.i2)
        WHERE db.i.id == db.i2.id))
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
University of Wyoming Publ. Sci. , Bot. 36(4): 60 (1970)

#### Original name
Phyllosticta tetonensis Solheim

### Remarks
null


text:
Register a webhook

<form (ngSubmit)="createWebhook()" [formGroup]="form">

      The webhook could not be created.
      {{errorMessage}}

    <webhook-form-groups [events]="store.events$ | async" [form]="form" [webhook]="webhook"></webhook-form-groups>

    <button [disabled]="form.invalid" class="btn btn-primary btn-sm" type="submit">Register</button>
    <button (click)="modal.dismiss(); $event.stopPropagation()" class="btn btn-default btn-sm">Cancel</button>

</form>


text:
package org.openrdf.repository.object.exceptions;

/**
 * A Bean property failed to be saved.
 *
 * @author James Leigh
 *
 */
public class ObjectPersistException extends ObjectStoreException {

	private static final long serialVersionUID = 6299010514003759105L;

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

	public ObjectPersistException(Exception cause) {
		super(cause);
	}

}


text:
package nl.ebpi.yaidom.convert

import scala.collection.immutable

import org.w3c.dom.Element

import nl.ebpi.yaidom
import nl.ebpi.yaidom.core.Declarations
import nl.ebpi.yaidom.core.Scope
import nl.ebpi.yaidom.simple
import nl.ebpi.yaidom.simple.Comment
import nl.ebpi.yaidom.simple.DocumentConverter
import nl.ebpi.yaidom.simple.Elem
import nl.ebpi.yaidom.simple.ElemConverter
import nl.ebpi.yaidom.simple.EntityRef
import nl.ebpi.yaidom.simple.Node
import nl.ebpi.yaidom.simple.ProcessingInstruction
import nl.ebpi.yaidom.simple.Text
import YaidomToDomConversions.DocumentProducer
import YaidomToDomConversions.ElementProducer

/**
 * Converter from yaidom nodes to DOM nodes, in particular from [[nl.ebpi.yaidom.simple.Elem]] to a `org.w3c.dom.Element`,
 * and from  [[nl.ebpi.yaidom.simple.Document]] to a `org.w3c.dom.Document`.
 *
 * @author Chris de Vreeze
 */
trait YaidomToDomConversions extends ElemConverter[ElementProducer] with DocumentConverter[DocumentProducer] {

  /** Converts a yaidom `Document` to a function from DOM documents (as node factories) to (filled) DOM documents */
  final def convertDocument(document: simple.Document): DocumentProducer = {
    { (doc: org.w3c.dom.Document) =>
      val pis: immutable.IndexedSeq[org.w3c.dom.ProcessingInstruction] =
        document.processingInstructions map { pi => convertProcessingInstruction(pi, doc) }
      for (pi <- pis) doc.appendChild(pi)

      val comments: immutable.IndexedSeq[org.w3c.dom.Comment] =
        document.comments map { com => convertComment(com, doc) }
      for (c <- comments) doc.appendChild(c)

      val docRoot: Element = convertElem(document.documentElement, doc, Scope.Empty)
      doc.appendChild(docRoot)

      if (document.uriOption.isDefined) doc.setDocumentURI(document.uriOption.get.toString)

      doc
    }
  }

  /** Same as `{ doc => convertElem(elm, doc, Scope.Empty) }` */
  final def convertElem(elm: Elem): ElementProducer = {
    { (doc: org.w3c.dom.Document) =>
      val element = convertElem(elm, doc, Scope.Empty)
      element
    }
  }

  /**
   * Converts a yaidom node to a DOM node. A DOM document is passed as node factory. If the node is an element,
   * the passed parent scope is used as in `convertElem(e, doc, parentScope)`.
   */
  final def convertNode(node: Node, doc: org.w3c.dom.Document, parentScope: Scope): org.w3c.dom.Node = {
    node match {
      case e: Elem                   => convertElem(e, doc, parentScope)
      case t: Text                   => convertText(t, doc)
      case pi: ProcessingInstruction => convertProcessingInstruction(pi, doc)
      case er: EntityRef             => convertEntityRef(er, doc)
      case c: Comment                => convertComment(c, doc)
    }
  }

  /**
   * Converts a yaidom `Elem` to a DOM element. A DOM document is passed as node factory.
   * The passed parent scope is used as follows: the namespace declarations on the result DOM element are:
   * `parentScope.relativize(elm.scope)`.
   */
  final def convertElem(elm: Elem, doc: org.w3c.dom.Document, parentScope: Scope): Element = {
    // Not tail-recursive, but the recursion depth should be limited

    val element = createElementWithoutChildren(elm, doc, parentScope)
    val childNodes: immutable.IndexedSeq[org.w3c.dom.Node] =
      elm.children map { ch => convertNode(ch, doc, elm.scope) }

    for (ch <- childNodes) element.appendChild(ch)

    element
  }

  /**
   * Converts a yaidom `Text` to a DOM `Text`. A DOM document is passed as node factory.
   */
  final def convertText(text: Text, doc: org.w3c.dom.Document): org.w3c.dom.Text = {
    val domText =
      if (text.isCData) {
        doc.createCDATASection(text.text)
      } else {
        doc.createTextNode(text.text)
      }

    domText
  }

  /**
   * Converts a yaidom `ProcessingInstruction` to a DOM `ProcessingInstruction`. A DOM document is passed as node factory.
   */
  final def convertProcessingInstruction(
    processingInstruction: ProcessingInstruction, doc: org.w3c.dom.Document): org.w3c.dom.ProcessingInstruction = {

    val domPi = doc.createProcessingInstruction(processingInstruction.target, processingInstruction.data)
    domPi
  }

  /**
   * Converts a yaidom `EntityRef` to a DOM `EntityReference`. A DOM document is passed as node factory.
   */
  final def convertEntityRef(entityRef: EntityRef, doc: org.w3c.dom.Document): org.w3c.dom.EntityReference = {
    val domEntityRef = doc.createEntityReference(entityRef.entity)
    domEntityRef
  }

  /**
   * Converts a yaidom `Comment` to a DOM `Comment`. A DOM document is passed as node factory.
   */
  final def convertComment(comment: Comment, doc: org.w3c.dom.Document): org.w3c.dom.Comment = {
    val domComment = doc.createComment(comment.text)
    domComment
  }

  private def createElementWithoutChildren(elm: Elem, doc: org.w3c.dom.Document, parentScope: Scope): Element = {
    val element =
      if (elm.resolvedName.namespaceUriOption.isEmpty) {
        doc.createElement(elm.localName)
      } else {
        doc.createElementNS(elm.resolvedName.namespaceUriOption.get, elm.qname.toString)
      }

    val namespaceDeclarations: Declarations = parentScope.relativize(elm.scope)

    for ((prefix, ns) <- namespaceDeclarations.prefixNamespaceMap) {
      if (prefix == "") {
        element.setAttribute("xmlns", ns)
      } else {
        element.setAttributeNS("http://www.w3.org/2000/xmlns/", s"xmlns:$prefix", ns)
      }
    }

    val attrScope = elm.attributeScope

    for ((attrQName, attrValue) <- elm.attributes) {
      if (attrQName.prefixOption.isEmpty) {
        // We use setAttributeNS and not setAttribute here.
        // According to Johan Walters, when using setAttribute, schema validation may fail in sufficiently
        // recent Xerces distributions, which is related to the distinction between implementation types Attr and AttrNS.
        element.setAttributeNS(null, attrQName.localPart, attrValue)
      } else {
        val attrEName = attrScope.resolveQNameOption(attrQName).getOrElse(sys.error(
          s"Attribute name '${attrQName}' should resolve to an EName in scope [${attrScope}]"))
        val attrJavaQName = attrEName.toJavaQName(attrQName.prefixOption)
        element.setAttributeNS(attrJavaQName.getNamespaceURI, attrQName.toString, attrValue)
      }
    }

    element
  }
}

object YaidomToDomConversions {

  /** Producer of a DOM `Element`, given a DOM `Document` as factory of DOM objects */
  type ElementProducer = (org.w3c.dom.Document => Element)

  /** Producer of a DOM `Document`, given the DOM `Document` as factory of DOM objects */
  type DocumentProducer = (org.w3c.dom.Document => org.w3c.dom.Document)
}


text:
package ctxkit

import (
	"context"

	"github.com/go-kit/log"
	grpc_ctxtags "github.com/grpc-ecosystem/go-grpc-middleware/tags"
)

type ctxMarker struct{}

type ctxLogger struct {
	logger log.Logger
	fields []interface{}
}

var (
	ctxMarkerKey = &ctxMarker{}
)

// AddFields adds fields to the logger.
func AddFields(ctx context.Context, fields ...interface{}) {
	l, ok := ctx.Value(ctxMarkerKey).(*ctxLogger)
	if !ok || l == nil {
		return
	}
	l.fields = append(l.fields, fields...)
}

// Extract takes the call-scoped Logger from grpc_kit middleware.
//
// It always returns a Logger that has all the grpc_ctxtags updated.
func Extract(ctx context.Context) log.Logger {
	l, ok := ctx.Value(ctxMarkerKey).(*ctxLogger)
	if !ok || l == nil {
		return log.NewNopLogger()
	}
	// Add grpc_ctxtags tags metadata until now.
	fields := TagsToFields(ctx)
	return log.With(l.logger, append(fields, l.fields...)...)
}

// TagsToFields transforms the Tags on the supplied context into kit fields.
func TagsToFields(ctx context.Context) []interface{} {
	var fields []interface{}
	tags := grpc_ctxtags.Extract(ctx)
	for k, v := range tags.Values() {
		fields = append(fields, k, v)
	}
	return fields
}

// ToContext adds the kit.Logger to the context for extraction later.
// Returning the new context that has been created.
func ToContext(ctx context.Context, logger log.Logger) context.Context {
	l := &ctxLogger{
		logger: logger,
	}
	return context.WithValue(ctx, ctxMarkerKey, l)
}


text:
from cStringIO import StringIO
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from pdfminer.pdftypes import PDFException
from pdfminer.psparser import PSException

import os.path
from glob import glob
from codecs import open

from topicexplorer.lib import util

from progressbar import ProgressBar, Percentage, Bar

def convert(fname, pages=None):
    if not pages:
        pagenums = set()
    else:
        pagenums = set(pages)

    output = StringIO()
    manager = PDFResourceManager()
    converter = TextConverter(manager, output, laparams=LAParams())
    interpreter = PDFPageInterpreter(manager, converter)

    infile = file(fname, 'rb')
    for page in PDFPage.get_pages(infile, pagenums):
        interpreter.process_page(page)
    infile.close()
    converter.close()
    text = output.getvalue()
    output.close()
    text += '\n'
    return text

def convert_and_write(fname, output_dir=None, overwrite=False, verbose=False):
    output = os.path.basename(fname)
    output = output.replace('.pdf','.txt')
    if output_dir:
        output = os.path.join(output_dir, output)
    if output_dir is not None and not os.path.exists(output_dir):
        os.makedirs(output_dir)

    if overwrite or util.overwrite_prompt(output):
        with open(output, 'wb') as outfile:
            outfile.write(convert(fname))
            if verbose:
                print "converted", fname, "->", output

def main(path_or_paths, output_dir=None, verbose=1):
    if isinstance(path_or_paths, basestring):
        path_or_paths = [path_or_paths]

    for p in path_or_paths:
        if os.path.isdir(p):
            num_files = len(list(util.find_files(p, '*.pdf')))
            if verbose == 1:
                pbar = ProgressBar(widgets=[Percentage(), Bar()],
                                   maxval=num_files).start()
            for file_n, pdffile in enumerate(util.find_files(p, '*.pdf')):
                try:
                    convert_and_write(pdffile, output_dir, overwrite=True)
                except (PDFException, PSException):
                    print "Skipping {0} due to PDF Exception".format(pdffile)

                if verbose == 1:
                    pbar.update(file_n)

            if verbose == 1:
                pbar.finish()
        else:
            convert_and_write(p, output_dir, overwrite=True, verbose=True)

if __name__ == '__main__':
    from argparse import ArgumentParser
    parser = ArgumentParser()

    parser.add_argument("path", nargs='+', help="PDF file or folder to parse",
        type=lambda x: util.is_valid_filepath(parser, x))
    parser.add_argument("-o", '--output',
        help="output path [default: same as filename]")

    args = parser.parse_args()

    main(args.path, args.output)


text:
export class Ajax {
    get(url:string):Promise<any> {
        return new Promise<any>((resolve, reject)=>{
            let request:XMLHttpRequest = new XMLHttpRequest();
            request.onreadystatechange = function() {
                if (request.readyState === 4) {
                    if (request.status === 200) {
                        resolve(request.responseText);
                    } else {
                        reject();
                    }
                }
            };
            request.open("GET", url, true);
            request.send(null);
        });

    }
}


text:
package org.fujion.plotly.layout;

import org.fujion.ancillary.Options;
import org.fujion.annotation.Option;
import org.fujion.plotly.common.DashStyleEnum;

/**
 * Layout options for shapes.
 */
public class ShapeOptions extends Options {

    /**
     * Type of shape.
     */
    public enum TypeEnum {
        /**
         * A circle is drawn from (("x0"+"x1")/2, ("y0"+"y1")/2)) with radius (|("x0"+"x1")/2 -
         * "x0"|, |("y0"+"y1")/2 -"y0")|)
         */
        CIRCLE,
        /**
         * A line is drawn from ("x0","y0") to ("x1","y1")
         */
        LINE,
        /**
         * Draw a custom SVG path using "path".
         */
        PATH,
        /**
         * A rectangle is drawn linking ("x0","y0"), ("x1","y0"), ("x1","y1"), ("x0","y1"),
         * ("x0","y0")
         */
        RECT;

        @Override
        public String toString() {
            return name().toLowerCase();
        }
    }

    /**
     * The color filling the shape's interior.
     *

     * Default: "rgba(0,0,0,0)"
     */
    @Option
    public String fillcolor;

    /**
     * Specifies whether shapes are drawn below or above traces.
     *

     * Default: ABOVE
     */
    @Option
    public LayerEnum layer;

    /**
     * The line color.
     */
    @Option("line.color")
    public String line_color;

    /**
     * The dash style of lines.
     *

     * Default: SOLID
     */
    @Option("line.dash")
    public DashStyleEnum line_dash;

    /**
     * The line width (in px).
     *

     * Default: 2
     */
    @Option("line.width")
    public Integer line_width;

    /**
     * The opacity of the shape.
     *

     * Constraints: ≥0 and ≤1
     *

     * Default: 1
     */
    @Option
    public Double opacity;

    /**
     * For "type" PATH - a valid SVG path but with the pixel values replaced by data values. There
     * are a few restrictions / quirks only absolute instructions, not relative. So the allowed
     * segments are: M, L, H, V, Q, C, T, S, and Z arcs (A) are not allowed because radius rx and ry
     * are relative. In the future we could consider supporting relative commands, but we would have
     * to decide on how to handle date and log axes. Note that even as is, Q and C Bezier paths that
     * are smooth on linear axes may not be smooth on log, and vice versa. no chained "polybezier"
     * commands - specify the segment type for each one. On category axes, values are numbers scaled
     * to the serial numbers of categories because using the categories themselves there would be no
     * way to describe fractional positions On data axes: because space and T are both normal
     * components of path strings, we can't use either to separate date from time parts. Therefore
     * we'll use underscore for this purpose: 2015-02-21_13:45:56.789.
     */
    @Option
    public String path;

    /**
     * Specifies the shape type to be drawn.
     */
    @Option
    public TypeEnum type;

    /**
     * Determines whether or not a shape is visible.
     *

     * Default: true.
     */
    @Option
    public Boolean visible;

    /**
     * The shape's starting x position.
     */
    @Option
    public Integer x0;

    /**
     * The shape's ending x position.
     */
    @Option
    public Integer x1;

    /**
     * The shape's x coordinate axis. If set to an x axis id (e.g. "x" or "x2"), the "x" position
     * refers to an x coordinate If set to "paper", the "x" position refers to the distance from the
     * left side of the plotting area in normalized coordinates where "0" ("1") corresponds to the
     * left (right) side. If the axis "type" is "log", then you must take the log of your desired
     * range. If the axis "type" is "date", then you must convert the date to unix time in
     * milliseconds.
     */
    @Option
    public String xref;

    /**
     * The shape's starting y position.
     */
    @Option
    public Integer y0;

    /**
     * The shape's ending y position.
     */
    @Option
    public Integer y1;

    /**
     * The annotation's y coordinate axis. If set to an y axis id (e.g. "y" or "y2"), the "y"
     * position refers to an y coordinate If set to "paper", the "y" position refers to the distance
     * from the bottom of the plotting area in normalized coordinates where "0" ("1") corresponds to
     * the bottom (top).
     */
    @Option
    public String yref;
}


text:
package org.skfiy.typhon.rnsd.web;

import org.skfiy.typhon.rnsd.Version;
import java.io.File;
import java.io.FilenameFilter;

/**
 *
 * @author Kevin Zou <kevinz@skfiy.org>
 */
class Upgrade implements Comparable<Upgrade> {

    private final File dir;
    private final Version version;

    Upgrade(File dir) {
        this.dir = dir;
        version = new Version(dir.getName());
    }

    File getDir() {
        return dir;
    }

    File[] getSqlFiles() {
        return getDir().listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".sql");
            }
        });
    }

    Version getVersion() {
        return version;
    }

    @Override
    public int compareTo(Upgrade o) {
        return version.compareTo(o.version);
    }
}


text:
package microsoft.exchange.webservices.data;

/**
 * Used to create instances of ComplexProperty.
 *
 * @param <TComplexProperty> Type that extends ComplexProperty
 */
interface ICreateComplexPropertyDelegate
    <TComplexProperty extends ComplexProperty> {

  /**
   * used to create instances of ComplexProperty.
   *
   * @return Complex property instance
   */
  TComplexProperty createComplexProperty();
}


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

/*=============================================================================
	PostProcessAA.h: Post processing anti aliasing implementation.
=============================================================================*/

#pragma once

#include "RenderingCompositionGraph.h"

// derives from TRenderingCompositePassBase<InputCount, OutputCount>
class FRCPassPostProcessAA : public TRenderingCompositePassBase<1, 1>
{
public:
	// @param InQuality 1..6, larger values are ignored
	FRCPassPostProcessAA(uint32 InQuality) : Quality(InQuality)
	{
		check(InQuality > 0);
	}

	// interface FRenderingCompositePass ---------

	virtual void Process(FRenderingCompositePassContext& Context) override;
	virtual void Release() override { delete this; }
	virtual FPooledRenderTargetDesc ComputeOutputDesc(EPassOutputId InPassOutputId) const override;

private:
	// 1..6, larger values are ignored
	uint32 Quality;
};


text:
constexpr auto Builtin_GLSL_BasicEffect_VS = R"(

layout(location=0)in vec3 Position;
#if LIGHTING_ENABLED
layout(location=1)in vec3 Normal;
#if TEXTURE_ENABLED
layout(location=2)in vec2 TextureCoord;
#else
layout(location=2)in vec4 Color;
#endif
#else
#if TEXTURE_ENABLED
layout(location=1)in vec2 TextureCoord;
#else
layout(location=1)in vec4 Color;
#endif
#endif
uniform ModelConstantBuffer{
mat4x4 Model;
vec4 Material;
vec4 DiffuseColor;};
uniform WorldConstantBuffer{
mat4x4 ViewProjection;
mat4x4 View;
mat4x4 Projection;
mat4x4 InverseView;
vec4 LightDirection;};
out VertexData{
#if LIGHTING_ENABLED
vec3 WorldSpacePosition;
vec3 Normal;
#endif
#if TEXTURE_ENABLED
vec2 TextureCoord;
#endif
#if VERTEX_COLOR_ENABLED
vec4 Color;
#endif
}Out;
void main(){
vec4 worldSpacePosition=Model*vec4(Position.xyz,1.0);
gl_Position=ViewProjection*worldSpacePosition;
#if LIGHTING_ENABLED
Out.WorldSpacePosition=worldSpacePosition.xyz;
Out.Normal=mat3x3(Model)*Normal.xyz;
#endif
#if TEXTURE_ENABLED
Out.TextureCoord=TextureCoord.xy;
#endif
#if VERTEX_COLOR_ENABLED
Out.Color=Color.rgba;
#endif
}
)";


text:
from django.apps import AppConfig

class KeopsConfig(AppConfig):
    name = 'keops'
    data = ['base.xml']


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/channel/v1/service.proto

package com.google.cloud.channel.v1;

public interface GetCustomerRepricingConfigRequestOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.channel.v1.GetCustomerRepricingConfigRequest)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Required. The resource name of the CustomerRepricingConfig.
   * Format:
   * accounts/{account_id}/customers/{customer_id}/customerRepricingConfigs/{id}.
   *

   *
   *
   * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The name.
   */
  java.lang.String getName();
  /**
   *
   *
   *

   * Required. The resource name of the CustomerRepricingConfig.
   * Format:
   * accounts/{account_id}/customers/{customer_id}/customerRepricingConfigs/{id}.
   *

   *
   *
   * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The bytes for name.
   */
  com.google.protobuf.ByteString getNameBytes();
}


text:
package cz.cuni.mff.spl.deploy.store.exception;

import cz.cuni.mff.spl.deploy.exception.DeployException;

/**
 *
 * @author Frantisek Haas
 *
 */
public class StoreException extends DeployException {

    /**
     * Serialization ID.
     */
    private static final long serialVersionUID = 7444306552791657755L;

    public StoreException() {

    }

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

    public StoreException(Throwable cause) {
        super(cause);
    }

    public StoreException(String message, Throwable cause) {
        super(message, cause);
    }
}


text:
package ch.hellorin.jcsp;

import org.jcsp.lang.*;

/**
 * Testing alting with poisonable channels.
 *
 * @author David LAWRENCE
 * @version 1.0
 */
public class TestAltingPoison {

	/** Main **/
	public static void main (String[] args) {
		// Case where the timeout is reached and the channel is poisoned
		int timeBeforeWrite = 200; // in ms
		int timeoutTime     = 100; // in ms
		System.out.println("###############################");
		System.out.println("### Timeout reached example ###");
		System.out.println("###############################");
		execute_example(timeoutTime, timeBeforeWrite);
		System.out.println("");

		// Case where a message is written on the channel
		timeBeforeWrite = 100; // in ms
		timeoutTime     = 200; // in ms
		System.out.println("#######################################");
		System.out.println("### Data written on channel example ###");
		System.out.println("#######################################");
		execute_example(timeoutTime, timeBeforeWrite);
		System.out.println("");
	}

	/**
	 * Execute the example with a given value of timeout
	 *
	 * @param timeoutTime
	 * 		Waiting time before a timeout is reached
	 * @param timeBeforeWrite
	 * 		Waiting time before writing to the data channel
	 **/
	private static void execute_example(final int timeoutTime, final int timeBeforeWrite) {
		// Create a channel for data transmission with a poison Immunity of 0
		One2OneChannel dataLink = Channel.one2one(0);

		// Execute two processes in parallel: One that wait either for
		// a data written on the data channel or for a timeout
		System.out.println("Execute the two processes");
		new Parallel (
				new CSProcess[] {
						new Processing(dataLink.in(), timeoutTime),
						new DataChannelManager(dataLink.out(), timeBeforeWrite)
				}
		).run();
		System.out.println("End of program");
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Policy
      xmlns="urn:oasis:names:tc:xacml:2.0:policy:schema:os"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="urn:oasis:names:tc:xacml:2.0:policy:schema:os
        access_control-xacml-2.0-policy-schema-os.xsd"
      PolicyId="urn:oasis:names:tc:xacml:2.0:conformance-test:IIC214:policy"
      RuleCombiningAlgId="urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:deny-overrides">
    <Description>
        Policy for Conformance Test IIC214.
    </Description>
    <Target/>
    <Rule
          RuleId="urn:oasis:names:tc:xacml:2.0:conformance-test:IIC214:rule"
          Effect="Permit">
        <Condition>
            <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:x500Name-subset">
            <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:x500Name-bag">
                <AttributeValue
                      DataType="urn:oasis:names:tc:xacml:1.0:data-type:x500Name">  cn=Anne,OU=Sun Labs, o=Sun, c=US</AttributeValue>
                <AttributeValue
                      DataType="urn:oasis:names:tc:xacml:1.0:data-type:x500Name">cn=AHA,ou=Sun Labs,o=Sun,c=US</AttributeValue>
            </Apply>
            <SubjectAttributeDesignator
                  AttributeId="urn:oasis:names:tc:xacml:2.0:conformance-test:test-attr"
                  DataType="urn:oasis:names:tc:xacml:1.0:data-type:x500Name"/>
            </Apply>
        </Condition>
    </Rule>
</Policy>


text:
using System;
using System.Runtime.CompilerServices;

namespace jQueryApi.UI.Interactions {

    /// <summary>
    /// Create targets for draggable elements
    /// </summary>
    /// <remarks>
    /// <para>The jQuery UI Droppable plugin makes selected elements droppable (meaning they accept being dropped on by draggables). You can specify which (individually) or which kind of draggables each will accept.</para>
    /// </remarks>
    [ScriptImport]
    [ScriptIgnoreNamespace]
    public sealed class DroppableObject : WidgetObject {

        private DroppableObject() {
        }

        [ScriptName("droppable")]
        public DroppableObject Droppable() {
            return null;
        }

        [ScriptName("droppable")]
        public DroppableObject Droppable(DroppableOptions options) {
            return null;
        }
    }
}


text: - https://www.imooc.com/video/17462


text:
using UnityEngine;
using System.Collections;

public class DebugMode : MonoBehaviour
{
    public bool enableDebugMode = true;

    private GameObject player;
    private PlayerController playerController;

	void Start ()
	{
	    player = FindObjectOfType<PlayerController>().gameObject;
	    playerController = player.GetComponent<PlayerController>();
	    if (!player || !playerController)
	    {
	        Debug.LogWarning("Player could not be found, is the player controller script disabled?");
	    }
	}

	//Add Whatever You Want
	void Update ()
    {
	    if (enableDebugMode)
	    {
            if (Input.GetKeyDown(KeyCode.E))
            {
                FindObjectOfType<GateScript>().openGate = true;
                //Overkill
                FindObjectOfType<GateScript>().gameObject.transform.parent.GetComponent<BoxCollider>().enabled = false;
            }

        }
	}
}


text:
CREATE OR REPLACE FUNCTION devilry__on_commentfile_after_insert_or_update() RETURNS TRIGGER AS $$
DECLARE
    var_group_id integer;
BEGIN
    var_group_id = devilry__get_group_id_from_comment_id(NEW.comment_id);
    IF var_group_id IS NOT NULL THEN
        PERFORM devilry__rebuild_assignmentgroupcacheddata(var_group_id);
    END IF;
    RETURN NEW;
END
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS devilry__on_commentfile_after_insert_or_update_trigger
    ON devilry_comment_commentfile;
CREATE TRIGGER devilry__on_commentfile_after_insert_or_update_trigger
    AFTER INSERT OR UPDATE ON devilry_comment_commentfile
    FOR EACH ROW
        EXECUTE PROCEDURE devilry__on_commentfile_after_insert_or_update();

CREATE OR REPLACE FUNCTION devilry__on_commentfile_after_delete() RETURNS TRIGGER AS $$
DECLARE
    var_group_id integer;
BEGIN
    var_group_id = devilry__get_group_id_from_comment_id(OLD.comment_id);
    IF var_group_id IS NOT NULL THEN
        PERFORM devilry__rebuild_assignmentgroupcacheddata(var_group_id);
    END IF;
    RETURN OLD;
END
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS devilry__on_commentfile_after_delete
    ON devilry_comment_commentfile;
CREATE TRIGGER devilry__on_commentfile_after_delete
    AFTER DELETE ON devilry_comment_commentfile
    FOR EACH ROW
        EXECUTE PROCEDURE devilry__on_commentfile_after_delete();


text:
import pymongo
import json
import traceback

cache = {}

client = pymongo.MongoClient()
try:
	dbConf = json.load(open("./model/db.json","r"))
except:
	try:
		dbConf = json.load(open("./db.json","r"))
	except:
		dbConf = {"dbname": "voteview"}

db = client[dbConf["dbname"]]

def partyLookup(qDict, api):
	if api not in ["Web_FP_Search", "exportCSV", "Web_Members"]:
		return {}

	if not "id" in qDict and not "name" in qDict:
		return {}

	if "id" in qDict:
		party = db.voteview_parties.find_one({"id": qDict["id"]}, {"_id": 0, "id": 1, "count": 1, "fullName": 1, "colorScheme": 1, "minCongress": 1, "maxCongress": 1, "partyname": 1, "noun": 1, "loyalty_counts": 1})

                if api == "Web_Members" and party:
                        return party['loyalty_counts']

		if party and not "colorScheme" in party:
			party["colorScheme"] = "grey"

		if not party:
			return {}
		else:
			return {"results": [party]}

	elif "name" in qDict:
		parties = db.voteview_parties.find({"fullName": {"$regex": ".*"+qDict["name"]+".*", "$options": "i"}}, {"_id": 0, "id": 1, "count": 1, "fullName": 1, "colorScheme": 1, "minCongress": 1, "maxCongress": 1, "partyname": 1, "noun": 1})
		partySet = []
		for party in parties:
			if party and not "colorScheme" in party:
				party["colorScheme"] = "grey"

			partySet.append(party)
		if len(partySet):
			return {"results": partySet}
		else:
			return {}

	return {}

def noun(id):
	if str(id) in cache:
		return cache[str(id)]["noun"]

	results = partyLookup({"id": id}, "Web_FP_Search")
	if "results" in results:
		cache[str(id)] = results["results"][0]
		return results["results"][0]["noun"]
	else:
		return "Error Noun "+str(id)

def partyName(id):
	if str(id) in cache:
		return cache[str(id)]["fullName"]

	results = partyLookup({"id": id}, "Web_FP_Search")
	if "results" in results:
		cache[str(id)] = results["results"][0]
		return results["results"][0]["fullName"]
	else:
		return "Error Party "+str(id)

def shortName(id):
	if str(id) in cache:
		return cache[str(id)]["partyname"]

	results = partyLookup({"id": id}, "Web_FP_Search")
	if "results" in results:
		cache[str(id)] = results["results"][0]
		return results["results"][0]["partyname"]
	else:
		return "party "+str(id)

def partyColor(id):
	if str(id) in cache:
		return cache[str(id)]["colorScheme"]

	results = partyLookup({"id": id}, "Web_FP_Search")
	if "results" in results:
		cache[str(id)] = results["results"][0]
		return results["results"][0]["colorScheme"]
	else:
		return "grey"

if __name__ == "__main__":
        print partyLookup({"id":200}, "Web_Members")
        #print noun(5000)
	#print partyName(347)
	#print partyLookup({"name": "democrat"}, "Web_FP_Search")