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

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.devtools.build.lib.analysis.TransitionMode.TARGET;

import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.TransitiveInfoCollection;
import com.google.devtools.build.lib.analysis.config.CoreOptionConverters.StrictDepsMode;
import com.google.devtools.build.lib.rules.java.JavaCompilationArgsProvider;
import com.google.devtools.build.lib.rules.java.JavaCompilationArtifacts;
import com.google.devtools.build.lib.rules.java.JavaInfo;
import com.google.devtools.build.lib.rules.java.JavaLibraryHelper;
import com.google.devtools.build.lib.rules.java.JavaRuleOutputJarsProvider;
import com.google.devtools.build.lib.rules.java.JavaRuntimeInfo;
import com.google.devtools.build.lib.rules.java.JavaSemantics;
import com.google.devtools.build.lib.rules.java.JavaToolchainProvider;
import com.google.devtools.build.lib.rules.proto.ProtoLangToolchainProvider;

/** Common logic used by java*_proto aspects (e.g. {@link JavaLiteProtoAspect}). */
public class JavaProtoAspectCommon {

  // The name of an attribute of {@link JavaProtoAspect} used for storing the {@link Label} of
  // the proto toolchain for Java.
  public static final String SPEED_PROTO_TOOLCHAIN_ATTR = ":aspect_java_proto_toolchain";
  // The name of an attribute of {@link JavaLiteProtoLibrary} and {@link JavaLiteProtoAspect} used
  // for storing the {@link Label} of the proto toolchain for Java-lite.
  public static final String LITE_PROTO_TOOLCHAIN_ATTR = ":aspect_proto_toolchain_for_javalite";

  private static final String SPEED_JAR_SUFFIX = "-speed";
  private static final String LITE_JAR_SUFFIX = "-lite";
  private static final String MUTABLE_JAR_SUFFIX = "-new-mutable";

  private final RuleContext ruleContext;
  private final JavaSemantics javaSemantics;
  private final String protoToolchainAttr;
  private final String jarSuffix;
  private final RpcSupport rpcSupport;

  /**
   * Returns a {@link JavaProtoAspectCommon} instance that handles logic for {@code
   * java_proto_library}.
   */
  static JavaProtoAspectCommon getSpeedInstance(
      RuleContext ruleContext, JavaSemantics javaSemantics, RpcSupport rpcSupport) {
    return new JavaProtoAspectCommon(
        ruleContext, javaSemantics, rpcSupport, SPEED_PROTO_TOOLCHAIN_ATTR, SPEED_JAR_SUFFIX);
  }

  /**
   * Returns a {@link JavaProtoAspectCommon} instance that handles logic for {@code
   * java_lite_proto_library}.
   */
  static JavaProtoAspectCommon getLiteInstance(
      RuleContext ruleContext, JavaSemantics javaSemantics) {
    return new JavaProtoAspectCommon(
        ruleContext, javaSemantics, null, LITE_PROTO_TOOLCHAIN_ATTR, LITE_JAR_SUFFIX);
  }

  /**
   * Returns a {@link JavaProtoAspectCommon} instance that handles logic for {@code
   * java_mutable_proto_library}.
   */
  public static JavaProtoAspectCommon getMutableInstance(
      RuleContext ruleContext,
      JavaSemantics javaSemantics,
      RpcSupport rpcSupport,
      String protoToolchainAttr) {
    return new JavaProtoAspectCommon(
        ruleContext, javaSemantics, rpcSupport, protoToolchainAttr, MUTABLE_JAR_SUFFIX);
  }

  private JavaProtoAspectCommon(
      RuleContext ruleContext,
      JavaSemantics javaSemantics,
      RpcSupport rpcSupport,
      String protoToolchainAttr,
      String jarSuffix) {
    this.ruleContext = ruleContext;
    this.javaSemantics = javaSemantics;
    this.protoToolchainAttr = protoToolchainAttr;
    this.jarSuffix = jarSuffix;
    this.rpcSupport = rpcSupport;
  }

  /**
   * Registers an action that compiles the given {@code sourceJar} and archives the compiled classes
   * into {@code outputJar}, using {@code dep} as information about the dependencies compilation.
   *
   * @return a {@JavaCompilationArgsProvider} wrapping information about the compilation action that
   *     was registered.
   */
  public JavaCompilationArgsProvider createJavaCompileAction(
      String injectingRuleKind,
      Artifact sourceJar,
      Artifact outputJar,
      JavaCompilationArgsProvider dep)
      throws InterruptedException {
    JavaLibraryHelper helper =
        new JavaLibraryHelper(ruleContext)
            .setInjectingRuleKind(injectingRuleKind)
            .setOutput(outputJar)
            .addSourceJars(sourceJar)
            .setJavacOpts(ProtoJavacOpts.constructJavacOpts(ruleContext))
            .addDep(dep)
            .setCompilationStrictDepsMode(StrictDepsMode.ERROR);
    for (TransitiveInfoCollection t : getProtoRuntimeDeps()) {
      JavaCompilationArgsProvider provider =
          JavaInfo.getProvider(JavaCompilationArgsProvider.class, t);
      if (provider != null) {
        helper.addDep(provider);
      }
    }

    JavaCompilationArtifacts artifacts =
        helper.build(
            javaSemantics,
            JavaToolchainProvider.from(ruleContext),
            JavaRuntimeInfo.forHost(ruleContext),
            JavaRuleOutputJarsProvider.builder(),
            /*createOutputSourceJar*/ false,
            /*outputSourceJar=*/ null);
    return helper.buildCompilationArgsProvider(
        artifacts, /*isReportedAsStrict=*/ true, /*isNeverlink=*/ false);
  }

  /**
   * Returns a list of all the target needed by proto libraries (e.g. {@code java_proto_library}) at
   * runtime.
   */
  public ImmutableList<TransitiveInfoCollection> getProtoRuntimeDeps() {
    ImmutableList.Builder<TransitiveInfoCollection> result = ImmutableList.builder();
    TransitiveInfoCollection runtime = getProtoToolchainProvider().runtime();
    if (runtime != null) {
      result.add(runtime);
    }
    if (rpcSupport != null) {
      result.addAll(rpcSupport.getRuntimes(ruleContext));
    }
    return result.build();
  }

  /** Returns the toolchain that specifies how to generate code from {@code .proto} files. */
  public ProtoLangToolchainProvider getProtoToolchainProvider() {
    return checkNotNull(
        ruleContext.getPrerequisite(protoToolchainAttr, TARGET, ProtoLangToolchainProvider.class));
  }

  /**
   * Returns the toolchain that specifies how to generate Java-lite code from {@code .proto} files.
   */
  static ProtoLangToolchainProvider getLiteProtoToolchainProvider(RuleContext ruleContext) {
    return ruleContext.getPrerequisite(
        LITE_PROTO_TOOLCHAIN_ATTR, TARGET, ProtoLangToolchainProvider.class);
  }

  /**
   * Returns an {@link Artifact} corresponding to a source jar. Its name is computed from the label
   * name and the library type of the current instance. For example, if the instance is created with
   * {@link getLiteInstance} the name of the jar will be "-lite-src.jar".
   *
   *
The {@link Artifact} will be created in the bazel-genfiles directory.
   */
  public Artifact getSourceJarArtifact() {
    return ruleContext.getGenfilesArtifact(
        ruleContext.getLabel().getName() + jarSuffix + "-src.jar");
  }

  /**
   * Returns an {@link Artifact} corresponding to an output jar. Its name is computed from the label
   * name and the library type of the current instance. For example, if the instance is created with
   * {@link getLiteInstance} the name of the jar will be "lib-lite.jar".
   *
   *
The {@link Artifact} will be created in the bazel-bin directory.
   */
  public Artifact getOutputJarArtifact() {
    return ruleContext.getBinArtifact(
        "lib" + ruleContext.getLabel().getName() + jarSuffix + ".jar");
  }
}


text:
Product Variations
==================

With the eCommerce module is possible to sell variants of the same product. Doing so keeps your
store looking tidy when users browse the site. Here we explain how you can manage these variations.

A product can have an unlimited number of variations. Each variation has a individual price and
product id associated with it.

A few terms to understand: _Variation, Attribute Type, Attribute Value._
This table for a "Ball" product explains the terminology visually:

![Here is an example table to help demonstrate](\images\product-variation-table.jpg)

Each variation also has one or more attribute values of a specific type.
The ball example above has a variation with the attribute value 'small' for the attribute type 'size'.

Creating Attribute Types and Values
-----------------------------------

Before you create a product variation, you should first create a some attributes types, with values
to choose from.

 1. Create Attribute Types

  * In the CMS, select the product you wish to edit.
  * Find the 'Content > Variations' tab for your product.
  * Click the "Add Product Attribute Type" link in the "Variation Attribute Types" table.
  * Give the new attribute type a name (eg: "Shoe Size") and label (eg: "Size"). The 'label' is used on the front-end of the website.
  * Click 'Save'

 2. Assign attribute types to the product

  * Check the newly created attribute type in the 'Variation Attribute Types' table.
  * Save and publish the product page.
  * Note that you should save the product after checking each attribute type. The attribute types may not be set otherwise.

 3. Create Attribute Values

  * Click the product attribute type edit icon.
  * Switch to the 'Values' tab.
  * Fill out 'Value' and 'Sort' table as required.

 Note, you can also manage product attribute types and values in the "Products" section:

  * Switch to the 'Products' section of the SilverStripe CMS.
  * Choose 'Product Attribute Type' from the 'Search for:' drop-down list on the left.
  * Find and click on the attribute type you want to add values to.
  * In the 'Values' tab, click the 'Add Product Attribute Value' link and add any number of values. You can set a sort value for each, if appropriate eg: "small" would need to come before "medium".

Creating a Product Variation
----------------------------

Once you have set up some attribute types and values, and then assigned some attribute types to your product,
you can create variations for it.

 * Find the 'Variations' tab for the product.
 * Click 'Add Product Variation'
 * Fill out a product code, and price.
 * Select attribute values from the attribute type drop-downs.
 * Save

Creating and updating variations from a spreadsheet
---------------------------------------------------

See [Bulk Loading Products](BulkLoadingProducts#ProductVariations.md).

redpajama_set_name: RedPajamaGithub


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.08.09 at 06:44:50 PM IST
//

package org.ieee.ltsc.lom.resource;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;

/**
 *
Java class for LanguageString.Type complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="LanguageString.Type">
 *   <simpleContent>
 *     <extension base="<http://www.w3.org/2001/XMLSchema>string">
 *       <attribute name="language" type="{http://ltsc.ieee.org/xsd/apipv1p0/LOM/resource}CharacterString.Type" />
 *     </extension>
 *   </simpleContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "LanguageString.Type", propOrder = {
    "value"
})
public class LanguageStringType {

    @XmlValue
    protected String value;
    @XmlAttribute(name = "language")
    protected String language;

    /**
     * Gets the value of the value property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getValue() {
        return value;
    }

    /**
     * Sets the value of the value property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setValue(String value) {
        this.value = value;
    }

    /**
     * Gets the value of the language property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getLanguage() {
        return language;
    }

    /**
     * Sets the value of the language property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setLanguage(String value) {
        this.language = value;
    }

}


text:
<?php

namespace FPlus\Millennium\Model;

use FPlus\Millennium\Utils\MapIterator;

class ClientHistoryMap implements \IteratorAggregate
{
    /**
     * @var DateKeyValuePair[]
     */
    protected $KeyValueOfdateTimeArrayOfClientHistoryabPHSVWZ;

    public function __construct()
    {
    }

    /**
     * @return DateKeyValuePair[]
     */
    public function getPairs()
    {
        return $this->KeyValueOfdateTimeArrayOfClientHistoryabPHSVWZ;
    }

    /**
     * @param DateKeyValuePair[] $Pairs
     *
     * @return ClientHistoryMap
     */
    public function setPairs(array $Pairs = null)
    {
        $this->KeyValueOfdateTimeArrayOfClientHistoryabPHSVWZ = $Pairs;

        return $this;
    }

    public function getIterator()
    {
        return new MapIterator($this->KeyValueOfdateTimeArrayOfClientHistoryabPHSVWZ);
    }
}


text:
use std::collections::BTreeMap;

use serde::{de, Deserialize, Deserializer, Serialize, Serializer};

use crate::models::krate::MAX_NAME_LENGTH;

use crate::models::Crate;
use crate::models::DependencyKind;
use crate::models::Keyword as CrateKeyword;

#[derive(Deserialize, Serialize, Debug)]
pub struct EncodableCrateUpload {
    pub name: EncodableCrateName,
    pub vers: EncodableCrateVersion,
    pub deps: Vec<EncodableCrateDependency>,
    pub features: BTreeMap<EncodableFeatureName, Vec<EncodableFeature>>,
    pub description: Option<String>,
    pub homepage: Option<String>,
    pub documentation: Option<String>,
    pub readme: Option<String>,
    pub readme_file: Option<String>,
    #[serde(default)]
    pub keywords: EncodableKeywordList,
    #[serde(default)]
    pub categories: EncodableCategoryList,
    pub license: Option<String>,
    pub license_file: Option<String>,
    pub repository: Option<String>,
    #[serde(default)]
    pub links: Option<String>,
}

#[derive(PartialEq, Eq, Hash, Serialize, Debug, Deref)]
pub struct EncodableCrateName(pub String);
#[derive(Serialize, Debug, Deref)]
pub struct EncodableDependencyName(pub String);
#[derive(Debug, Deref)]
pub struct EncodableCrateVersion(pub semver::Version);
#[derive(Debug, Deref)]
pub struct EncodableCrateVersionReq(pub String);
#[derive(Serialize, Debug, Deref, Default)]
pub struct EncodableKeywordList(pub Vec<EncodableKeyword>);
#[derive(Serialize, Debug, Deref)]
pub struct EncodableKeyword(pub String);
#[derive(Serialize, Debug, Deref, Default)]
pub struct EncodableCategoryList(pub Vec<EncodableCategory>);
#[derive(Serialize, Deserialize, Debug, Deref)]
pub struct EncodableCategory(pub String);
#[derive(Serialize, Debug, Deref)]
pub struct EncodableFeature(pub String);
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Debug, Deref)]
pub struct EncodableFeatureName(pub String);

#[derive(Serialize, Deserialize, Debug)]
pub struct EncodableCrateDependency {
    pub optional: bool,
    pub default_features: bool,
    pub name: EncodableCrateName,
    pub features: Vec<EncodableFeature>,
    pub version_req: EncodableCrateVersionReq,
    pub target: Option<String>,
    pub kind: Option<DependencyKind>,
    pub explicit_name_in_toml: Option<EncodableDependencyName>,
    pub registry: Option<String>,
}

impl<'de> Deserialize<'de> for EncodableCrateName {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<EncodableCrateName, D::Error> {
        let s = String::deserialize(d)?;
        if !Crate::valid_name(&s) {
            let value = de::Unexpected::Str(&s);
            let expected = format!(
                "a valid crate name to start with a letter, contain only letters, \
                 numbers, hyphens, or underscores and have at most {MAX_NAME_LENGTH} characters"
            );
            Err(de::Error::invalid_value(value, &expected.as_ref()))
        } else {
            Ok(EncodableCrateName(s))
        }
    }
}

impl<T: ?Sized> PartialEq<T> for EncodableCrateName
where
    String: PartialEq<T>,
{
    fn eq(&self, rhs: &T) -> bool {
        self.0 == *rhs
    }
}

impl<'de> Deserialize<'de> for EncodableDependencyName {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<EncodableDependencyName, D::Error> {
        let s = String::deserialize(d)?;
        if !Crate::valid_dependency_name(&s) {
            let value = de::Unexpected::Str(&s);
            let expected = format!(
                "a valid dependency name to start with a letter or underscore, contain only letters, \
                 numbers, hyphens, or underscores and have at most {MAX_NAME_LENGTH} characters"
            );
            Err(de::Error::invalid_value(value, &expected.as_ref()))
        } else {
            Ok(EncodableDependencyName(s))
        }
    }
}

impl<'de> Deserialize<'de> for EncodableKeyword {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<EncodableKeyword, D::Error> {
        let s = String::deserialize(d)?;
        if !CrateKeyword::valid_name(&s) {
            let value = de::Unexpected::Str(&s);
            let expected = "a valid keyword specifier";
            Err(de::Error::invalid_value(value, &expected))
        } else {
            Ok(EncodableKeyword(s))
        }
    }
}

impl<'de> Deserialize<'de> for EncodableFeatureName {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let s = String::deserialize(d)?;
        if !Crate::valid_feature_name(&s) {
            let value = de::Unexpected::Str(&s);
            let expected = "a valid feature name containing only letters, \
                            numbers, '-', '+', or '_'";
            Err(de::Error::invalid_value(value, &expected))
        } else {
            Ok(EncodableFeatureName(s))
        }
    }
}

impl<'de> Deserialize<'de> for EncodableFeature {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<EncodableFeature, D::Error> {
        let s = String::deserialize(d)?;
        if !Crate::valid_feature(&s) {
            let value = de::Unexpected::Str(&s);
            let expected = "a valid feature name";
            Err(de::Error::invalid_value(value, &expected))
        } else {
            Ok(EncodableFeature(s))
        }
    }
}

impl<'de> Deserialize<'de> for EncodableCrateVersion {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<EncodableCrateVersion, D::Error> {
        let s = String::deserialize(d)?;
        match semver::Version::parse(&s) {
            Ok(v) => Ok(EncodableCrateVersion(v)),
            Err(..) => {
                let value = de::Unexpected::Str(&s);
                let expected = "a valid semver";
                Err(de::Error::invalid_value(value, &expected))
            }
        }
    }
}

impl<'de> Deserialize<'de> for EncodableCrateVersionReq {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<EncodableCrateVersionReq, D::Error> {
        let s = String::deserialize(d)?;
        match semver::VersionReq::parse(&s) {
            Ok(_) => Ok(EncodableCrateVersionReq(s)),
            Err(..) => {
                let value = de::Unexpected::Str(&s);
                let expected = "a valid version req";
                Err(de::Error::invalid_value(value, &expected))
            }
        }
    }
}

impl<'de> Deserialize<'de> for EncodableKeywordList {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<EncodableKeywordList, D::Error> {
        let inner = <Vec<EncodableKeyword> as Deserialize<'de>>::deserialize(d)?;
        if inner.len() > 5 {
            let expected = "at most 5 keywords per crate";
            return Err(de::Error::invalid_length(inner.len(), &expected));
        }
        for val in &inner {
            if val.len() > 20 {
                let expected = "a keyword with less than 20 characters";
                return Err(de::Error::invalid_length(val.len(), &expected));
            }
        }
        Ok(EncodableKeywordList(inner))
    }
}

impl<'de> Deserialize<'de> for EncodableCategoryList {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<EncodableCategoryList, D::Error> {
        let inner = <Vec<EncodableCategory> as Deserialize<'de>>::deserialize(d)?;
        if inner.len() > 5 {
            let expected = "at most 5 categories per crate";
            Err(de::Error::invalid_length(inner.len(), &expected))
        } else {
            Ok(EncodableCategoryList(inner))
        }
    }
}

impl Serialize for EncodableCrateVersion {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&(**self).to_string())
    }
}

impl Serialize for EncodableCrateVersionReq {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&(**self).to_string())
    }
}

use diesel::pg::Pg;
use diesel::serialize::{self, Output, ToSql};
use diesel::sql_types::Text;
use std::io::Write;

impl ToSql<Text, Pg> for EncodableFeature {
    fn to_sql<W: Write>(&self, out: &mut Output<'_, W, Pg>) -> serialize::Result {
        ToSql::<Text, Pg>::to_sql(&**self, out)
    }
}

#[test]
fn feature_deserializes_for_valid_features() {
    use serde_json as json;

    assert_ok!(json::from_str::<EncodableFeature>("\"foo\""));
    assert_err!(json::from_str::<EncodableFeature>("\"\""));
    assert_err!(json::from_str::<EncodableFeature>("\"/\""));
    assert_err!(json::from_str::<EncodableFeature>("\"%/%\""));
    assert_ok!(json::from_str::<EncodableFeature>("\"a/a\""));
    assert_ok!(json::from_str::<EncodableFeature>("\"32-column-tables\""));
}


text:
@implementation BannerModel
+ (NSDictionary *)replacedKeyFromPropertyName
{
    return @{@"banner_id" : @"id",
             };
}

@end


text:
def render(path, &block)
  content_file = ContentFile.new(path)

  if content_file.fullpath.end_with?(".haml")
    if block_given?
      Haml::Engine.new(content_file.contents).render(&block)
    else
      Haml::Engine.new(content_file.contents).render
    end
  elsif content_file.fullpath.end_with?(".md")
    PandocRuby.new(content_file.contents).to_html
  else
    raise "Renderer not found for #{content_file.fullpath}."
  end
end

class ContentFile
  EXTS = [".md", ".haml"]

  attr_reader :path, :ext, :stem, :dir, :basename

  def initialize(path)
    @path = path
    @ext = File.extname(path)
    @stem = File.basename(path, ext)
    @dir = File.dirname(path)
    @basename = File.basename(path)

    raise "#{path} does not exist" unless exists?
  end

  def contents
    @contents ||= EmojiParser.detokenize(File.read(fullpath))
  end

  def fullpath
    @fullpath ||= candidates.detect { |path| File.exists?(path) }
  end

  def to_s
    basename
  end

  def exists?
    fullpath != nil
  end

  def partial?
    stem.start_with?("_")
  end

  # If the template opens with a doctype declaration, assume we're a full
  # page.
  def fullpage?
    File.open(path, &:readline)[0..2] == "!!!"
  end

  private

  def candidates
    [
      path,
      File.join(dir, "_" + basename),
      File.join(dir, "content", basename),
      File.join(dir, "content", "_" + basename),
      EXTS.map { |ext| path + ext },
      EXTS.map { |ext| File.join(dir, "_" + stem + ext) },
      EXTS.map { |ext| File.join("content", path + ext) },
      EXTS.map { |ext| File.join(dir, "content", "_" + stem + ext) }
    ].flatten
  end
end


text:
using System.Text;

namespace Papper.Internal
{
    internal interface ITree
    {
        ITreeNode Root { get; }
        ITreeNode? Get(ITreePath path);
        ITreeNode? Get(ITreePath path, ref int offset, ref StringBuilder symbolicPath, bool getRef = false);
        bool TryGet(ITreePath path, out ITreeNode node);
        bool TryGet(ITreePath path, ref int offset, ref StringBuilder symbolicPath, out ITreeNode node, bool getRef = false);
    }
}


text:
#include "sqliteInt.h"

#ifndef SQLITE_OMIT_VIRTUALTABLE
/* Forward declaration */
static void updateVirtualTable(
  Parse *pParse,       /* The parsing context */
  SrcList *pSrc,       /* The virtual table to be modified */
  Table *pTab,         /* The virtual table */
  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
  Expr *pRowidExpr,    /* Expression used to recompute the rowid */
  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
  Expr *pWhere         /* WHERE clause of the UPDATE statement */
);
#endif /* SQLITE_OMIT_VIRTUALTABLE */

/*
** The most recently coded instruction was an OP_Column to retrieve the
** i-th column of table pTab. This routine sets the P4 parameter of the
** OP_Column to the default value, if any.
**
** The default value of a column is specified by a DEFAULT clause in the
** column definition. This was either supplied by the user when the table
** was created, or added later to the table definition by an ALTER TABLE
** command. If the latter, then the row-records in the table btree on disk
** may not contain a value for the column and the default value, taken
** from the P4 parameter of the OP_Column instruction, is returned instead.
** If the former, then all row-records are guaranteed to include a value
** for the column and the P4 value is not required.
**
** Column definitions created by an ALTER TABLE command may only have
** literal default values specified: a number, null or a string. (If a more
** complicated default expression value was provided, it is evaluated
** when the ALTER TABLE is executed and one of the literal values written
** into the sqlite_master table.)
**
** Therefore, the P4 parameter is only required if the default value for
** the column is a literal number, string or null. The sqlite3ValueFromExpr()
** function is capable of transforming these types of expressions into
** sqlite3_value objects.
**
** If parameter iReg is not negative, code an OP_RealAffinity instruction
** on register iReg. This is used when an equivalent integer value is
** stored in place of an 8-byte floating point value in order to save
** space.
*/
void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
  assert( pTab!=0 );
  if( !pTab->pSelect ){
    sqlite3_value *pValue;
    u8 enc = ENC(sqlite3VdbeDb(v));
    Column *pCol = &pTab->aCol[i];
    VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
    assert( i<pTab->nCol );
    sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
                         pCol->affinity, &pValue);
    if( pValue ){
      sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
    }
#ifndef SQLITE_OMIT_FLOATING_POINT
    if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
      sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
    }
#endif
  }
}

/*
** Process an UPDATE statement.
**
**   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
**          \_______/ \________/     \______/       \________________/
*            onError   pTabList      pChanges             pWhere
*/
void sqlite3Update(
  Parse *pParse,         /* The parser context */
  SrcList *pTabList,     /* The table in which we should change things */
  ExprList *pChanges,    /* Things to be changed */
  Expr *pWhere,          /* The WHERE clause.  May be null */
  int onError            /* How to handle constraint errors */
){
  int i, j;              /* Loop counters */
  Table *pTab;           /* The table to be updated */
  int addr = 0;          /* VDBE instruction address of the start of the loop */
  WhereInfo *pWInfo;     /* Information about the WHERE clause */
  Vdbe *v;               /* The virtual database engine */
  Index *pIdx;           /* For looping over indices */
  int nIdx;              /* Number of indices that need updating */
  int iCur;              /* VDBE Cursor number of pTab */
  sqlite3 *db;           /* The database structure */
  int *aRegIdx = 0;      /* One register assigned to each index to be updated */
  int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
                         ** an expression for the i-th column of the table.
                         ** aXRef[i]==-1 if the i-th column is not changed. */
  int chngRowid;         /* True if the record number is being changed */
  Expr *pRowidExpr = 0;  /* Expression defining the new record number */
  int openAll = 0;       /* True if all indices need to be opened */
  AuthContext sContext;  /* The authorization context */
  NameContext sNC;       /* The name-context to resolve expressions in */
  int iDb;               /* Database containing the table being updated */
  int okOnePass;         /* True for one-pass algorithm without the FIFO */
  int hasFK;             /* True if foreign key processing is required */

#ifndef SQLITE_OMIT_TRIGGER
  int isView;            /* True when updating a view (INSTEAD OF trigger) */
  Trigger *pTrigger;     /* List of triggers on pTab, if required */
  int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
#endif
  int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */

  /* Register Allocations */
  int regRowCount = 0;   /* A count of rows changed */
  int regOldRowid;       /* The old rowid */
  int regNewRowid;       /* The new rowid */
  int regNew;
  int regOld = 0;
  int regRowSet = 0;     /* Rowset of rows to be updated */
  int regRec;            /* Register used for new table record to insert */

  memset(&sContext, 0, sizeof(sContext));
  db = pParse->db;
  if( pParse->nErr || db->mallocFailed ){
    goto update_cleanup;
  }
  assert( pTabList->nSrc==1 );

  /* Locate the table which we want to update.
  */
  pTab = sqlite3SrcListLookup(pParse, pTabList);
  if( pTab==0 ) goto update_cleanup;
  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);

  /* Figure out if we have any triggers and if the table being
  ** updated is a view.
  */
#ifndef SQLITE_OMIT_TRIGGER
  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
  isView = pTab->pSelect!=0;
  assert( pTrigger || tmask==0 );
#else
# define pTrigger 0
# define isView 0
# define tmask 0
#endif
#ifdef SQLITE_OMIT_VIEW
# undef isView
# define isView 0
#endif

  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
    goto update_cleanup;
  }
  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
    goto update_cleanup;
  }
  aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
  if( aXRef==0 ) goto update_cleanup;
  for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;

  /* Allocate a cursors for the main database table and for all indices.
  ** The index cursors might not be used, but if they are used they
  ** need to occur right after the database cursor.  So go ahead and
  ** allocate enough space, just in case.
  */
  pTabList->a[0].iCursor = iCur = pParse->nTab++;
  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
    pParse->nTab++;
  }

  /* Initialize the name-context */
  memset(&sNC, 0, sizeof(sNC));
  sNC.pParse = pParse;
  sNC.pSrcList = pTabList;

  /* Resolve the column names in all the expressions of the
  ** of the UPDATE statement.  Also find the column index
  ** for each column to be updated in the pChanges array.  For each
  ** column to be updated, make sure we have authorization to change
  ** that column.
  */
  chngRowid = 0;
  for(i=0; i<pChanges->nExpr; i++){
    if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
      goto update_cleanup;
    }
    for(j=0; j<pTab->nCol; j++){
      if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
        if( j==pTab->iPKey ){
          chngRowid = 1;
          pRowidExpr = pChanges->a[i].pExpr;
        }
        aXRef[j] = i;
        break;
      }
    }
    if( j>=pTab->nCol ){
      if( sqlite3IsRowid(pChanges->a[i].zName) ){
        chngRowid = 1;
        pRowidExpr = pChanges->a[i].pExpr;
      }else{
        sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
        pParse->checkSchema = 1;
        goto update_cleanup;
      }
    }
#ifndef SQLITE_OMIT_AUTHORIZATION
    {
      int rc;
      rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
                           pTab->aCol[j].zName, db->aDb[iDb].zName);
      if( rc==SQLITE_DENY ){
        goto update_cleanup;
      }else if( rc==SQLITE_IGNORE ){
        aXRef[j] = -1;
      }
    }
#endif
  }

  hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);

  /* Allocate memory for the array aRegIdx[].  There is one entry in the
  ** array for each index associated with table being updated.  Fill in
  ** the value with a register number for indices that are to be used
  ** and with zero for unused indices.
  */
  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
  if( nIdx>0 ){
    aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
    if( aRegIdx==0 ) goto update_cleanup;
  }
  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
    int reg;
    if( chngRowid ){
      reg = ++pParse->nMem;
    }else{
      reg = 0;
      for(i=0; i<pIdx->nColumn; i++){
        if( aXRef[pIdx->aiColumn[i]]>=0 ){
          reg = ++pParse->nMem;
          break;
        }
      }
    }
    aRegIdx[j] = reg;
  }

  /* Begin generating code. */
  v = sqlite3GetVdbe(pParse);
  if( v==0 ) goto update_cleanup;
  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  sqlite3BeginWriteOperation(pParse, 1, iDb);

#ifndef SQLITE_OMIT_VIRTUALTABLE
  /* Virtual tables must be handled separately */
  if( IsVirtual(pTab) ){
    updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
                       pWhere);
    pWhere = 0;
    pTabList = 0;
    goto update_cleanup;
  }
#endif

  /* Allocate required registers. */
  regOldRowid = regNewRowid = ++pParse->nMem;
  if( pTrigger || hasFK ){
    regOld = pParse->nMem + 1;
    pParse->nMem += pTab->nCol;
  }
  if( chngRowid || pTrigger || hasFK ){
    regNewRowid = ++pParse->nMem;
  }
  regNew = pParse->nMem + 1;
  pParse->nMem += pTab->nCol;
  regRec = ++pParse->nMem;

  /* Start the view context. */
  if( isView ){
    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  }

  /* If we are trying to update a view, realize that view into
  ** a ephemeral table.
  */
#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  if( isView ){
    sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
  }
#endif

  /* Resolve the column names in all the expressions in the
  ** WHERE clause.
  */
  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
    goto update_cleanup;
  }

  /* Begin the database scan
  */
  sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
  pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0, WHERE_ONEPASS_DESIRED);
  if( pWInfo==0 ) goto update_cleanup;
  okOnePass = pWInfo->okOnePass;

  /* Remember the rowid of every item to be updated.
  */
  sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
  if( !okOnePass ){
    regRowSet = ++pParse->nMem;
    sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
  }

  /* End the database scan loop.
  */
  sqlite3WhereEnd(pWInfo);

  /* Initialize the count of updated rows
  */
  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
    regRowCount = ++pParse->nMem;
    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  }

  if( !isView ){
    /*
    ** Open every index that needs updating.  Note that if any
    ** index could potentially invoke a REPLACE conflict resolution
    ** action, then we need to open all indices because we might need
    ** to be deleting some records.
    */
    if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
    if( onError==OE_Replace ){
      openAll = 1;
    }else{
      openAll = 0;
      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
        if( pIdx->onError==OE_Replace ){
          openAll = 1;
          break;
        }
      }
    }
    for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
      if( openAll || aRegIdx[i]>0 ){
        KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
        sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
                       (char*)pKey, P4_KEYINFO_HANDOFF);
        assert( pParse->nTab>iCur+i+1 );
      }
    }
  }

  /* Top of the update loop */
  if( okOnePass ){
    int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
    addr = sqlite3VdbeAddOp0(v, OP_Goto);
    sqlite3VdbeJumpHere(v, a1);
  }else{
    addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
  }

  /* Make cursor iCur point to the record that is being updated. If
  ** this record does not exist for some reason (deleted by a trigger,
  ** for example, then jump to the next iteration of the RowSet loop.  */
  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);

  /* If the record number will change, set register regNewRowid to
  ** contain the new value. If the record number is not being modified,
  ** then regNewRowid is the same register as regOldRowid, which is
  ** already populated.  */
  assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
  if( chngRowid ){
    sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
    sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
  }

  /* If there are triggers on this table, populate an array of registers
  ** with the required old.* column data.  */
  if( hasFK || pTrigger ){
    u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
    oldmask |= sqlite3TriggerColmask(pParse,
        pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
    );
    for(i=0; i<pTab->nCol; i++){
      if( aXRef[i]<0 || oldmask==0xffffffff || (oldmask & (1<<i)) ){
        sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
      }else{
        sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
      }
    }
    if( chngRowid==0 ){
      sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
    }
  }

  /* Populate the array of registers beginning at regNew with the new
  ** row data. This array is used to check constaints, create the new
  ** table and index records, and as the values for any new.* references
  ** made by triggers.
  **
  ** If there are one or more BEFORE triggers, then do not populate the
  ** registers associated with columns that are (a) not modified by
  ** this UPDATE statement and (b) not accessed by new.* references. The
  ** values for registers not modified by the UPDATE must be reloaded from
  ** the database after the BEFORE triggers are fired anyway (as the trigger
  ** may have modified them). So not loading those that are not going to
  ** be used eliminates some redundant opcodes.
  */
  newmask = sqlite3TriggerColmask(
      pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
  );
  for(i=0; i<pTab->nCol; i++){
    if( i==pTab->iPKey ){
      sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
    }else{
      j = aXRef[i];
      if( j>=0 ){
        sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
      }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
        /* This branch loads the value of a column that will not be changed
        ** into a register. This is done if there are no BEFORE triggers, or
        ** if there are one or more BEFORE triggers that use this value via
        ** a new.* reference in a trigger program.
        */
        testcase( i==31 );
        testcase( i==32 );
        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
        sqlite3ColumnDefault(v, pTab, i, regNew+i);
      }
    }
  }

  /* Fire any BEFORE UPDATE triggers. This happens before constraints are
  ** verified. One could argue that this is wrong.
  */
  if( tmask&TRIGGER_BEFORE ){
    sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
    sqlite3TableAffinityStr(v, pTab);
    sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
        TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);

    /* The row-trigger may have deleted the row being updated. In this
    ** case, jump to the next row. No updates or AFTER triggers are
    ** required. This behaviour - what happens when the row being updated
    ** is deleted or renamed by a BEFORE trigger - is left undefined in the
    ** documentation.
    */
    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);

    /* If it did not delete it, the row-trigger may still have modified
    ** some of the columns of the row being updated. Load the values for
    ** all columns not modified by the update statement into their
    ** registers in case this has happened.
    */
    for(i=0; i<pTab->nCol; i++){
      if( aXRef[i]<0 && i!=pTab->iPKey ){
        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
        sqlite3ColumnDefault(v, pTab, i, regNew+i);
      }
    }
  }

  if( !isView ){
    int j1;                       /* Address of jump instruction */

    /* Do constraint checks. */
    sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
        aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);

    /* Do FK constraint checks. */
    if( hasFK ){
      sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
    }

    /* Delete the index entries associated with the current record.  */
    j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
    sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);

    /* If changing the record number, delete the old record.  */
    if( hasFK || chngRowid ){
      sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
    }
    sqlite3VdbeJumpHere(v, j1);

    if( hasFK ){
      sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
    }

    /* Insert the new index entries and the new record. */
    sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);

    /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
    ** handle rows (possibly in other tables) that refer via a foreign key
    ** to the row just updated. */
    if( hasFK ){
      sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
    }
  }

  /* Increment the row counter
  */
  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  }

  sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
      TRIGGER_AFTER, pTab, regOldRowid, onError, addr);

  /* Repeat the above with the next record to be updated, until
  ** all record selected by the WHERE clause have been updated.
  */
  sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
  sqlite3VdbeJumpHere(v, addr);

  /* Close all tables */
  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
    if( openAll || aRegIdx[i]>0 ){
      sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
    }
  }
  sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);

  /* Update the sqlite_sequence table by storing the content of the
  ** maximum rowid counter values recorded while inserting into
  ** autoincrement tables.
  */
  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
    sqlite3AutoincrementEnd(pParse);
  }

  /*
  ** Return the number of rows that were changed. If this routine is
  ** generating code because of a call to sqlite3NestedParse(), do not
  ** invoke the callback function.
  */
  if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
    sqlite3VdbeSetNumCols(v, 1);
    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
  }

update_cleanup:
  sqlite3AuthContextPop(&sContext);
  sqlite3DbFree(db, aRegIdx);
  sqlite3DbFree(db, aXRef);
  sqlite3SrcListDelete(db, pTabList);
  sqlite3ExprListDelete(db, pChanges);
  sqlite3ExprDelete(db, pWhere);
  return;
}
/* Make sure "isView" and other macros defined above are undefined. Otherwise
** thely may interfere with compilation of other functions in this file
** (or in another file, if this file becomes part of the amalgamation).  */
#ifdef isView
 #undef isView
#endif
#ifdef pTrigger
 #undef pTrigger
#endif

#ifndef SQLITE_OMIT_VIRTUALTABLE
/*
** Generate code for an UPDATE of a virtual table.
**
** The strategy is that we create an ephemerial table that contains
** for each row to be changed:
**
**   (A)  The original rowid of that row.
**   (B)  The revised rowid for the row. (note1)
**   (C)  The content of every column in the row.
**
** Then we loop over this ephemeral table and for each row in
** the ephermeral table call VUpdate.
**
** When finished, drop the ephemeral table.
**
** (note1) Actually, if we know in advance that (A) is always the same
** as (B) we only store (A), then duplicate (A) when pulling
** it out of the ephemeral table before calling VUpdate.
*/
static void updateVirtualTable(
  Parse *pParse,       /* The parsing context */
  SrcList *pSrc,       /* The virtual table to be modified */
  Table *pTab,         /* The virtual table */
  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
  Expr *pRowid,        /* Expression used to recompute the rowid */
  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
  Expr *pWhere         /* WHERE clause of the UPDATE statement */
){
  Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
  ExprList *pEList = 0;     /* The result set of the SELECT statement */
  Select *pSelect = 0;      /* The SELECT statement */
  Expr *pExpr;              /* Temporary expression */
  int ephemTab;             /* Table holding the result of the SELECT */
  int i;                    /* Loop counter */
  int addr;                 /* Address of top of loop */
  int iReg;                 /* First register in set passed to OP_VUpdate */
  sqlite3 *db = pParse->db; /* Database connection */
  const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
  SelectDest dest;

  /* Construct the SELECT statement that will find the new values for
  ** all updated rows.
  */
  pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
  if( pRowid ){
    pEList = sqlite3ExprListAppend(pParse, pEList,
                                   sqlite3ExprDup(db, pRowid, 0));
  }
  assert( pTab->iPKey<0 );
  for(i=0; i<pTab->nCol; i++){
    if( aXRef[i]>=0 ){
      pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
    }else{
      pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
    }
    pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
  }
  pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);

  /* Create the ephemeral table into which the update results will
  ** be stored.
  */
  assert( v );
  ephemTab = pParse->nTab++;
  sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));

  /* fill the ephemeral table
  */
  sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
  sqlite3Select(pParse, pSelect, &dest);

  /* Generate code to scan the ephemeral table and call VUpdate. */
  iReg = ++pParse->nMem;
  pParse->nMem += pTab->nCol+1;
  addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
  sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
  sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
  for(i=0; i<pTab->nCol; i++){
    sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
  }
  sqlite3VtabMakeWritable(pParse, pTab);
  sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
  sqlite3MayAbort(pParse);
  sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
  sqlite3VdbeJumpHere(v, addr);
  sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);

  /* Cleanup */
  sqlite3SelectDelete(db, pSelect);
}
#endif /* SQLITE_OMIT_VIRTUALTABLE */


text:
struct URLProtocol;
extern URLProtocol kFFmpegFileProtocol;

#endif  // MEDIA_TOOLS_MEDIA_BENCH_FILE_PROTOCOL_H_


text:
package logbook.gui.background;

import java.util.concurrent.TimeUnit;

import logbook.data.context.GlobalContext;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.List;

/**
 * 非同期にコンソールを更新します
 *
 */
public final class AsyncExecApplicationMainConsole extends Thread {
    private static final Logger LOG = LogManager.getLogger(AsyncExecApplicationMainConsole.class);
    private static final int CYCLE = 500;
    private static final int MAX_LOG_LINES = 200;

    private final List console;

    /**
     * 非同期にコンソールを更新します
     *
     * @param display
     * @param console
     */
    public AsyncExecApplicationMainConsole(List console) {
        this.console = console;
        this.setName("logbook_async_exec_application_main_console");
    }

    /**
     * 現在のメイン画面を更新します
     */
    @Override
    public void run() {
        try {
            while (true) {
                // ログメッセージを取り出す
                String message;
                while ((message = GlobalContext.getConsoleMessage()) != null) {
                    Display.getDefault().syncExec(new UpdateConsoleTask(this.console, message));
                }
                TimeUnit.MILLISECONDS.sleep(CYCLE);
            }
        } catch (Exception e) {
            LOG.fatal("Thread is aborted", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 非同期にコンソールを更新します
     */
    private static final class UpdateConsoleTask implements Runnable {

        private final List console;
        private final String message;

        /**
         * 非同期にコンソールを更新します
         */
        public UpdateConsoleTask(List console, String message) {
            this.console = console;
            this.message = message;
        }

        @Override
        public void run() {
            int size = this.console.getItemCount();
            if (size >= MAX_LOG_LINES) {
                this.console.remove(0);
            }
            this.console.add(this.message);
            this.console.setSelection(this.console.getItemCount() - 1);
        }
    }
}


text:
import json
import os
from celery.schedules import crontab

from eventkit_cloud.celery import app
from eventkit_cloud.settings.base import is_true
from eventkit_cloud.settings.contrib import *  # NOQA

# Celery config
CELERY_TRACK_STARTED = True

"""
 IMPORTANT

 Don't propagate exceptions in the celery chord header to the finalize task.
 If exceptions are thrown in the chord header then allow the
 finalize task to collect the results and update the overall run state.

"""
# CELERY_CHORD_PROPAGATES = False

CELERYD_PREFETCH_MULTIPLIER = 1
CELERYBEAT_SCHEDULER = "django_celery_beat.schedulers:DatabaseScheduler"
CELERY_RESULT_BACKEND = os.getenv("CELERY_RESULT_BACKEND", "rpc://")

# Pickle used to be the default, and accepting pickled content is a security concern.  Using the new default json,
# causes a circular reference error, that will need to be resolved.
CELERY_TASK_SERIALIZER = "json"
CELERY_ACCEPT_CONTENT = ["json"]
# configure periodic task

BEAT_SCHEDULE = {
    "expire-runs": {"task": "Expire Runs", "schedule": crontab(minute="0", hour="0")},
    "provider-statuses": {
        "task": "Check Provider Availability",
        "schedule": crontab(minute="*/{}".format(os.getenv("PROVIDER_CHECK_INTERVAL", "30"))),
    },
    "clean-up-queues": {"task": "Clean Up Queues", "schedule": crontab(minute="0", hour="0")},
    "clear-tile-cache": {"task": "Clear Tile Cache", "schedule": crontab(minute="0", day_of_month="*/14")},
    "clear-user-sessions": {"task": "Clear User Sessions", "schedule": crontab(minute="0", day_of_month="*/2")},
    "update-statistics-cache": {
        "task": "Update Statistics Caches",
        "schedule": crontab(minute="0", day_of_month="*/4"),
    },
}

BEAT_SCHEDULE.update(
    {
        "scale-celery": {
            "task": "Scale Celery",
            "schedule": 60.0,
            "kwargs": {"max_tasks_memory": int(os.getenv("CELERY_MAX_TASKS_MEMORY", 20000))},
            "options": {"priority": 90, "queue": "scale", "routing_key": "scale"},
        },
    }
)

CELERY_SCALE_BY_RUN = is_true(os.getenv("CELERY_SCALE_BY_RUN", False))
CELERY_GROUP_NAME = os.getenv("CELERY_GROUP_NAME", None)

app.conf.beat_schedule = BEAT_SCHEDULE

CELERYD_USER = CELERYD_GROUP = "eventkit"
if os.getenv("VCAP_SERVICES"):
    CELERYD_USER = CELERYD_GROUP = "vcap"
CELERYD_USER = os.getenv("CELERYD_USER", CELERYD_USER)
CELERYD_GROUP = os.getenv("CELERYD_GROUP", CELERYD_GROUP)

BROKER_URL = None
if os.getenv("VCAP_SERVICES"):
    for service, listings in json.loads(os.getenv("VCAP_SERVICES")).items():
        try:
            if "rabbitmq" in service:
                BROKER_URL = listings[0]["credentials"]["protocols"]["amqp"]["uri"]
            if "cloudamqp" in service:
                BROKER_URL = listings[0]["credentials"]["uri"]
        except KeyError:
            continue
        if BROKER_URL:
            break
if not BROKER_URL:
    BROKER_URL = os.environ.get("BROKER_URL", "amqp://guest:guest@localhost:5672//")

BROKER_API_URL = None
if os.getenv("VCAP_SERVICES"):
    for service, listings in json.loads(os.getenv("VCAP_SERVICES")).items():
        try:
            if "rabbitmq" in service:
                BROKER_API_URL = listings[0]["credentials"]["http_api_uri"]
            if "cloudamqp" in service:
                BROKER_API_URL = listings[0]["credentials"]["http_api_uri"]
        except KeyError:
            continue
        if BROKER_API_URL:
            break
if not BROKER_API_URL:
    BROKER_API_URL = os.environ.get("BROKER_API_URL", "http://guest:guest@localhost:15672/api/")

MAX_TASK_ATTEMPTS = int(os.getenv("MAX_TASK_ATTEMPTS", 3))

app.conf.task_soft_time_limit = int(os.getenv("TASK_TIMEOUT", 0)) or None


text:
@interface BWUnanchoredButton : NSButton
{
	NSPoint topAndLeftInset;
}

@end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class org.hsqldb.util.SqlTool.SqlToolException (HSQLDB 1.8.0.10 API)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../hsqldbstylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.hsqldb.util.SqlTool.SqlToolException

Packages that use SqlTool.SqlToolException

org.hsqldb.util

Uses of SqlTool.SqlToolException in org.hsqldb.util

Methods in org.hsqldb.util that throw SqlTool.SqlToolException

static void
SqlTool.objectMain(java.lang.String[] arg)

          Connect to a JDBC Database and execute the commands given on
 stdin or in SQL file(s).

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2001 - 2005 HSQL Development Group. All Rights Reserved.


text:
module Canson
  # responsible to return the block
  class Responder
    attr_reader :method, :response_handler
    attr_writer :base

    def initialize(method = nil, &block)
      @method = method
      @response_handler = block
    end

    def call
      @response_handler
    end
  end
end


text:
///    @file    TypeDescription.h
///    @author  Martin Cole
///    @date    Mon May 14 10:16:28 2001

#if ! defined(Disclosure_TypeDescription_h)
#define Disclosure_TypeDescription_h

#include <vector>
#include <string>
#include <complex>

#include <Core/Utils/Legacy/share.h>

namespace SCIRun {

struct CompileInfo;

class SCISHARE TypeDescription {
public:
  enum category_e {
    DATA_E,
    BASIS_E,
    MESH_E,
    CONTAINER_E,
    FIELD_E,
    OTHER_E
  };

  typedef std::vector<const TypeDescription*> td_vec;

  TypeDescription(const std::string& name,
		  const std::string& path,
		  const std::string& namesp,
		  category_e c = OTHER_E);
  TypeDescription(const std::string& name,
		  td_vec *sub, // this takes ownership of the memory.
		  const std::string& path,
		  const std::string& namesp,
		  category_e c = OTHER_E);
  ~TypeDescription();

  td_vec* get_sub_type() const {
    return subtype_;
  }
  /// The arguments determine how the templated types are separated.
  /// default is "<" and "> "
  std::string get_name(const std::string & type_sep_start = "<",
		  const std::string & type_sep_end = "> ") const;
  std::string get_similar_name(const std::string &substitute,
			  const int pos,
			  const std::string & type_sep_start = "<",
			  const std::string & type_sep_end = "> ") const;

  std::string get_filename() const;

  std::string get_h_file_path() const { return h_file_path_; }
  std::string get_namespace() const { return namespace_; }

  struct Register {
    explicit Register(const TypeDescription*);
    ~Register();
  };

  /// convert a string that ends in .cc to end in .h
  static std::string cc_to_h(const std::string &dot_cc);
  static std::string strip_absolute_path(const std::string &path);
  static const TypeDescription* lookup_type(const std::string&);

private:
  td_vec                     *subtype_;
  std::string                name_;
  std::string                h_file_path_;
  std::string                namespace_;
  category_e                 category_;
  // Hide these methods
  TypeDescription(const TypeDescription&);
  TypeDescription& operator=(const TypeDescription&);

  void register_type();
};

SCISHARE const TypeDescription* get_type_description(double*);
SCISHARE const TypeDescription* get_type_description(std::complex<double>*);
SCISHARE const TypeDescription* get_type_description(float*);
SCISHARE const TypeDescription* get_type_description(short*);
SCISHARE const TypeDescription* get_type_description(unsigned short*);
SCISHARE const TypeDescription* get_type_description(int*);
SCISHARE const TypeDescription* get_type_description(unsigned int*);
SCISHARE const TypeDescription* get_type_description(long*);
SCISHARE const TypeDescription* get_type_description(unsigned long*);
SCISHARE const TypeDescription* get_type_description(long long*);
SCISHARE const TypeDescription* get_type_description(unsigned long long*);
SCISHARE const TypeDescription* get_type_description(char*);
SCISHARE const TypeDescription* get_type_description(unsigned char*);
SCISHARE const TypeDescription* get_type_description(bool*);
SCISHARE const TypeDescription* get_type_description(std::string*);

template <class T>
const TypeDescription* get_type_description(std::vector<T>*)
{
  static TypeDescription* td = nullptr;
  if(!td){
    const TypeDescription *sub = get_type_description(static_cast<T*>(nullptr));
    TypeDescription::td_vec *subs = new TypeDescription::td_vec(1);
    (*subs)[0] = sub;
    td = new TypeDescription("vector", subs, "std::vector", "std",
				TypeDescription::CONTAINER_E);
  }
  return td;
}

template <class T1, class T2>
const TypeDescription* get_type_description (std::pair<T1,T2> *)
{
  static TypeDescription* td = nullptr;
  if(!td){
    const TypeDescription *sub1 = get_type_description(static_cast<T1*>(nullptr));
    const TypeDescription *sub2 = get_type_description(static_cast<T2*>(nullptr));
    TypeDescription::td_vec *subs = new TypeDescription::td_vec(2);
    (*subs)[0] = sub1;
    (*subs)[1] = sub2;
    td = new TypeDescription("pair", subs, "std::utility", "std",
				TypeDescription::CONTAINER_E);
  }
  return td;

}

} // End namespace SCIRun

#endif //Disclosure_TypeDescription_h


text:
package com.github.lunatrius.schematica.client.gui.control;

import com.github.lunatrius.schematica.client.gui.GuiHelper;
import com.github.lunatrius.schematica.client.util.BlockList;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiSlot;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.item.ItemStack;

class GuiSchematicMaterialsSlot extends GuiSlot {
    private final Minecraft minecraft = Minecraft.getMinecraft();

    private final GuiSchematicMaterials guiSchematicMaterials;

    protected int selectedIndex = -1;

    public GuiSchematicMaterialsSlot(GuiSchematicMaterials par1) {
        super(Minecraft.getMinecraft(), par1.width, par1.height, 16, par1.height - 34, 24);
        this.guiSchematicMaterials = par1;
        this.selectedIndex = -1;
    }

    @Override
    protected int getSize() {
        return this.guiSchematicMaterials.blockList.size();
    }

    @Override
    protected void elementClicked(int index, boolean par2, int par3, int par4) {
        this.selectedIndex = index;
    }

    @Override
    protected boolean isSelected(int index) {
        return index == this.selectedIndex;
    }

    @Override
    protected void drawBackground() {
    }

    @Override
    protected void drawContainerBackground(Tessellator tessellator) {
    }

    @Override
    protected int getScrollBarX() {
        return this.width / 2 + getListWidth() / 2 + 2;
    }

    @Override
    protected void drawSlot(int index, int x, int y, int par4, int mouseX, int mouseY) {
        final BlockList.WrappedItemStack wrappedItemStack = this.guiSchematicMaterials.blockList.get(index);
        final ItemStack itemStack = wrappedItemStack.itemStack;

        final String itemName = wrappedItemStack.getItemStackDisplayName();
        final String amount = wrappedItemStack.getFormattedAmount();

        GuiHelper.drawItemStack(this.minecraft.renderEngine, this.minecraft.fontRendererObj, x, y, itemStack);

        this.guiSchematicMaterials.drawString(this.minecraft.fontRendererObj, itemName, x + 24, y + 6, 0xFFFFFF);
        this.guiSchematicMaterials.drawString(this.minecraft.fontRendererObj, amount, x + 215 - this.minecraft.fontRendererObj.getStringWidth(amount), y + 6, 0xFFFFFF);

        if (mouseX > x && mouseY > y && mouseX <= x + 18 && mouseY <= y + 18) {
            this.guiSchematicMaterials.renderToolTip(itemStack, mouseX, mouseY);
            GlStateManager.disableLighting();
        }
    }
}


text:
package org.apache.datasketches.memory;

import static org.apache.datasketches.memory.internal.Util.negativeCheck;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Objects;

import org.apache.datasketches.memory.internal.BaseWritableBufferImpl;

/**
 * Defines the read-only API for relative positional access to a resource.
 *
 * @author Lee Rhodes
 */
public interface Buffer extends BaseBuffer {

  //BYTE BUFFER
  /**
   * Accesses the given ByteBuffer for read-only operations. The returned Buffer object has the
   * same byte order, as the given ByteBuffer.
   * @param byteBuffer the given ByteBuffer, must not be null.
   * @return a new Buffer for read-only operations on the given ByteBuffer.
   */
  static Buffer wrap(ByteBuffer byteBuffer) {
    return wrap(byteBuffer, byteBuffer.order());
  }

  /**
   * Accesses the given ByteBuffer for read-only operations. The returned Buffer object has
   * the given byte order, ignoring the byte order of the given ByteBuffer.
   * @param byteBuffer the given ByteBuffer, must not be null
   * @param byteOrder the byte order to be used, which may be independent of the byte order
   * state of the given ByteBuffer
   * @return a new Buffer for read-only operations on the given ByteBuffer.
   */
  static Buffer wrap(ByteBuffer byteBuffer, ByteOrder byteOrder) {
    Objects.requireNonNull(byteBuffer, "byteBuffer must not be null");
    Objects.requireNonNull(byteOrder, "byteOrder must not be null");
    negativeCheck(byteBuffer.capacity(), "byteBuffer");
    return BaseWritableBufferImpl.wrapByteBuffer(byteBuffer, true, byteOrder, null);
  }

  //DUPLICATES
  /**
   * Returns a read-only duplicate view of this Buffer with the same but independent values of
   * start, position and end.
   *

   *
Returned object's origin = this object's origin

   *
Returned object's start = this object's start

   *
Returned object's position = this object's position

   *
Returned object's end = this object's end

   *
Returned object's capacity = this object' capacityBytes

   *
Returned object's start, position and end are mutable and
   * independent of this object's start, position and end

   *

   * @return a read-only duplicate view of this Buffer with the same but independent values of
   * start, position and end.
   */
  Buffer duplicate();

  /**
   * Returns a read-only duplicate view of this Buffer with the same but independent values of
   * start, position and end, but with the specified byteOrder.
   *

   *
Returned object's origin = this object's origin

   *
Returned object's start = this object's start

   *
Returned object's position = this object's position

   *
Returned object's end = this object's end

   *
Returned object's capacity = this object' capacityBytes

   *
Returned object's start, position and end are mutable and
   * independent of this object's start, position and end

   *

   * @param byteOrder the given ByteOrder.
   * @return a read-only duplicate view of this Buffer with the same but independent values of
   * start, position and end.
   */
  Buffer duplicate(ByteOrder byteOrder);

  //NO MAP

  //REGIONS
  /**
   * A region is a read-only view of this object.
   *

   *
Returned object's origin = this object's position

   *
Returned object's start = 0

   *
Returned object's position = 0

   *
Returned object's end = this object's (end - position)

   *
Returned object's capacity = this object's (end - position)

   *
Returned object's start, position and end are mutable and
   * independent of this object's start, position and end

   *

   * @return a new Buffer representing the defined region based on the current
   * position and end.
   */
  Buffer region();

  /**
   * A region is a read-only view of this object.
   *

   *
Returned object's origin = this objects' origin + offsetBytes

   *
Returned object's start = 0

   *
Returned object's position = 0

   *
Returned object's end = capacityBytes

   *
Returned object's capacity = capacityBytes

   *
Returned object's start, position and end are mutable and
   * independent of this object's start, position and end

   *
Returned object's byte order = byteOrder

   *

   *
   * @param offsetBytes the starting offset with respect to the origin of this WritableBuffer
   * @param capacityBytes the capacity of the returned region in bytes
   * @param byteOrder the given byte order
   * @return a new Buffer representing the defined writable region
   * based on the current position, end and byteOrder.
   */
  Buffer region(long offsetBytes, long capacityBytes, ByteOrder byteOrder);

  //AS MEMORY
  /**
   * Convert this Buffer to a Memory. The current start, position and end
   * are ignored.
   * @return Memory
   */
  default Memory asMemory() {
    return asMemory(getTypeByteOrder());
  }

  /**
   * Convert this Buffer to a Memory with the given byte order.
   * The current start, position and end are ignored.
   * @param byteOrder the given byte order.
   * @return Memory
   */
  Memory asMemory(ByteOrder byteOrder);

  //NO ACCESS PRIMITIVE HEAP ARRAYS for readOnly

  //PRIMITIVE getX() and getXArray()
  /**
   * Gets the boolean value at the current position.
   * Increments the position by 1.
   * @return the boolean at the current position
   */
  boolean getBoolean();

  /**
   * Gets the boolean value at the given offset.
   * This does not change the position.
   * @param offsetBytes offset bytes relative to this Memory start
   * @return the boolean at the given offset
   */
  boolean getBoolean(long offsetBytes);

  /**
   * Gets the boolean array at the current position.
   * Increments the position by lengthBooleans - dstOffsetBooleans.
   * @param dstArray The preallocated destination array.
   * @param dstOffsetBooleans offset in array units
   * @param lengthBooleans number of array units to transfer
   */
  void getBooleanArray(boolean[] dstArray, int dstOffsetBooleans, int lengthBooleans);

  /**
   * Gets the byte value at the current position.
   * Increments the position by Byte.BYTES.
   * @return the byte at the current position
   */
  byte getByte();

  /**
   * Gets the byte value at the given offset.
   * This does not change the position.
   * @param offsetBytes offset bytes relative to this Memory start
   * @return the byte at the given offset
   */
  byte getByte(long offsetBytes);

  /**
   * Gets the byte array at the current position.
   * Increments the position by Byte.BYTES * (lengthBytes - dstOffsetBytes).
   * @param dstArray The preallocated destination array.
   * @param dstOffsetBytes offset in array units
   * @param lengthBytes number of array units to transfer
   */
  void getByteArray(byte[] dstArray, int dstOffsetBytes, int lengthBytes);

  /**
   * Gets the char value at the current position.
   * Increments the position by Character.BYTES.
   * @return the char at the current position
   */
  char getChar();

  /**
   * Gets the char value at the given offset.
   * This does not change the position.
   * @param offsetBytes offset bytes relative to this Memory start
   * @return the char at the given offset
   */
  char getChar(long offsetBytes);

  /**
   * Gets the char array at the current position.
   * Increments the position by Character.BYTES * (lengthChars - dstOffsetChars).
   * @param dstArray The preallocated destination array.
   * @param dstOffsetChars offset in array units
   * @param lengthChars number of array units to transfer
   */
  void getCharArray(char[] dstArray, int dstOffsetChars, int lengthChars);

  /**
   * Gets the double value at the current position.
   * Increments the position by Double.BYTES.
   * @return the double at the current position
   */
  double getDouble();

  /**
   * Gets the double value at the given offset.
   * This does not change the position.
   * @param offsetBytes offset bytes relative to this Memory start
   * @return the double at the given offset
   */
  double getDouble(long offsetBytes);

  /**
   * Gets the double array at the current position.
   * Increments the position by Double.BYTES * (lengthDoubles - dstOffsetDoubles).
   * @param dstArray The preallocated destination array.
   * @param dstOffsetDoubles offset in array units
   * @param lengthDoubles number of array units to transfer
   */
  void getDoubleArray(double[] dstArray, int dstOffsetDoubles, int lengthDoubles);

  /**
   * Gets the float value at the current position.
   * Increments the position by Float.BYTES.
   * @return the float at the current position
   */
  float getFloat();

  /**
   * Gets the float value at the given offset.
   * This does not change the position.
   * @param offsetBytes offset bytes relative to this Memory start
   * @return the float at the given offset
   */
  float getFloat(long offsetBytes);

  /**
   * Gets the float array at the current position.
   * Increments the position by Float.BYTES * (lengthFloats - dstOffsetFloats).
   * @param dstArray The preallocated destination array.
   * @param dstOffsetFloats offset in array units
   * @param lengthFloats number of array units to transfer
   */
  void getFloatArray(float[] dstArray, int dstOffsetFloats, int lengthFloats);

  /**
   * Gets the int value at the current position.
   * Increments the position by Integer.BYTES.
   * @return the int at the current position
   */
  int getInt();

  /**
   * Gets the int value at the given offset.
   * This does not change the position.
   * @param offsetBytes offset bytes relative to this Memory start
   * @return the int at the given offset
   */
  int getInt(long offsetBytes);

  /**
   * Gets the int array at the current position.
   * Increments the position by Integer.BYTES * (lengthInts - dstOffsetInts).
   * @param dstArray The preallocated destination array.
   * @param dstOffsetInts offset in array units
   * @param lengthInts number of array units to transfer
   */
  void getIntArray(int[] dstArray, int dstOffsetInts, int lengthInts);

  /**
   * Gets the long value at the current position.
   * Increments the position by Long.BYTES.
   * @return the long at the current position
   */
  long getLong();

  /**
   * Gets the long value at the given offset.
   * This does not change the position.
   * @param offsetBytes offset bytes relative to this Memory start
   * @return the long at the given offset
   */
  long getLong(long offsetBytes);

  /**
   * Gets the long array at the current position.
   * Increments the position by Long.BYTES * (lengthLongs - dstOffsetLongs).
   * @param dstArray The preallocated destination array.
   * @param dstOffsetLongs offset in array units
   * @param lengthLongs number of array units to transfer
   */
  void getLongArray(long[] dstArray, int dstOffsetLongs, int lengthLongs);

  /**
   * Gets the short value at the current position.
   * Increments the position by Short.BYTES.
   * @return the short at the current position
   */
  short getShort();

  /**
   * Gets the short value at the given offset.
   * This does not change the position.
   * @param offsetBytes offset bytes relative to this Memory start
   * @return the short at the given offset
   */
  short getShort(long offsetBytes);

  /**
   * Gets the short array at the current position.
   * Increments the position by Short.BYTES * (lengthShorts - dstOffsetShorts).
   * @param dstArray The preallocated destination array.
   * @param dstOffsetShorts offset in array units
   * @param lengthShorts number of array units to transfer
   */
  void getShortArray(short[] dstArray, int dstOffsetShorts, int lengthShorts);

  //SPECIAL PRIMITIVE READ METHODS: compareTo
  /**
   * Compares the bytes of this Buffer to that Buffer.
   * This uses absolute offsets not the start, position and end.
   * Returns (this < that) ? (some negative value) : (this > that) ? (some positive value)
   * : 0;.
   * If all bytes are equal up to the shorter of the two lengths, the shorter length is
   * considered to be less than the other.
   * @param thisOffsetBytes the starting offset for this Buffer
   * @param thisLengthBytes the length of the region to compare from this Buffer
   * @param that the other Buffer to compare with
   * @param thatOffsetBytes the starting offset for that Buffer
   * @param thatLengthBytes the length of the region to compare from that Buffer
   * @return (this < that) ? (some negative value) : (this > that) ? (some positive value)
   * : 0;
   */
  int compareTo(long thisOffsetBytes, long thisLengthBytes, Buffer that,
          long thatOffsetBytes, long thatLengthBytes);

}


text:
<?php

defined('_JEXEC') or die;

jimport('joomla.updater.update');

/**
 * Installer Update Model
 *
 * @package     Joomla.Administrator
 * @subpackage  com_installer
 * @since       1.6
 */
class InstallerModelUpdate extends JModelList
{
	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @see     JController
	 * @since   1.6
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'name',
				'client_id',
				'type',
				'folder',
				'extension_id',
				'update_id',
				'update_site_id',
			);
		}

		parent::__construct($config);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field.
	 * @param   string  $direction  An optional direction (asc|desc).
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState($ordering = null, $direction = null)
	{
		$app = JFactory::getApplication();
		$value = $app->getUserStateFromRequest($this->context . '.filter.search', 'filter_search');
		$this->setState('filter.search', $value);

		$clientId = $this->getUserStateFromRequest($this->context . '.filter.client_id', 'filter_client_id', '');
		$this->setState('filter.client_id', $clientId);

		$categoryId = $this->getUserStateFromRequest($this->context . '.filter.type', 'filter_type', '');
		$this->setState('filter.type', $categoryId);

		$group = $this->getUserStateFromRequest($this->context . '.filter.group', 'filter_group', '');
		$this->setState('filter.group', $group);

		$this->setState('message', $app->getUserState('com_installer.message'));
		$this->setState('extension_message', $app->getUserState('com_installer.extension_message'));
		$app->setUserState('com_installer.message', '');
		$app->setUserState('com_installer.extension_message', '');

		parent::populateState('name', 'asc');
	}

	/**
	 * Method to get the database query
	 *
	 * @return  JDatabaseQuery  The database query
	 *
	 * @since   1.6
	 */
	protected function getListQuery()
	{
		$db = $this->getDbo();
		$query = $db->getQuery(true);
		$type = $this->getState('filter.type');
		$client = $this->getState('filter.client_id');
		$group = $this->getState('filter.group');

		// Grab updates ignoring new installs
		$query->select('*')
			->from('#__updates')
			->where('extension_id != 0')
			->order($this->getState('list.ordering') . ' ' . $this->getState('list.direction'));

		if ($type)
		{
			$query->where('type=' . $db->quote($type));
		}
		if ($client != '')
		{
			$query->where('client_id = ' . intval($client));
		}
		if ($group != '' && in_array($type, array('plugin', 'library', '')))
		{
			$query->where('folder=' . $db->quote($group == '*' ? '' : $group));
		}

		// Filter by extension_id
		if ($eid = $this->getState('filter.extension_id'))
		{
			$query->where($db->quoteName('extension_id') . ' = ' . $db->quote((int) $eid));
		}
		else
		{
			$query->where($db->quoteName('extension_id') . ' != ' . $db->quote(0))
				->where($db->quoteName('extension_id') . ' != ' . $db->quote(700));
		}

		// Filter by search
		$search = $this->getState('filter.search');
		if (!empty($search))
		{
			$query->where('name LIKE ' . $db->quote('%' . $search . '%'));
		}
		return $query;
	}

	/**
	 * Finds updates for an extension.
	 *
	 * @param   int  $eid            Extension identifier to look for
	 * @param   int  $cache_timeout  Cache timout
	 *
	 * @return  boolean Result
	 *
	 * @since   1.6
	 */
	public function findUpdates($eid = 0, $cache_timeout = 0)
	{
		// Purge the updates list
		$this->purge();

		$updater = JUpdater::getInstance();
		$updater->findUpdates($eid, $cache_timeout);
		return true;
	}

	/**
	 * Removes all of the updates from the table.
	 *
	 * @return  boolean result of operation
	 *
	 * @since   1.6
	 */
	public function purge()
	{
		$db = JFactory::getDbo();

		// Note: TRUNCATE is a DDL operation
		// This may or may not mean depending on your database
		$db->setQuery('TRUNCATE TABLE #__updates');
		if ($db->execute())
		{
			// Reset the last update check timestamp
			$query = $db->getQuery(true)
				->update($db->quoteName('#__update_sites'))
				->set($db->quoteName('last_check_timestamp') . ' = ' . $db->quote(0));
			$db->setQuery($query);
			$db->execute();
			$this->_message = JText::_('COM_INSTALLER_PURGED_UPDATES');
			return true;
		}
		else
		{
			$this->_message = JText::_('COM_INSTALLER_FAILED_TO_PURGE_UPDATES');
			return false;
		}
	}

	/**
	 * Enables any disabled rows in #__update_sites table
	 *
	 * @return  boolean result of operation
	 *
	 * @since   1.6
	 */
	public function enableSites()
	{
		$db = JFactory::getDbo();
		$query = $db->getQuery(true)
			->update('#__update_sites')
			->set('enabled = 1')
			->where('enabled = 0');
		$db->setQuery($query);
		if ($db->execute())
		{
			if ($rows = $db->getAffectedRows())
			{
				$this->_message .= JText::plural('COM_INSTALLER_ENABLED_UPDATES', $rows);
			}
			return true;
		}
		else
		{
			$this->_message .= JText::_('COM_INSTALLER_FAILED_TO_ENABLE_UPDATES');
			return false;
		}
	}

	/**
	 * Update function.
	 *
	 * Sets the "result" state with the result of the operation.
	 *
	 * @param   array  $uids  Array[int] List of updates to apply
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	public function update($uids)
	{
		$result = true;
		foreach ($uids as $uid)
		{
			$update = new JUpdate;
			$instance = JTable::getInstance('update');
			$instance->load($uid);
			$update->loadFromXML($instance->detailsurl);

			// Install sets state and enqueues messages
			$res = $this->install($update);

			if ($res)
			{
				$instance->delete($uid);
			}

			$result = $res & $result;
		}

		// Set the final state
		$this->setState('result', $result);
	}

	/**
	 * Handles the actual update installation.
	 *
	 * @param   JUpdate  $update  An update definition
	 *
	 * @return  boolean   Result of install
	 *
	 * @since   1.6
	 */
	private function install($update)
	{
		$app = JFactory::getApplication();
		if (isset($update->get('downloadurl')->_data))
		{
			$url = $update->downloadurl->_data;
		}
		else
		{
			JError::raiseWarning('', JText::_('COM_INSTALLER_INVALID_EXTENSION_UPDATE'));
			return false;
		}

		$p_file = JInstallerHelper::downloadPackage($url);

		// Was the package downloaded?
		if (!$p_file)
		{
			JError::raiseWarning('', JText::sprintf('COM_INSTALLER_PACKAGE_DOWNLOAD_FAILED', $url));
			return false;
		}

		$config		= JFactory::getConfig();
		$tmp_dest	= $config->get('tmp_path');

		// Unpack the downloaded package file
		$package	= JInstallerHelper::unpack($tmp_dest . '/' . $p_file);

		// Get an installer instance
		$installer	= JInstaller::getInstance();
		$update->set('type', $package['type']);

		// Install the package
		if (!$installer->update($package['dir']))
		{
			// There was an error updating the package
			$msg = JText::sprintf('COM_INSTALLER_MSG_UPDATE_ERROR', JText::_('COM_INSTALLER_TYPE_TYPE_' . strtoupper($package['type'])));
			$result = false;
		}
		else
		{
			// Package updated successfully
			$msg = JText::sprintf('COM_INSTALLER_MSG_UPDATE_SUCCESS', JText::_('COM_INSTALLER_TYPE_TYPE_' . strtoupper($package['type'])));
			$result = true;
		}

		// Quick change
		$this->type = $package['type'];

		// Set some model state values
		$app->enqueueMessage($msg);

		// TODO: Reconfigure this code when you have more battery life left
		$this->setState('name', $installer->get('name'));
		$this->setState('result', $result);
		$app->setUserState('com_installer.message', $installer->message);
		$app->setUserState('com_installer.extension_message', $installer->get('extension_message'));

		// Cleanup the install files
		if (!is_file($package['packagefile']))
		{
			$config = JFactory::getConfig();
			$package['packagefile'] = $config->get('tmp_path') . '/' . $package['packagefile'];
		}

		JInstallerHelper::cleanupInstall($package['packagefile'], $package['extractdir']);

		return $result;
	}

	/**
	* Method to get the row form.
	*
	* @param   array    $data      Data for the form.
	* @param   boolean  $loadData  True if the form is to load its own data (default case), false if not.
	*
	* @return  mixed  A JForm object on success, false on failure
	*
	* @since	2.5.2
	*/
	public function getForm($data = array(), $loadData = true)
	{
		// Get the form.
		JForm::addFormPath(JPATH_COMPONENT . '/models/forms');
		JForm::addFieldPath(JPATH_COMPONENT . '/models/fields');
		$form = JForm::getInstance('com_installer.update', 'update', array('load_data' => $loadData));

		// Check for an error.
		if ($form == false)
		{
			$this->setError($form->getMessage());
			return false;
		}
		// Check the session for previously entered form data.
		$data = $this->loadFormData();

		// Bind the form data if present.
		if (!empty($data))
		{
			$form->bind($data);
		}

		return $form;
	}

	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return  mixed  The data for the form.
	 *
	 * @since	2.5.2
	 */
	protected function loadFormData()
	{
		// Check the session for previously entered form data.
		$data = JFactory::getApplication()->getUserState($this->context . '.data', array());
		return $data;
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IBApi.Serialization;

namespace IBApi.Messages.Client
{
    [IbSerializable(71)]
    class StartApiMessage : IClientMessage
    {
        public int Version;
        public int ClientId;
    }
}


text:
/* dbc.java DoubleBufferedComponent
 * Started: 1999.06.03
 *
 * LightweightComponent whose job is to ensure the image buffers
 * imgPrimary and imgBuffer are correctly sized and painted.
 *
 * Usage:
 *   dbc()
 *   * getBufferGraphics() do not allow direct access of imgBuffer
 *   * switchBuffers() set imgBuffer to imgPrimary and vice versa
 *   * repaint() forces java vm to paint component
 * Problems:
 *   - if component hasn't been resized getBufferGraphics return null
 *     + use a function like isDrawable that uses stuff in main to
 *       wait for componentResized to finish
       = removed componentResized and moved stuff to validate
 *   - watch out for the case where width or height is 0
       = added 1 to createImg
 */
import java.awt.*;
import java.awt.image.*;
import javax.swing.JComponent;

public class dbc extends JComponent
{
public int id = -1;

//private Image imgPrimary = null;
//private Image imgBuffer  = null;
private BufferedImage imgPrimary = null;
private BufferedImage imgBuffer  = null;

public dbc()
{ /*DoNothing*/
    //imgBuffer = new BufferedImage(200, 200, BufferedImage.TYPE_INT_RGB);
    //imgPrimary = new BufferedImage(200, 200, BufferedImage.TYPE_INT_RGB);
}

/*
public void invalidate()
  { super.invalidate(); }

public void validate()
{
	super.validate();
	allocateBufferedImages();
}
*/

public void printBuffers()
{
int h = getHeight();
int w = getWidth();
System.out.println(h);
System.out.println(w);

if (imgBuffer != null) {
	System.out.println("imgBuffer Height " + imgBuffer.getHeight());
	System.out.println("imgBuffer Width " + imgBuffer.getWidth());
}

if (imgPrimary != null) {
	System.out.println("imgPrimary Height " + imgPrimary.getHeight());
	System.out.println("imgPrimary Width " + imgPrimary.getWidth());
}
}

public void allocateBufferedImages()
{
	if (!isShowing()) {
		if (imgBuffer != null) {
			imgBuffer.flush();
			imgBuffer = null;
		}
		if (imgPrimary != null) {
			imgPrimary.flush();
			imgPrimary = null;
		}

		return;
	}

	int h = getHeight();
	int w = getWidth();
	if (h > 0 && w > 0) {
		if (imgBuffer != null) {
			int heightImgBuffer = imgBuffer.getHeight();
			int widthImgBuffer = imgBuffer.getWidth();
			if (h != heightImgBuffer || w != widthImgBuffer) {
				imgBuffer.flush();
				imgBuffer = null;
			}
		}

		if (imgBuffer == null) {
			imgBuffer = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);

			Graphics g = imgBuffer.getGraphics();
			g.setColor(new Color(204, 204, 204));
			g.fillRect(0, 0, w, h);
			g.dispose();
		}

		if (imgPrimary != null) {
			int heightImgPrimary = imgPrimary.getHeight();
			int widthImgPrimary = imgPrimary.getWidth();
			if (h != heightImgPrimary || w != widthImgPrimary) {
				imgPrimary.flush();
				imgPrimary = null;
			}
		}

		if (imgPrimary == null) {
			imgPrimary = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);

			Graphics g = imgPrimary.getGraphics();
			g.setColor(new Color(204, 204, 204));
			g.fillRect(0, 0, w, h);
			g.dispose();
		}
	}
}

public void clear()
{
  if (imgBuffer != null)
  {
    Graphics g = imgBuffer.getGraphics();
    assert g != null;

    g.setColor(new Color(204, 204, 204));
    g.fillRect(0, 0, imgBuffer.getWidth(this), imgBuffer.getHeight(this));

    g.dispose();
  }
}

public void paint(BufferedImage img)
{
  if (imgBuffer != null)
  {
    Graphics g = imgBuffer.getGraphics();
    assert g != null;

    //g.setColor(Color.red);//new Color(204, 204, 204));
    //g.fillRect(0, 0, imgBuffer.getWidth(this) - 5, imgBuffer.getHeight(this) - 5);
    //g.clearRect(0, 0, imgBuffer.getWidth(this) - 5, imgBuffer.getHeight(this) - 5);
    g.drawImage(img, 0, 0, this);

    g.dispose();
  }

  img.flush();
}

public void update(Graphics g)
  { paint(g); }

public void paint(Graphics g)
{
  if (imgPrimary != null)
    g.drawImage(imgPrimary, 0, 0, this);
}

public Graphics getBufferGraphics()
  { return imgBuffer != null ? imgBuffer.getGraphics() : null; }

public void switchBuffers()
{
  BufferedImage tmp  = imgBuffer;
  imgBuffer  = imgPrimary;
  imgPrimary = tmp;
}

public static void main(String[] sa)
{
  dbc mydbc = new dbc();

  javax.swing.JFrame f = new javax.swing.JFrame("dbc");
  f.getContentPane().setLayout(new BorderLayout());
  f.setSize(100, 100);
  f.getContentPane().add(mydbc, "Center");
  f.setVisible(true);

  boolean red = false;
  while (true)
  {
    Graphics g = mydbc.getBufferGraphics();
    assert g != null;

    if (red)
    {
      g.setColor(Color.red);
      g.drawLine(100,0,0,100);
    }
    else
    {
      g.setColor(Color.blue);
      g.drawLine(0,0,100,100);
    }
    red = !red;
    g.dispose();

    mydbc.switchBuffers();
    mydbc.repaint();

    try
    {
      Thread.sleep(1000);
    }
    catch (InterruptedException ie)
    {
    }
  }
}
}//class dbc
/*
import com.sun.image.codec.jpeg.*;
public ppm cppm = new ppm();
public void saveppm(String s)
  { saveppm(s, getWidth(), getHeight()); }
public void saveppm(String s, int w, int h)
  { cppm.set(s, w, h); }

protected String sjpeg = null;
public void savejpeg(String s)
{
  ASSERT.NOTNULL(s);
  sjpeg = s;
  savejpeg();
}

protected void savejpeg()
{
  if (imgBuffer == null || sjpeg == null) return;

  try
  {
    //System.out.print(getSize());
    BufferedImage bimg = (BufferedImage)imgBuffer;

    JPEGEncodeParam param = JPEGCodec.getDefaultJPEGEncodeParam(bimg);
    param.setQuality((float)1, true);

    java.io.FileOutputStream fos = new java.io.FileOutputStream(sjpeg);
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos, param);
    encoder.encode(bimg);
    fos.close();

    sjpeg = null;
    return;
  }
  catch (java.io.FileNotFoundException e) { }
  catch (java.io.IOException e) { e.printStackTrace(); }
}
*/


text:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scaleType="fitCenter"
    android:adjustViewBounds="true"
    android:gravity="center_vertical"
    android:textStyle="bold"
    android:padding="8dp"
    android:text="0"
    android:textColor="@color/backgroundBlue"
    android:background="@drawable/badge_back"/>