text:
package org.knowm.xchange.bitkonan;

import org.knowm.xchange.BaseExchange;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.ExchangeSpecification;
import org.knowm.xchange.bitkonan.service.polling.BitKonanMarketDataService;

import si.mazi.rescu.SynchronizedValueFactory;

public class BitKonanExchange extends BaseExchange implements Exchange {

  @Override
  protected void initServices() {
    this.pollingMarketDataService = new BitKonanMarketDataService(this);
  }

  @Override
  public ExchangeSpecification getDefaultExchangeSpecification() {

    ExchangeSpecification exchangeSpecification = new ExchangeSpecification(this.getClass().getCanonicalName());
    exchangeSpecification.setSslUri("https://bitkonan.com");
    exchangeSpecification.setHost("bitkonan.com");
    exchangeSpecification.setPort(80);
    exchangeSpecification.setExchangeName("BitKonan");
    exchangeSpecification.setExchangeDescription("BitKonan is a Bitcoin exchange.");

    return exchangeSpecification;
  }

  @Override
  public SynchronizedValueFactory<Long> getNonceFactory() {
    // No private API implemented. Not needed for this exchange at the moment.
    return null;
  }
}


text:
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>

<link href="doc-style.css" type="text/css" rel="StyleSheet">

		Local Properties

Managed Object Types	Data Object Types	All Properties	All Methods

Data Object - HostVmfsSpec

Property of

VmfsDatastoreCreateSpec

Parameter to

FormatVmfs

Extends

DynamicData

See also

HostScsiDiskPartition

Data Object
                  Description

         This data object type describes the VMware File System (VMFS)
  creation specification. Once created, these properties for the most
  part cannot be changed.  There are a few exceptions.

Properties

	          Name

	          Type

	          Description

blockSizeMb*	xsd:int

         The block size of VMFS in megabytes (MB).  Determines the maximum file
  size.  If this optional property is not set, the maximum
  file size defaults to the maximum file size for the platform.

  In VMFS2, the valid block sizes 1MB, 2MB, 4MB, 8MB, 16MB, 32MB, 64MB,
  128MB, and 256MB.
  In VMFS3, the valid block sizes are 1MB, 2MB, 4MB, and 8MB.
  In VMFS5, the only valid block size is 1MB.

extent	HostScsiDiskPartition

         Head extent of VMFS.  The head extent identifies the VMFS.  However,
  the head extent should not be used to identify the VMFS across host
  reboots.  The actual identifier is specified in "vmhbaI:T:L" format
  which is not guaranteed to be stable across reboots.  Define a volume
  name that is unique to the host and use it to refer to the VMFS.
  Alternatively, the immutable UUID of the VMFS can be used after it
  is created.

majorVersion	xsd:int

         Major version number of VMFS.  This can be changed if the VMFS is
  upgraded, but this is an irreversible change.

volumeName	xsd:string

         Volume name of VMFS.

						Properties inherited from DynamicData

dynamicProperty, dynamicType

*Need not be set

Show WSDL type definition

<textarea cols="20" rows="10" name="wsdl-textarea" wrap="off" readonly="1" id="wsdl-textarea">         <complexType xmlns="http://www.w3.org/2001/XMLSchema" xmlns:vim25="urn:vim25" name="HostVmfsSpec">
            <complexContent>
               <extension base="vim25:DynamicData">
                  <sequence>
                     <element name="extent" type="vim25:HostScsiDiskPartition"/>
                     <element name="blockSizeMb" type="xsd:int" minOccurs="0"/>
                     <element name="majorVersion" type="xsd:int"/>
                     <element name="volumeName" type="xsd:string"/>
                  </sequence>
               </extension>
            </complexContent>
         </complexType></textarea>

Top of page		Local Properties

Managed Object Types	Data Object Types	All Properties	All Methods

redpajama_set_name: RedPajamaGithub


text:
package lithium.community.android.sdk.rest;

/**
 * Created by Lithium Technologies Inc on 8/31/17.
 */

public class LiRequestHeaderConstants {
    public static final String LI_REQUEST_CONTENT_TYPE = "Content-Type";
    public static final String LI_REQUEST_APPLICATION_IDENTIFIER = "Application-Identifier";
    public static final String LI_REQUEST_APPLICATION_VERSION = "Application-Version";
    public static final String LI_REQUEST_VISITOR_ID = "Visitor-Id";
    public static final String LI_REQUEST_VISIT_ORIGIN_TIME = "Visit-Origin-Time";
    public static final String LI_REQUEST_VISIT_LAST_ISSUE_TIME = "Visit-Last-Issue-Time";
    public static final String LI_REQUEST_CLIENT_ID = "client-id";

}


text:
All notable changes to this project will be documented in this file.

## [Unreleased][unreleased]
### Fixed

### Added
- Add base64enc and base64dec functions

### Removed

### Changed

[unreleased]: https://github.com/gliderlabs/glidergun/compare/v0.1.0...HEAD


text:
using System;
using Uniforms.Misc.Droid;

namespace Uniforms.Misc.Droid
{
    public static class ScreenUtils
    {
        public static void Init ()
        {
            var display = Xamarin.Forms.Forms.Context.Resources.DisplayMetrics;
            Misc.ScreenUtils.ScreenSize = new Xamarin.Forms.Size (
                display.WidthPixels / display.Density,
                display.HeightPixels / display.Density
            );
        }
    }
}


text:
package com.intellij.plugins.haxe.ide.actions;

import java.util.Properties;

import consulo.awt.TargetAWT;
import consulo.haxe.module.extension.HaxeModuleExtension;
import javax.annotation.Nonnull;
import com.intellij.icons.AllIcons;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.actions.CreateFileFromTemplateDialog;
import com.intellij.ide.actions.CreateTemplateInPackageAction;
import com.intellij.ide.fileTemplates.FileTemplate;
import com.intellij.ide.fileTemplates.FileTemplateManager;
import com.intellij.ide.fileTemplates.FileTemplateUtil;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.impl.DirectoryIndex;
import com.intellij.plugins.haxe.HaxeBundle;
import com.intellij.plugins.haxe.ide.HaxeFileTemplateUtil;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.util.IncorrectOperationException;
import consulo.ide.IconDescriptor;
import consulo.ui.image.Image;
import consulo.ui.image.ImageEffects;
import icons.HaxeIcons;

/**
 * @author: Fedor.Korotkov
 */
public class CreateClassAction extends CreateTemplateInPackageAction<PsiFile>
{
	public CreateClassAction()
	{
		super(HaxeBundle.message("action.create.new.class"), HaxeBundle.message("action.create.new.class"), ImageEffects.layered(AllIcons.Nodes.Class, HaxeIcons.HaxeLang), true);
	}

	@Override
	protected boolean isAvailable(DataContext dataContext)
	{
		final Module module = dataContext.getData(LangDataKeys.MODULE);
		return super.isAvailable(dataContext) && module != null && ModuleUtilCore.getExtension(module, HaxeModuleExtension.class) != null;
	}

	@Override
	protected PsiElement getNavigationElement(@Nonnull PsiFile createdElement)
	{
		return createdElement.getNavigationElement();
	}

	@Override
	protected boolean checkPackageExists(PsiDirectory directory)
	{
		return DirectoryIndex.getInstance(directory.getProject()).getPackageName(directory.getVirtualFile()) != null;
	}

	@Override
	protected String getActionName(PsiDirectory directory, String newName, String templateName)
	{
		return HaxeBundle.message("progress.creating.class", newName);
	}

	@Override
	protected void buildDialog(Project project, PsiDirectory directory, CreateFileFromTemplateDialog.Builder builder)
	{
		builder.setTitle(IdeBundle.message("action.create.new.class"));
		for(FileTemplate fileTemplate : HaxeFileTemplateUtil.getApplicableTemplates())
		{
			final String templateName = fileTemplate.getName();
			final String shortName = HaxeFileTemplateUtil.getTemplateShortName(templateName);
			final Image icon = HaxeFileTemplateUtil.getTemplateIcon(templateName);
			builder.addKind(shortName, icon, templateName);
		}
	}

	@Override
	protected PsiFile doCreate(@Nonnull PsiDirectory dir, String className, String templateName) throws IncorrectOperationException
	{
		String packageName = DirectoryIndex.getInstance(dir.getProject()).getPackageName(dir.getVirtualFile());
		try
		{
			return createClass(className, packageName, dir, templateName).getContainingFile();
		}
		catch(Exception e)
		{
			throw new IncorrectOperationException(e.getMessage(), e);
		}
	}

	private static PsiElement createClass(String className, String packageName, @Nonnull PsiDirectory directory,
			final String templateName) throws Exception
	{
		final Properties props = new Properties(FileTemplateManager.getInstance(directory.getProject()).getDefaultProperties(directory.getProject()));
		props.setProperty(FileTemplate.ATTRIBUTE_NAME, className);
		props.setProperty(FileTemplate.ATTRIBUTE_PACKAGE_NAME, packageName);

		final FileTemplate template = FileTemplateManager.getInstance().getInternalTemplate(templateName);

		return FileTemplateUtil.createFromTemplate(template, className, props, directory, CreateClassAction.class.getClassLoader());
	}
}


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

  <title>Geolocation API Specification</title>
  <meta content="text/html;charset=utf-8" http-equiv=Content-Type>

<link rel="stylesheet" type="text/css" href="http://www.w3.org/StyleSheets/TR/W3C-REC">

Geolocation API Specification

W3C Recommendation 24 October 2013

This Version:

http://www.w3.org/TR/2013/REC-geolocation-API-20131024/

Latest Published Version:

http://www.w3.org/TR/geolocation-API/

Latest Editor's Draft:

http://dev.w3.org/geo/api/spec-source.html

Previous version:

http://www.w3.org/TR/2012/PR-geolocation-API-20120510/

Editor:

Andrei Popescu, Google, Inc

Please refer to the errata for this document, which may include some normative corrections.

See also  translations.

Copyright © 2008-2013 <acronym title="World Wide Web Consortium">W3C</acronym>® (<acronym title="Massachusetts Institute of Technology">MIT</acronym>, <acronym title="European Research Consortium for Informatics and Mathematics">ERCIM</acronym>, Keio, Beihang), All Rights Reserved. W3C liability, trademark and document use rules apply.

Abstract

This specification defines an API that provides scripted access to
   geographical location information associated with the hosting device.

Status of This Document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

This document has been reviewed by W3C Members, by software developers, and by other W3C groups and interested parties, and is endorsed by the Director as a W3C Recommendation. It is a stable document and may be used as reference material or cited from another document. W3C's role in making the Recommendation is to draw attention to the specification and to promote its widespread deployment. This enhances the functionality and interoperability of the Web.

  By publishing this Recommendation, W3C expects that the functionality
  specified in this Geolocation API Recommendation will not be affected
  by changes to HTML5 or Web IDL as those specifications proceed to
  Recommendation.

This document incorporates minor changes made against the Proposed Recommendation of 10 May 2012.

Comments on the document should be sent to the Working Group's public
mailing list
public-geolocation@w3.org
(subscribe, archives). See W3C mailing list and archive usage
guidelines.

The entrance criteria to enter the Proposed Recommendation stage was
to have (1) a minimum of two independent and interoperable user agents
that implement each feature of the Geolocation API and pass
the User
Agent Tests
and (2) a minimum
of two Websites that pass the
Website Tests .

During the Candidate Recommendation period, the group generated the
Implementation
Report which includes the information on known implementations.

The group has confirmed there were at least five User Agent
implementations, and all the features of the Geolocation API
specification were implemented by two or more User Agents.

Also there were at least two Websites that pass the Website Tests.

See the Implementation Report for the details of the results.

This document has been produced by
the W3C Geolocation
Working Group, following the procedures set out for the
W3C Process,
with the intention of advancing it along the W3C Recommendation
track.

This document was produced by a group operating under the
5
February 2004 W3C Patent Policy. W3C maintains a public list of any
patent disclosures made in connection with the deliverables of
the group; that page also includes instructions for disclosing a
patent. An individual who has actual knowledge of a patent which
the individual believes contains
Essential Claim(s) must disclose the information in accordance
with
section 6 of the W3C Patent Policy.

Table of Contents

1 Conformance
    requirements

2 Introduction

3 Scope

4 Security and privacy
    considerations

4.1 Privacy
      considerations for implementers of the Geolocation API

4.2
      Privacy considerations for recipients of location
      information

4.3
      Additional implementation considerations

5 API
    Description

5.1
      Geolocation interface

5.2
      PositionOptions interface

5.3 Position
      interface

5.4
      Coordinates interface

5.5
      PositionError interface

6 Use-Cases and
    Requirements

6.1
      Use-Cases

6.2
      Requirements

Acknowledgments

References

1 Conformance requirements

All diagrams, examples, and notes in this specification are
   non-normative, as are all sections explicitly marked non-normative.
   Everything else in this specification is normative.

The key words "MUST", "MUST NOT", "REQUIRED",
   "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in the
   normative parts of this document are to be interpreted as described in
   RFC2119. For readability, these words do not appear in all uppercase
   letters in this specification. [RFC2119]

Requirements phrased in the imperative as part of algorithms (such as
   "strip any leading space characters" or "return false and abort these
   steps") are to be interpreted with the meaning of the key word ("must",
   "should", "may", etc) used in introducing the algorithm.

Conformance requirements phrased as algorithms or specific steps may be
   implemented in any manner, so long as the end result is equivalent. (In
   particular, the algorithms defined in this specification are intended to
   be easy to follow, and not intended to be performant.)

User agents may impose implementation-specific
   limits on otherwise unconstrained inputs, e.g. to prevent denial of
   service attacks, to guard against running out of memory, or to work around
   platform-specific limitations.

Implementations that use ECMAScript to implement the APIs defined in
    this specification must implement them in a manner consistent with the
    ECMAScript Bindings defined in the Web IDL specification, as this
    specification uses that specification's terminology. [WEBIDL]

2 Introduction

This section is non-normative.

The Geolocation API defines a high-level interface to location
   information associated only with the device hosting the implementation,
   such as latitude and longitude. The API itself is agnostic of the
   underlying location information sources. Common sources of location
   information include Global Positioning System (GPS) and location inferred
   from network signals such as IP address, RFID, WiFi and Bluetooth MAC
   addresses, and GSM/CDMA cell IDs, as well as user input. No guarantee is
   given that the API returns the device's actual location.

The API is designed to enable both "one-shot" position requests and
   repeated position updates, as well as the ability to explicitly query the
   cached positions. Location information is represented by latitude and
   longitude coordinates. The Geolocation API in this specification builds
   upon earlier work in the industry, including [AZALOC], [GEARSLOC],
   and [LOCATIONAWARE].

The following code extracts illustrate how to obtain basic location
   information:

 Example of a "one-shot" position request.

    function showMap(position) {
      // Show a map centered at (position.coords.latitude, position.coords.longitude).
    }

    // One-shot position request.
    navigator.geolocation.getCurrentPosition(showMap);

Example of requesting repeated position updates.

    function scrollMap(position) {
      // Scrolls the map so that it is centered at (position.coords.latitude, position.coords.longitude).
    }

    // Request repeated updates.
    var watchId = navigator.geolocation.watchPosition(scrollMap);

    function buttonClickHandler() {
      // Cancel the updates when the user clicks a button.
      navigator.geolocation.clearWatch(watchId);
    }

Example of requesting repeated position updates and handling errors.

    function scrollMap(position) {
      // Scrolls the map so that it is centered at (position.coords.latitude, position.coords.longitude).
    }

    function handleError(error) {
      // Update a div element with error.message.
    }

    // Request repeated updates.
    var watchId = navigator.geolocation.watchPosition(scrollMap, handleError);

    function buttonClickHandler() {
      // Cancel the updates when the user clicks a button.
      navigator.geolocation.clearWatch(watchId);
    }

Example of requesting a potentially cached position.

    // Request a position. We accept positions whose age is not
    // greater than 10 minutes. If the user agent does not have a
    // fresh enough cached position object, it will automatically
    // acquire a new one.
    navigator.geolocation.getCurrentPosition(successCallback,
                                             errorCallback,
                                             {maximumAge:600000});

    function successCallback(position) {
      // By using the 'maximumAge' option above, the position
      // object is guaranteed to be at most 10 minutes old.
    }

    function errorCallback(error) {
      // Update a div element with error.message.
    }

Forcing the user agent to return a fresh cached position.

    // Request a position. We only accept cached positions whose age is not
    // greater than 10 minutes. If the user agent does not have a fresh
    // enough cached position object, it will immediately invoke the error
    // callback.
    navigator.geolocation.getCurrentPosition(successCallback,
                                             errorCallback,
                                             {maximumAge:600000, timeout:0});

    function successCallback(position) {
      // By using the 'maximumAge' option above, the position
      // object is guaranteed to be at most 10 minutes old.
      // By using a 'timeout' of 0 milliseconds, if there is
      // no suitable cached position available, the user agent
      // will asynchronously invoke the error callback with code
      // TIMEOUT and will not initiate a new position
      // acquisition process.
    }

    function errorCallback(error) {
      switch(error.code) {
        case error.TIMEOUT:
          // Quick fallback when no suitable cached position exists.
          doFallback();
          // Acquire a new position object.
          navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
          break;
        case ... // treat the other error cases.
      };
    }

    function doFallback() {
      // No fresh enough cached position available.
      // Fallback to a default position.
    }

Forcing the user agent to return any available cached position.

    // Request a position. We only accept cached positions, no matter what
    // their age is. If the user agent does not have a cached position at
    // all, it will immediately invoke the error callback.
    navigator.geolocation.getCurrentPosition(successCallback,
                                             errorCallback,
                                             {maximumAge:Infinity, timeout:0});

    function successCallback(position) {
      // By setting the 'maximumAge' to Infinity, the position
      // object is guaranteed to be a cached one.
      // By using a 'timeout' of 0 milliseconds, if there is
      // no cached position available at all, the user agent
      // will immediately invoke the error callback with code
      // TIMEOUT and will not initiate a new position
      // acquisition process.
      if (position.timestamp < freshness_threshold &&
          position.coords.accuracy < accuracy_threshold) {
        // The position is relatively fresh and accurate.
      } else {
        // The position is quite old and/or inaccurate.
      }
    }

    function errorCallback(error) {
      switch(error.code) {
        case error.TIMEOUT:
          // Quick fallback when no cached position exists at all.
          doFallback();
          // Acquire a new position object.
          navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
          break;
        case ... // treat the other error cases.
      };
    }

    function doFallback() {
      // No cached position available at all.
      // Fallback to a default position.
    }

3 Scope

This section is non-normative.

This specification is limited to providing a scripting API for
   retrieving geographic position information associated with a hosting
   device. The geographic position information is provided in terms of World
   Geodetic System coordinates [WGS84].

The scope of this specification does not include providing a markup
   language of any kind.

The scope of this specification does not include defining new URI
   schemes for building URIs that identify geographic locations.

4 Security and privacy
   considerations

The API defined in this specification is used to retrieve the
   geographic location of a hosting device. In almost all cases, this
   information also discloses the location of the user of the device, thereby
   potentially compromising the user's privacy. A conforming implementation
   of this specification must provide a mechanism that protects the user's
   privacy and this mechanism should ensure that no location information is
   made available through this API without the user's express permission.

4.1 Privacy
   considerations for implementers of the Geolocation API

User agents must not send location information to Web sites without the
   express permission of the user. User agents must acquire permission
   through a user interface, unless they have prearranged trust relationships
   with users, as described below. The user interface must include the host
   component of the document's URI [URI]. Those
   permissions that are acquired through the user interface and that are
   preserved beyond the current browsing session (i.e. beyond the time when
   the browsing context [BROWSINGCONTEXT] is
   navigated to another URL) must be revocable and user agents must respect
   revoked permissions.

Some user agents will have prearranged trust relationships that do not
   require such user interfaces. For example, while a Web browser will
   present a user interface when a Web site performs a geolocation request, a
   VOIP telephone may not present any user interface when using location
   information to perform an E911 function.

4.2 Privacy
   considerations for recipients of location information

Recipients must only request location information when necessary.
   Recipients must only use the location information for the task for which
   it was provided to them. Recipients must dispose of location information
   once that task is completed, unless expressly permitted to retain it by
   the user. Recipients must also take measures to protect this information
   against unauthorized access. If location information is stored, users
   should be allowed to update and delete this information.

The recipient of location information must not retransmit the location
   information without the user's express permission. Care should be taken
   when retransmitting and use of encryption is encouraged.

Recipients must clearly and conspicuously disclose the fact that they
   are collecting location data, the purpose for the collection, how long the
   data is retained, how the data is secured, how the data is shared if it is
   shared, how users may access, update and delete the data, and any other
   choices that users have with respect to the data. This disclosure must
   include an explanation of any exceptions to the guidelines listed above.

4.3
   Additional implementation considerations

This section is non-normative.

Further to the requirements listed in the previous section, implementers
   of the Geolocation API are also advised to consider the following aspects
   that may negatively affect the privacy of their users: in certain cases,
   users may inadvertently grant permission to the user agent to disclose
   their location to Web sites. In other cases, the content hosted at a
   certain URL changes in such a way that the previously granted location
   permissions no longer apply as far as the user is concerned. Or the users
   might simply change their minds.

Predicting or preventing these situations is inherently difficult.
   Mitigation and in-depth defensive measures are an implementation
   responsibility and not prescribed by this specification. However, in
   designing these measures, implementers are advised to enable user
   awareness of location sharing, and to provide easy access to interfaces
   that enable revocation of permissions.

5 API Description

5.1 Geolocation
   interface

The Geolocation object is
   used by scripts to programmatically determine the location information
   associated with the hosting device. The location information is acquired
   by applying a user-agent specific algorithm, creating a Position object, and populating that object
   with appropriate data accordingly.

Objects implementing the Navigator interface (e.g. the
   window.navigator object) must also implement the NavigatorGeolocation interface [NAVIGATOR]. An instance of NavigatorGeolocation would be then obtained by
   using binding-specific casting methods on an instance of
   Navigator.

 [NoInterfaceObject]
 interface <dfn id=navi-geo>NavigatorGeolocation</dfn> {
   readonly attribute Geolocation geolocation;
 };

 Navigator implements NavigatorGeolocation;

 [NoInterfaceObject]
 interface <dfn id=geolocation>Geolocation</dfn> {
   void getCurrentPosition(PositionCallback successCallback,
                           optional PositionErrorCallback errorCallback,
                           optional PositionOptions options);

   long watchPosition(PositionCallback successCallback,
                      optional PositionErrorCallback errorCallback,
                      optional PositionOptions options);

   void clearWatch(long watchId);
 };

 callback <dfn id=position-callback>PositionCallback</dfn> = void (Position position);

 callback <dfn id=error-callback>PositionErrorCallback</dfn> = void (PositionError positionError);

The <dfn id=get-current-position>getCurrentPosition()</dfn>
   method takes one, two or three arguments. When called, it must immediately
   return and then asynchronously attempt to obtain the current
   location of the device. If the attempt is successful,
   the successCallback must be invoked
   (i.e. the handleEvent operation must be called on the
   callback object) with a new Position object,
   reflecting the current location of the device. If the attempt
   fails, the errorCallback must be invoked with a
   new PositionError object, reflecting the reason for the failure.

The implementation of the getCurrentPosition method
  should execute the following set of steps:

Run the following pre-processing steps:

If a PositionOptions parameter was present,
        and its maximumAge attribute was defined to a
        non-negative value, assign this value to an internal
        maximumAge variable. If maximumAge was defined
        to a negative value or was not specified, set the internal maximumAge
        variable to 0.

If a PositionOptions parameter was present,
        and its timeout attribute was defined to a
        non-negative value, assign this value to an internal timeout
        variable. If timeout was defined to a negative value,
        set the internal timeout variable to 0. If timeout
        was not specified, set the internal timeout variable to Infinity.

If a PositionOptions parameter was present,
          and its enableHighAccuracy attribute was
          defined, assign this value to an internal enableHighAccuracy
          variable. Otherwise, set the internal enableHighAccuracy
          variable to false.

 If a cached Position object, whose age is no greater
          than the value of the maximumAge variable, is available,
          invoke the successCallback with the
          cached Position object as a parameter and exit
          this set of steps.

 If the value of the timeout variable is 0, invoke
    the errorCallback (if present) with a
    new PositionError object whose code
    attribute is set to TIMEOUT and exit this set of steps.

Start a location acquisition operation (e.g. by
          invoking a platform-specific API), possibly taking into
          account the value of the enableHighAccuracy variable (see
          the definition
          of enableHighAccuracy
          for details).

Start a timer that will fire after the number of milliseconds
              denoted by the value of the timeout variable. When the
              timer fires, cancel any ongoing location acquisition
              operations associated with this instance of the steps,
              invoke the errorCallback (if present)
              with a new PositionError object
              whose code attribute is set to TIMEOUT, and
              exit this set of steps.

If the operation completes successfully before the timeout
    expires, cancel the pending timer, invoke
    the successCallback with a new Position
    object that reflects the result of the acquisition operation and
    exit this set of steps.

If the operation fails before the timeout expires, cancel the
    pending timer and invoke the errorCallback (if
    present) with a new PositionError object
    whose code is set to POSITION_UNAVAILABLE.

The <dfn id=watch-position>watchPosition()</dfn>
   method takes one, two or three arguments. When called, it must immediately
   return a long value that uniquely identifies a watch
   operation and then asynchronously start the watch
   operation. This operation must first attempt to obtain the current location of the
   device. If the attempt is successful, the successCallback must be invoked
   (i.e. the handleEvent operation must be called on the
   callback object) with a new Position object,
   reflecting the current location of the device. If the attempt
   fails, the errorCallback must be invoked with a
   new PositionError object, reflecting the reason for
   the failure. The watch operation then must continue
   to monitor the position of the device and invoke the appropriate
   callback every time this position changes. The watch operation
   must continue until
   the clearWatch method is
   called with the corresponding identifier.

The implementation of the watch process should execute the
  following set of steps:

Run the following pre-processing steps:

If a PositionOptions parameter was present,
        and its maximumAge attribute was defined to a
        non-negative value, assign this value to an internal
        maximumAge variable. If maximumAge was defined
        to a negative value or was not specified, set the internal maximumAge
        variable to 0.

If a PositionOptions parameter was present,
        and its timeout attribute was defined to a
        non-negative value, assign this value to an internal timeout
        variable. If timeout was defined to a negative value,
        set the internal timeout variable to 0. If timeout
        was not specified, set the internal timeout variable to Infinity.

If a PositionOptions parameter was present,
          and its enableHighAccuracy attribute was
          defined, assign this value to an internal enableHighAccuracy
          variable. Otherwise, set the internal enableHighAccuracy
          variable to false.

 If a cached Position object, whose age is no greater
          than the value of the maximumAge variable, is available,
          invoke the successCallback with the
          cached Position object as a parameter.

Register to receive system events that indicate that the
    position of the device may have changed (e.g. by listening or
    polling for changes in WiFi or cellular signals).

Start a location acquisition operation (e.g. by
          invoking a platform-specific API), possibly taking into
          account the value of the enableHighAccuracy variable (see
          the definition
          of enableHighAccuracy
          for details).

 Run the following acquisition steps:

If the timer is not already running, start a timer that will fire after the number of
        milliseconds denoted by the value of the timeout
        variable. When the timer fires, invoke
        the errorCallback (if present) with a
        new PositionError object whose code
        attribute is set to TIMEOUT and jump to step 6.

If the location acquisition operation successfully yields
        a new position before the timeout expires, perform the
        following two steps:

Cancel the pending timer. Note that the timer must be
            restarted once this algorithm jumps back to the beginning of the
            acquisition steps.

If the new position differs significantly from the
              previous position, invoke
              the successCallback with a
              new Position object that reflects the
              result of the acquisition operation.  This step may be
              subject to callback rate limitation
              (see below).

Else, if the location acquisition operation reports an
          error before the timeout expires, invoke the errorCallback (if present)
          with a new PositionError object
          whose code is set to POSITION_UNAVAILABLE. This
          step may be subject to callback rate limitation
          (see below).

Wait for a system event to be received. When such an event is
    received jump to the acquisition steps above.

In step 5.2.2 of the watch process,
  the successCallback is only invoked when a new position
  is obtained and this position differs significantly from the
  previously reported position. The definition of what constitutes a
  significant difference is left to the implementation. Furthermore,
  in steps 5.2.2 and 5.2.3, implementations may impose limitations on
  the frequency of callbacks so as to avoid inadvertently consuming a
  disproportionate amount of resources.

For both getCurrentPosition
  and watchPosition, the implementation must never invoke
  the successCallback without having first obtained
  permission from the user to share location. Furthermore, the
  implementation should always obtain the user's permission to share location before
  executing any of the getCurrentPosition or watchPosition steps
  described above. If the user grants permission, the
  appropriate callback must be invoked as described above. If the user
  denies permission, the errorCallback (if present)
  must be invoked with code PERMISSION_DENIED, irrespective of any
  other errors encountered in the above steps.
  The time that is spent obtaining the user permission must not be
  included in the period covered by the timeout attribute
  of the PositionOptions
  parameter. The timeout attribute must only apply to the
  location acquisition operation.

The <dfn id=clear-watch>clearWatch()</dfn> method
  takes one argument. When called, it must first check the value of
  the given <dfn id="watchId">watchId</dfn> argument.
  If this value does not correspond to any previously started watch
  process, then the method must return immediately without taking any
  further action. Otherwise, the watch process identified by the
  watchId argument must be immediately stopped and no
  further callbacks must be invoked.

5.2
   PositionOptions interface

The getCurrentPosition() and watchPosition() methods accept PositionOptions objects as their third
   argument.

 In ECMAScript, PositionOptions
   objects are represented using regular native objects with optional
   properties named enableHighAccuracy, timeout
   and maximumAge.

  [NoInterfaceObject]
  interface <dfn id=position-options>PositionOptions</dfn> {
    attribute boolean enableHighAccuracy;
    attribute long timeout;
    attribute long maximumAge;
  };

In ECMAScript, the enableHighAccuracy,
   timeout and maximumAge properties are all optional: when
   creating a PositionOptions object, the developer may specify any of these
   properties.

The <dfn id=high-accuracy>enableHighAccuracy</dfn>
   attribute provides a hint that the application would like to receive the
   best possible results. This may result in slower response times or
   increased power consumption. The user might also deny this capability, or
   the device might not be able to provide more accurate results than if the
   flag wasn't specified. The intended purpose of this attribute is to allow
   applications to inform the implementation that they do not require high
   accuracy geolocation fixes and, therefore, the implementation can avoid
   using geolocation providers that consume a significant amount of power (e.g. GPS).
   This is especially useful for applications running on battery-powered devices,
   such as mobile phones.

If the PositionOptions parameter
  to getCurrentPosition or watchPosition is
  omitted, the default value used for
  the enableHighAccuracy attribute is false. The same
  default value is used in ECMAScript when
  the enableHighAccuracy property is omitted.

The <dfn id=timeout>timeout</dfn> attribute denotes
   the maximum length of time (expressed in milliseconds) that is
   allowed to pass from the call
   to getCurrentPosition()
   or watchPosition() until
   the corresponding
   successCallback is invoked. If the implementation is unable
   to successfully acquire a new Position before the given timeout elapses, and
   no other errors have occurred in this interval, then the corresponding
   errorCallback must be invoked with
   a PositionError object
   whose code attribute is set
   to TIMEOUT. Note that the time that is
   spent obtaining the user permission is not included in the period
   covered by the timeout
   attribute. The timeout attribute only applies to the
   location acquisition operation.

If the PositionOptions parameter
  to getCurrentPosition or watchPosition is
  omitted, the default value used for the timeout
  attribute is Infinity. If a negative value is supplied,
  the timeout value is considered to be 0. The same
  default value is used in ECMAScript when the timeout
  property is omitted.

In case of a getCurrentPosition() call, the
   errorCallback would be invoked at most once.

   In case of
   a watchPosition(),
   the errorCallback could be invoked repeatedly: the
   first timeout is relative to the
   moment watchPosition()
   was called or the moment the user's permission was obtained, if
   that was necessary. Subsequent timeouts are relative to the moment
   when the implementation determines that the position of the hosting
   device has changed and a new
   Position object must be acquired.

The <dfn id=max-age>maximumAge</dfn> attribute indicates
   that the application is willing to accept a cached position whose age is
   no greater than the specified time in milliseconds. If maximumAge is set to 0, the
   implementation must immediately attempt to acquire a new position object.
   Setting the maximumAge to Infinity
   must determine the implementation to return a cached position regardless of
   its age. If an implementation does not have a cached position available
   whose age is no greater than the specified maximumAge, then it must acquire a new position
   object. In case of a watchPosition(), the maximumAge refers to the first position object
   returned by the implementation.

If the PositionOptions parameter
  to getCurrentPosition or watchPosition is
  omitted, the default value used for the maximumAge
  attribute is 0. If a negative value is supplied,
  the maximumAge value is considered to be 0. The same
  default value is used in ECMAScript when the maximumAge
  property is omitted.

5.3 Position interface

The Position interface is the
   container for the geolocation information returned by this API. This
   version of the specification allows one attribute of type Coordinates and a
   timestamp. Future versions of the API
   may allow additional attributes that provide other information about this
   position (e.g. street addresses).

  [NoInterfaceObject]
  interface <dfn id=position>Position</dfn> {
    readonly attribute Coordinates coords;
    readonly attribute DOMTimeStamp timestamp;
  };

The <dfn id=coords>coords</dfn> attribute contains a set of
   geographic coordinates together with their associated accuracy, as well as
   a set of other optional attributes such as altitude and speed.

The <dfn id=timestamp>timestamp</dfn> attribute represents
   the time when the Position object was
   acquired and is represented as a DOMTimeStamp [DOMTIMESTAMP].

5.4 Coordinates
   interface

  [NoInterfaceObject]
  interface <dfn id=coordinates>Coordinates</dfn> {
    readonly attribute double latitude;
    readonly attribute double longitude;
    readonly attribute double? altitude;
    readonly attribute double accuracy;
    readonly attribute double? altitudeAccuracy;
    readonly attribute double? heading;
    readonly attribute double? speed;
  };

The geographic coordinate reference system used by the attributes in
   this interface is the World Geodetic System (2d) [WGS84]. No other reference system is supported.

The <dfn id=lat>latitude</dfn> and <dfn
   id=lon>longitude</dfn> attributes are geographic coordinates
   specified in decimal degrees.

The <dfn id=altitude>altitude</dfn> attribute denotes the
   height of the position, specified in meters above the [WGS84] ellipsoid. If the implementation cannot
   provide altitude information, the value of this attribute must be null.

The <dfn id=accuracy>accuracy</dfn> attribute denotes the
   accuracy level of the latitude and longitude coordinates. It is specified
   in meters and must be supported by all implementations. The value of the accuracy
   attribute must be a non-negative real number.

The <dfn id=altitude-accuracy>altitudeAccuracy</dfn>
   attribute is specified in meters. If the implementation cannot provide
   altitude information, the value of this attribute must be null. Otherwise,
   the value of the altitudeAccuracy attribute must be a non-negative real number.

The accuracy and altitudeAccuracy values returned by
   an implementation should correspond to a 95% confidence level.

The <dfn id=heading>heading</dfn> attribute denotes the
   direction of travel of the hosting device and is specified in degrees,
   where 0° ≤ heading < 360°, counting clockwise relative to the true north.
   If the implementation cannot provide heading information, the value of this
   attribute must be null. If the hosting device is stationary (i.e. the value
   of the speed attribute is 0), then the value of the heading
   attribute must be NaN.

The <dfn id=speed>speed</dfn> attribute denotes the magnitude
   of the horizontal component of the hosting device's current velocity and is
   specified in meters per second.
   If the implementation cannot provide speed information, the value of this
   attribute must be null. Otherwise, the value of the speed attribute must be
   a non-negative real number.

5.5
   PositionError interface

  [NoInterfaceObject]
  interface <dfn id=position-error>PositionError</dfn> {
    const unsigned short PERMISSION_DENIED = 1;
    const unsigned short POSITION_UNAVAILABLE = 2;
    const unsigned short TIMEOUT = 3;
    readonly attribute unsigned short code;
    readonly attribute DOMString message;
  };

The <dfn id=code>code</dfn> attribute must return the
   appropriate code from the following list:

<dfn id="permission_denied_error">PERMISSION_DENIED</dfn>
    (numeric value 1)

The location acquisition process failed because the document
    does not have permission to use the Geolocation API.

<dfn
    id="position_unavailable_error">POSITION_UNAVAILABLE</dfn>
    (numeric value 2)

The position of the device could not be determined. For instance, one or more of the
    location providers used in the location acquisition process reported an
    internal error that caused the process to fail entirely.

<dfn id="timeout_error">TIMEOUT</dfn> (numeric value 3)

The length of time specified by the timeout
    property has elapsed before the implementation could successfully acquire a
    new Position object.

The <dfn id=message>message</dfn> attribute must return an
   error message describing the details of the error encountered. This
   attribute is primarily intended for debugging and developers should not
   use it directly in their application user interface.

6 Use-Cases and Requirements

6.1 Use-Cases

6.1.1 Find points of
   interest in the user's area

Someone visiting a foreign city could access a Web application that
   allows users to search or browse through a database of tourist
   attractions. Using the Geolocation API, the Web application has access to
   the user's approximate position and it is therefore able to rank the
   search results by proximity to the user's location.

6.1.2
   Annotating content with location information

 A group of friends is hiking through the Scottish highlands. Some of
   them write short notes and take pictures at various points throughout the
   journey and store them using a Web application that can work offline on
   their hand-held devices. Whenever they add new content, the application
   automatically tags it with location data from the Geolocation API (which,
   in turn, uses the on-board GPS device). Every time they reach a town or a
   village, and they are again within network coverage, the application
   automatically uploads their notes and pictures to a popular blogging Web
   site, which uses the geolocation data to construct links that point to a
   mapping service. Users who follow the group's trip can click on these
   links to see a satellite view of the area where the notes were written and
   the pictures were taken. Another example is a life blog where a user
   creates content (e.g. images, video, audio) that records her every day
   experiences. This content can be automatically annotated with information
   such as time, geographic position or even the user's emotional state at
   the time of the recording.

6.1.3 Show the
   user's position on a map

A user finds herself in an unfamiliar city area. She wants to check her
   position so she uses her hand-held device to navigate to a Web-based
   mapping application that can pinpoint her exact location on the city map
   using the Geolocation API. She then asks the Web application to provide
   driving directions from her current position to her desired destination.

6.1.4 Turn-by-turn
   route navigation

A mapping application can help the user navigate along a route by
   providing detailed turn-by-turn directions. The application does this by
   registering with the Geolocation API to receive repeated location updates
   of the user's position. These updates are delivered as soon as the
   implementing user agent determines that the position of the user has
   changed, which allows the application to anticipate any changes of
   direction that the user might need to do.

6.1.5 Alerts when
   points of interest are in the user's vicinity

A tour-guide Web application can use the Geolocation API to monitor the
   user's position and trigger visual or audio notifications when interesting
   places are in the vicinity. An online task management system can trigger
   reminders when the user is in the proximity of landmarks that are
   associated with certain tasks.

6.1.6 Up-to-date local
   information

A widget-like Web application that shows the weather or news that are
   relevant to the user's current area can use the Geolocation API to
   register for location updates. If the user's position changes, the widget
   can adapt the content accordingly.

6.1.7
   Location-tagged status updates in social networking applications

A social network application allows its users to automatically tag their
   status updates with location information. It does this by monitoring the
   user's position with the Geolocation API. Each user can control the
   granularity of the location information (e.g. city or neighborhood level)
   that is shared with the other users. Any user can also track his network
   of friends and get real-time updates about their current location.

6.2 Requirements

6.2.1 The Geolocation API
   must provide location data in terms of a pair of latitude and longitude
   coordinates.

6.2.2 The Geolocation API
   must provide information about the accuracy of the retrieved location
   data.

6.2.3 The Geolocation API
   must support "one-shot" position updates.

6.2.4 The Geolocation API
   must allow an application to register to receive updates when the position
   of the hosting device changes.

6.2.5 The Geolocation API
   must allow an application to request a cached position whose age is no
   greater than a specified value.

6.2.6 The Geolocation API must
   provide a way for the application to receive updates about errors that may
   have occurred while obtaining a location fix.

6.2.7 The Geolocation
   API must allow an application to specify a desired accuracy level of the
   location information.

6.2.8 The Geolocation
   API must be agnostic to the underlying sources of location information.

Acknowledgments

Alec Berntson, Alissa Cooper, Steve Block, Greg Bolsinga, Lars Erik Bolstad, Aaron Boodman,
   Dave Burke, Chris Butler, Max Froumentin, Shyam Habarakada, Marcin
   Hanclik, Ian Hickson, Brad Lassey, Angel Machin, Cameron McCormack, Daniel
   Park, Stuart Parmenter, Olli Pettay, Chris Prince, Arun Ranganathan, Aza
   Raskin, Carl Reed, Thomas Roessler, Dirk Segers, Allan Thomson, Martin
   Thomson, Doug Turner, Erik Wilde, Matt Womer, Mohamed Zergaoui

References

[AZALOC]

(Non-normative) Geolocation
    in Firefox and Beyond, Aza Raskin. See
    http://azarask.in/blog/post/geolocation-in-firefox-and-beyond

[BROWSINGCONTEXT]

The
    browsing context in HTML5, Ian Hickson, David Hyatt, Editors.  World Wide Web Consortium.  See
    http://www.w3.org/TR/2013/CR-html5-20130806/browsers.html#windows

[URI]

Uniform Resource Identifiers (URI): Generic Syntax
    .T. Berners-Lee, R. Fielding, L. Masinter, Editors. Internet Engineering Task Force.
    See http://www.ietf.org/rfc/rfc2396.txt

[NAVIGATOR]

Navigator
    interface in HTML5, Ian Hickson, David Hyatt, Editors.  World Wide Web Consortium.  See
	http://www.w3.org/TR/2013/CR-html5-20130806/webappapis.html#navigator

[DOMTIMESTAMP]

The
    DOMTimeStamp Type,
	Arnaud Le Hors, Philippe Le Hégaret, Gavin Nicol, Lauren Wood, Mike Champion, Steve Byrne, Editors. World Wide Web Consortium, 7 April 2004.  See
    http://www.w3.org/TR/DOM-Level-3-Core/core.html#Core-DOMTimeStamp

[GEARSLOC]

(Non-normative) Gears
    Geolocation API. See http://code.google.com/apis/gears/api_geolocation.html [historical]

[LOCATIONAWARE]

(Non-normative) LocationAware.org. See
    http://locationaware.org/  [historical]

[RFC2119]

Key words for use
    in RFCs to Indicate Requirement Levels, Scott Bradner.  Internet Engineering Task Force, March 1997. See
    http://www.ietf.org/rfc/rfc2119.txt

[RFC3066]

Tags for the
    Identification of Languages, Harald Tveit Alvestrand.  Internet Engineering Task Force, January 2001. See
    http://www.ietf.org/rfc/rfc3066.txt

[WEBIDL]

web IDL, Cameron McCormack, Editor.  World Wide Web Consortium, 19 April 2012. See
    http://www.w3.org/TR/2012/CR-WebIDL-20120419/

[WGS84]

National
    Imagery and Mapping Agency Technical Report 8350.2, Third
    Edition.  National Imagery and Mapping Agency, 3 January 2000.  See
    http://earth-info.nga.mil/GandG/publications/tr8350.2/wgs84fin.pdf


text:
package org.data2semantics.mustard.rdfvault;

import java.util.Arrays;
import java.util.HashMap;

import org.data2semantics.mustard.kernels.SparseVector;

/**
 * An implementation of Patricia tries over Strings that implements {@link Vault Vault<String>}.
 * It is both fast and memory efficient, especially for strings that have long
 * prefixes in common.
 *
 * @author  Steven de Rooij
 */
public class StringTree {

	// The root of the tree is always present and always an internal node.
	private InternalNode _root = new InternalNode(null, null, null, null);
	private int  _size = 0; // The number of items in the tree.
	private static final int ITEM_MARKER = 65536; // n.find_child(ITEM_MARKER) returns a dummy child if present.

	/**
	 * Returns the number of unique items stored in the vault.
	 * @return The number of items.
	 */
	public int size() { return _size; }

	public void trash(Object entry) {
		Leaf e = (Leaf)entry;
		e.verify();
		InternalNode n = e._parent; // we need the parent so we can repair its neighborhood later
		e.remove();       	        // unlink the leaf and mark it as invalid
		e.invalidate();
		_size--;

		// see if I am now a node with 0 or 1 children, if so remove me too
		if (n._parent==null) return;                   // never remove the root

		Node ch = n._children;
		if (ch==null) { n.remove(); return; } // no more children? just remove node
		if (ch._siblings!=null) return; // more than one child? Then we're done

		// There is exactly one child. Remove n and join the child with its parent's parent.
		int l_n = n._label.length;
		char [] new_label;
		if (ch._label==null) {
			new_label = n._label;
		} else {
			new_label = Arrays.copyOf(n._label, l_n + ch._label.length);
			System.arraycopy(ch._label, 0, new_label, l_n, ch._label.length);
		}
		n.remove();
		ch._label = new_label;
		ch._parent = n._parent;
		ch._siblings = n._parent._children;
		n._parent._children = ch;
	}

	public Object store(String item) {
		// Find the parent of the leaf for this item. If the parent does not exist yet, create it.
		int len = item.length();
		InternalNode n = _root;
		int depth = 0;
		search: while (depth<len) {
			Node ch = n.find_child(item.charAt(depth));
			if (ch==null) break search; // we know a leaf can be added
			int ext;
			for (ext=1; ext<ch._label.length; ext++) {
				if (depth+ext==len || item.charAt(depth+ext)!=ch._label[ext]) {
					n = ch.split_edge(ext);
					depth += ext;
					break search;
				}
			}
			// we have traversed the edge label and now we've reached ch
			depth += ext;
			if (ch instanceof Leaf) {
				if (depth==len) return ch;
				// the leaf represents a prefix of this item. Insert an internal node here
				n = ch.split_edge(ext);
				break search;
			}
			n = (InternalNode)ch;
		}

		// Add a new leaf to the tree, starting at internal node n.

		char [] new_label;
		if (len==depth) {
			Node ch = n.find_child(ITEM_MARKER);
			if (ch!=null) return ch;
			new_label=null;
		} else {
			new_label = item.substring(depth).toCharArray();
		}

		Leaf res = new Leaf(n, n._children, new_label);
		n._children = res;
		_size++;
		return res;
	}

	public Object search(String item) {
		Node n;
		int depth;
		for (n=_root, depth=0; depth<item.length(); depth+=n._label.length) {
			if (n instanceof Leaf) return null;
			Node ch = ((InternalNode)n).find_child(item.charAt(depth));
			if (ch==null) return null;
			for (int i=1; i<ch._label.length; i++) {
				if (depth+i==item.length() || item.charAt(depth+i)!=ch._label[i]) return null;
			}
			n = ch;
		}
		return n instanceof Leaf ? n : ((InternalNode)n).find_child(ITEM_MARKER);
	}

	public String redeem(Object ticket) {
		if (!(ticket instanceof Leaf)) return null;
		Leaf leaf = (Leaf)ticket;
		leaf.verify();
		StringBuilder sb = new StringBuilder();
		leaf.redeem_rec(sb);
		return sb.toString();
	}

	public String shorten(String uri, int steps) {
		Node n = (Node)search(uri);
		assert n!=null : "Cannot find the uri '"+uri+"' in the tree";
		if (n._label==null) steps++;
		for (int i=0; i<steps; i++) {
			if (n._parent!=null) n = n._parent;
		}
		StringBuilder sb = new StringBuilder();
		n.redeem_rec(sb);
		return sb.toString();
	}

	// once prefixstatistics are requested, no tree operations should be performed except through the statistics object
	public PrefixStatistics getPrefixStatistics(boolean include_internal_nodes) {
		return new PrefixStatistics(include_internal_nodes);
	}

	public class PrefixStatistics {

		private HashMap<InternalNode, Integer> _node2bitix = new HashMap<InternalNode,Integer>();
		private SparseVector _normalization = new SparseVector();
		private boolean _int_nodes;
		private int _bits_used = 0;

		// assign a bit to identify each of its children, and recurse.
		// returns the number of leafs with this node as ancestor.
		private int initialise_rec(InternalNode node) {
			int node_index = _bits_used;
			_node2bitix.put(node, node_index);
			for (Node n = node._children; n!=null; n=n._siblings) {
				if (_int_nodes || (n instanceof Leaf)) _bits_used++; // if !_int_nodes, only count edges to leaves
			}
			int leaves = 0;
			for (Node n = node._children; n!=null; n=n._siblings) {
				int l = 1;
				if (n instanceof InternalNode) l = initialise_rec((InternalNode)n);
				_normalization.setValue(node_index, l);
				leaves += l;
				node_index++;
			}

			return leaves;
		}

		public PrefixStatistics(boolean include_internal_nodes) {
			_int_nodes = include_internal_nodes;
			int tot_leaves = initialise_rec(_root);
			_normalization.setValue(0, tot_leaves);
			_normalization.setLastIndex(_bits_used-1);
		}

		public SparseVector getNormalization() { return _normalization; }

		public SparseVector createSparseVector(String s) {
			SparseVector sv = new SparseVector();
			sv.setLastIndex(_bits_used-1);

			Node n = _root;
			int depth = 0;
			while (n instanceof InternalNode) {
				// invariant: at internal node, depth <= s.length()
				int ix0 = _node2bitix.get(n);
				int c = depth==s.length() ? ITEM_MARKER : s.charAt(depth);
				Node ch = ((InternalNode)n)._children;
				int i,j;
				for (i=0,j=0; ch.label_char()!=c; i++) {
					if (ch instanceof Leaf) j++;
					ch = ch._siblings;
				}
				if (_int_nodes) {
					sv.setValue(ix0+i, 1.0);
				} else {
					if (ch instanceof Leaf) sv.setValue(ix0+j, 1.0); // output leaf index: one bit for each leaf!
				}
				depth += ch._label==null ? 0 : ch._label.length;
				n = ch;
			}

			return sv;
		}

		public double prefixSimilarity(String s1, String s2) {
			Node n = _root;
			int depth = 0;
			while (n instanceof InternalNode) {
				int c1 = depth==s1.length() ? ITEM_MARKER : s1.charAt(depth);
				int c2 = depth==s2.length() ? ITEM_MARKER : s2.charAt(depth);
				if (c1 != c2) break; // paths diverge at this node
				n = ((InternalNode)n)._children;
				while (n.label_char()!=c1) {
					n = n._siblings;
				}
				depth += n._label==null ? 0 : n._label.length;
			}
			// n is the internal node where the paths diverge, or a leaf indicating an exact match
			if (n instanceof Leaf) return 1.0;
			return 1.0 - _normalization.getValue(_node2bitix.get(n)) / _size;
		}

	}

	///////////////////////////////////////// Tree nodes ///////////////////////////////////////////////

	private static abstract class Node {
		protected InternalNode _parent;
		protected Node         _siblings;
		protected char []      _label;

		// Returns the first character of the edge label into this node, or ITEM_MARKER if the label is empty
		private int label_char() {
			return _label==null ? ITEM_MARKER : _label[0];
		}

		// Elminates this node from the tree. Do not remove the root node.
		protected void remove() {
			InternalNode n = _parent;
			if (n._children==this) {
				n._children = _siblings;
			} else {
				Node m = n._children;
				while (m._siblings!=this) { m = m._siblings; }
				m._siblings = m._siblings._siblings;
			}
		}

		// inserts an internal node into this edge with a label of length ext
		private InternalNode split_edge(int ext) {
			char [] label_chunk1, label_chunk2;
			if (ext==_label.length) {
				label_chunk1 = _label; label_chunk2 = null;
			} else {
				label_chunk1 = Arrays.copyOfRange(_label, 0, ext);
				label_chunk2 = Arrays.copyOfRange(_label, ext, _label.length);
			}
			InternalNode n = new InternalNode(_parent, this, _siblings, label_chunk1);
			_parent._children = n;
			_parent = n;
			_siblings = null;
			_label = label_chunk2;
			return n;
		}

		// helper for redeem
		protected void redeem_rec(StringBuilder sb) {
			if (_parent==null) return; // root node has empty string and no parent
			_parent.redeem_rec(sb);
			if (_label!=null) sb.append(_label);
		}
	}

	private static class InternalNode extends Node {
		private Node _children;

		private InternalNode(InternalNode parent, Node children, Node siblings, char [] label) {
			_parent = parent;
			_children = children;
			_siblings = siblings;
			_label = label;
		}

		/* Return the child whose edge label starts with c, or null if it is not there.
		 * The requested child, if it exists, is moved to the front of the linked list.
		 * This may speed up future lookups, and makes it easier to relink the child.
		 */
		private Node find_child(int c) {
			Node ch = _children;
			if (ch==null || ch.label_char()==c) return ch;
			for (Node cur=ch, nxt=ch._siblings; nxt!=null; cur=nxt, nxt=cur._siblings) {
				if (nxt.label_char()==c) {
					cur._siblings = nxt._siblings;
					nxt._siblings = ch;
					_children = nxt;
					return nxt;
				}
			}
			return null;
		}
	}

	private static class Leaf extends Node {

		private Leaf(InternalNode parent, Node siblings, char [] label) {
			_parent = parent;
			_siblings = siblings;
			_label = label;
		}

		private void invalidate() { _parent = null; _siblings = null; _label = null; }
		private void verify() { if (_parent==null) throw new InvalidTicketException(); }
	}
}


text:
// Copyright (c) Aptos
// SPDX-License-Identifier: Apache-2.0

use crate::{mock_tree_store::MockTreeStore, node_type::LeafNode, JellyfishMerkleTree, TestKey};
use aptos_crypto::{
    hash::{CryptoHash, SPARSE_MERKLE_PLACEHOLDER_HASH},
    HashValue,
};
use aptos_crypto_derive::{BCSCryptoHash, CryptoHasher};
use aptos_types::{
    proof::{SparseMerkleInternalNode, SparseMerkleRangeProof},
    transaction::Version,
};
use proptest::{
    collection::{btree_map, hash_map, vec},
    prelude::*,
};
use proptest_derive::Arbitrary;
use serde::{Deserialize, Serialize};
use std::{
    collections::{BTreeMap, HashMap, HashSet},
    ops::Bound,
};
use storage_interface::jmt_update_refs;

#[derive(
    Arbitrary,
    BCSCryptoHash,
    Clone,
    Debug,
    Default,
    PartialOrd,
    Ord,
    Eq,
    Hash,
    PartialEq,
    Serialize,
    Deserialize,
    CryptoHasher,
)]
pub struct ValueBlob(Vec<u8>);

impl From<Vec<u8>> for ValueBlob {
    fn from(blob: Vec<u8>) -> Self {
        Self(blob)
    }
}

impl crate::Key for ValueBlob {
    fn key_size(&self) -> usize {
        self.0.len()
    }
}
impl crate::Value for ValueBlob {
    fn value_size(&self) -> usize {
        self.0.len()
    }
}
impl crate::TestKey for ValueBlob {}
impl crate::TestValue for ValueBlob {}

pub(crate) fn gen_value() -> (HashValue, ValueBlob) {
    (
        HashValue::random(),
        ValueBlob::from(HashValue::random().to_vec()),
    )
}

/// Computes the key immediately after `key`.
pub fn plus_one(key: HashValue) -> HashValue {
    assert_ne!(key, HashValue::new([0xff; HashValue::LENGTH]));

    let mut buf = key.to_vec();
    for i in (0..HashValue::LENGTH).rev() {
        if buf[i] == 255 {
            buf[i] = 0;
        } else {
            buf[i] += 1;
            break;
        }
    }
    HashValue::from_slice(&buf).unwrap()
}

/// Initializes a DB with a set of key-value pairs by inserting one key at each version.
pub fn init_mock_db<V>(kvs: &HashMap<HashValue, (HashValue, V)>) -> (MockTreeStore<V>, Version)
where
    V: TestKey,
{
    assert!(!kvs.is_empty());

    let db = MockTreeStore::default();
    let tree = JellyfishMerkleTree::new(&db);

    for (i, (key, value)) in kvs.iter().enumerate() {
        let (_root_hash, write_batch) = tree
            .put_value_set_test(vec![(*key, Some(value))], i as Version)
            .unwrap();
        db.write_tree_update_batch(write_batch).unwrap();
    }

    (db, (kvs.len() - 1) as Version)
}

pub fn arb_existent_kvs_and_nonexistent_keys<V: TestKey>(
    num_kvs: usize,
    num_non_existing_keys: usize,
) -> impl Strategy<Value = (HashMap<HashValue, (HashValue, V)>, Vec<HashValue>)> {
    hash_map(
        any::<HashValue>(),
        (any::<HashValue>(), any::<V>()),
        1..num_kvs,
    )
    .prop_flat_map(move |kvs| {
        let kvs_clone = kvs.clone();
        (
            Just(kvs),
            vec(
                any::<HashValue>().prop_filter(
                    "Make sure these keys do not exist in the tree.",
                    move |key| !kvs_clone.contains_key(key),
                ),
                num_non_existing_keys,
            ),
        )
    })
}

pub fn test_get_with_proof<V: TestKey>(
    (existent_kvs, nonexistent_keys): (HashMap<HashValue, (HashValue, V)>, Vec<HashValue>),
) {
    let (db, version) = init_mock_db(&existent_kvs);
    let tree = JellyfishMerkleTree::new(&db);

    test_existent_keys_impl(&tree, version, &existent_kvs);
    test_nonexistent_keys_impl(&tree, version, &nonexistent_keys);
}

pub fn arb_kv_pair_with_distinct_last_nibble<V: TestKey>(
) -> impl Strategy<Value = ((HashValue, (HashValue, V)), (HashValue, (HashValue, V)))> {
    (
        any::<HashValue>().prop_filter("Can't be 0xffffff...", |key| {
            *key != HashValue::new([0xff; HashValue::LENGTH])
        }),
        vec((any::<HashValue>(), any::<V>()), 2),
    )
        .prop_map(|(key1, accounts)| {
            let key2 = plus_one(key1);
            ((key1, accounts[0].clone()), (key2, accounts[1].clone()))
        })
}

pub fn test_get_with_proof_with_distinct_last_nibble<V: TestKey>(
    (kv1, kv2): ((HashValue, (HashValue, V)), (HashValue, (HashValue, V))),
) {
    let mut kvs = HashMap::new();
    kvs.insert(kv1.0, kv1.1);
    kvs.insert(kv2.0, kv2.1);

    let (db, version) = init_mock_db(&kvs);
    let tree = JellyfishMerkleTree::new(&db);

    test_existent_keys_impl(&tree, version, &kvs);
}

pub fn arb_tree_with_index<V: TestKey>(
    tree_size: usize,
) -> impl Strategy<Value = (BTreeMap<HashValue, (HashValue, V)>, usize)> {
    btree_map(
        any::<HashValue>(),
        (any::<HashValue>(), any::<V>()),
        1..tree_size,
    )
    .prop_flat_map(|btree| {
        let len = btree.len();
        (Just(btree), 0..len)
    })
}

pub fn test_get_range_proof<V: TestKey>((btree, n): (BTreeMap<HashValue, (HashValue, V)>, usize)) {
    let (db, version) = init_mock_db(&btree.clone().into_iter().collect());
    let tree = JellyfishMerkleTree::new(&db);

    let nth_key = *btree.keys().nth(n).unwrap();
    let proof = tree.get_range_proof(nth_key, version).unwrap();
    verify_range_proof(
        tree.get_root_hash(version).unwrap(),
        btree.into_iter().take(n + 1).collect(),
        proof,
    );
}

fn test_existent_keys_impl<'a, V: TestKey>(
    tree: &JellyfishMerkleTree<'a, MockTreeStore<V>, V>,
    version: Version,
    existent_kvs: &HashMap<HashValue, (HashValue, V)>,
) {
    let root_hash = tree.get_root_hash(version).unwrap();

    for (key, value) in existent_kvs {
        let (account, proof) = tree.get_with_proof(*key, version).unwrap();
        assert!(proof
            .verify_by_hash(root_hash, *key, account.as_ref().map(|v| v.0))
            .is_ok());
        assert_eq!((account.as_ref().unwrap().0, account.unwrap().1 .0), *value);
    }
}

fn test_nonexistent_keys_impl<'a, V: TestKey>(
    tree: &JellyfishMerkleTree<'a, MockTreeStore<V>, V>,
    version: Version,
    nonexistent_keys: &[HashValue],
) {
    let root_hash = tree.get_root_hash(version).unwrap();

    for key in nonexistent_keys {
        let (account, proof) = tree.get_with_proof(*key, version).unwrap();
        assert!(proof.verify_by_hash(root_hash, *key, None).is_ok());
        assert!(account.is_none());
    }
}

/// Checks if we can construct the expected root hash using the entries in the btree and the proof.
fn verify_range_proof<V: TestKey>(
    expected_root_hash: HashValue,
    btree: BTreeMap<HashValue, (HashValue, V)>,
    proof: SparseMerkleRangeProof,
) {
    // For example, given the following sparse Merkle tree:
    //
    //                   root
    //                  /     \
    //                 /       \
    //                /         \
    //               o           o
    //              / \         / \
    //             a   o       o   h
    //                / \     / \
    //               o   d   e   X
    //              / \         / \
    //             b   c       f   g
    //
    // we transform the keys as follows:
    //   a => 00,
    //   b => 0100,
    //   c => 0101,
    //   d => 011,
    //   e => 100,
    //   X => 101
    //   h => 11
    //
    // Basically, the suffixes that doesn't affect the common prefix of adjacent leaves are
    // discarded. In this example, we assume `btree` has the keys `a` to `e` and the proof has `X`
    // and `h` in the siblings.

    // Now we want to construct a set of key-value pairs that covers the entire set of leaves. For
    // `a` to `e` this is simple -- we just insert them directly into this set. For the rest of the
    // leaves, they are represented by the siblings, so we just make up some keys that make sense.
    // For example, for `X` we just use 101000... (more zeros omitted), because that is one key
    // that would cause `X` to end up in the above position.
    let mut btree1 = BTreeMap::new();
    for (key, value) in &btree {
        let leaf = LeafNode::new(*key, value.0, (value.1.clone(), 0 /* version */));
        btree1.insert(*key, leaf.hash());
    }
    // Using the above example, `last_proven_key` is `e`. We look at the path from root to `e`.
    // For each 0-bit, there should be a sibling in the proof. And we use the path from root to
    // this position, plus a `1` as the key.
    let last_proven_key = *btree
        .keys()
        .last()
        .expect("We are proving at least one key.");
    for (i, sibling) in last_proven_key
        .iter_bits()
        .enumerate()
        .filter_map(|(i, bit)| if !bit { Some(i) } else { None })
        .zip(proof.right_siblings().iter().rev())
    {
        // This means the `i`-th bit is zero. We take `i` bits from `last_proven_key` and append a
        // one to make up the key for this sibling.
        let mut buf: Vec<_> = last_proven_key.iter_bits().take(i).collect();
        buf.push(true);
        // The rest doesn't matter, because they don't affect the position of the node. We just
        // add zeros.
        buf.resize(HashValue::LENGTH_IN_BITS, false);
        let key = HashValue::from_bit_iter(buf.into_iter()).unwrap();
        btree1.insert(key, *sibling);
    }

    // Now we do the transformation (removing the suffixes) described above.
    let mut kvs = vec![];
    for (key, value) in &btree1 {
        // The length of the common prefix of the previous key and the current key.
        let prev_common_prefix_len =
            prev_key(&btree1, key).map(|pkey| pkey.common_prefix_bits_len(*key));
        // The length of the common prefix of the next key and the current key.
        let next_common_prefix_len =
            next_key(&btree1, key).map(|nkey| nkey.common_prefix_bits_len(*key));

        // We take the longest common prefix of the current key and its neighbors. That's how much
        // we need to keep.
        let len = match (prev_common_prefix_len, next_common_prefix_len) {
            (Some(plen), Some(nlen)) => std::cmp::max(plen, nlen),
            (Some(plen), None) => plen,
            (None, Some(nlen)) => nlen,
            (None, None) => 0,
        };
        let transformed_key: Vec<_> = key.iter_bits().take(len + 1).collect();
        kvs.push((transformed_key, *value));
    }

    assert_eq!(compute_root_hash(kvs), expected_root_hash);
}

/// Reduces the problem by removing the first bit of every key.
fn reduce<'a>(kvs: &'a [(&[bool], HashValue)]) -> Vec<(&'a [bool], HashValue)> {
    kvs.iter().map(|(key, value)| (&key[1..], *value)).collect()
}

/// Returns the key immediately before `key` in `btree`.
fn prev_key<K, V>(btree: &BTreeMap<K, V>, key: &K) -> Option<K>
where
    K: Clone + Ord,
{
    btree
        .range((Bound::Unbounded, Bound::Excluded(key)))
        .next_back()
        .map(|(k, _v)| k.clone())
}

fn next_key<K, V>(btree: &BTreeMap<K, V>, key: &K) -> Option<K>
where
    K: Clone + Ord,
{
    btree
        .range((Bound::Excluded(key), Bound::Unbounded))
        .next()
        .map(|(k, _v)| k.clone())
}

/// Computes the root hash of a sparse Merkle tree. `kvs` consists of the entire set of key-value
/// pairs stored in the tree.
fn compute_root_hash(kvs: Vec<(Vec<bool>, HashValue)>) -> HashValue {
    let mut kv_ref = vec![];
    for (key, value) in &kvs {
        kv_ref.push((&key[..], *value));
    }
    compute_root_hash_impl(kv_ref)
}

fn compute_root_hash_impl(kvs: Vec<(&[bool], HashValue)>) -> HashValue {
    assert!(!kvs.is_empty());

    // If there is only one entry, it is the root.
    if kvs.len() == 1 {
        return kvs[0].1;
    }

    // Otherwise the tree has more than one leaves, which means we can find which ones are in the
    // left subtree and which ones are in the right subtree. So we find the first key that starts
    // with a 1-bit.
    let left_hash;
    let right_hash;
    match kvs.iter().position(|(key, _value)| key[0]) {
        Some(0) => {
            // Every key starts with a 1-bit, i.e., they are all in the right subtree.
            left_hash = *SPARSE_MERKLE_PLACEHOLDER_HASH;
            right_hash = compute_root_hash_impl(reduce(&kvs));
        }
        Some(index) => {
            // Both left subtree and right subtree have some keys.
            left_hash = compute_root_hash_impl(reduce(&kvs[..index]));
            right_hash = compute_root_hash_impl(reduce(&kvs[index..]));
        }
        None => {
            // Every key starts with a 0-bit, i.e., they are all in the left subtree.
            left_hash = compute_root_hash_impl(reduce(&kvs));
            right_hash = *SPARSE_MERKLE_PLACEHOLDER_HASH;
        }
    }

    SparseMerkleInternalNode::new(left_hash, right_hash).hash()
}

pub fn test_get_leaf_count(keys: HashSet<HashValue>) {
    let keys = keys.into_iter().collect::<Vec<_>>();
    let idx1 = keys.len() / 3;
    let idx2 = keys.len() / 3 * 2;
    let kvs = keys[0..idx2].iter().map(|k| (*k, gen_value())).collect();
    let (db, version) = init_mock_db(&kvs);
    let updates = keys[idx1..idx2]
        .iter()
        .map(|k| (*k, None))
        .chain(keys[idx2..].iter().map(|k| (*k, Some(gen_value()))))
        .collect::<Vec<_>>();
    let tree = JellyfishMerkleTree::new(&db);
    let (_, batch) = tree
        .put_value_set_test(jmt_update_refs(updates.as_slice()), version + 1)
        .unwrap();
    db.write_tree_update_batch(batch).unwrap();
    assert_eq!(
        tree.get_leaf_count(version + 1).unwrap(),
        keys.len() - (idx2 - idx1)
    )
}


text:
@import UIKit;
#import <ResearchKit/ORKDefines.h>
#import <ResearchKit/ORKStepViewController.h>

NS_ASSUME_NONNULL_BEGIN

/**
 The `ORKQuestionStepViewController` class is the concrete `ORKStepViewController`
 implementation for `ORKQuestionStep`.

 You should not need to instantiate an `ORKQuestionStepViewController` object
 directly. Instead, create an `ORKQuestionStep` object, include it in a task
 the task using a task view controller. The task view
 controller automatically instantiates the question step view controller
 when it needs to present a question step.

 To use `ORKQuestionStepViewController` directly, create an `ORKQuestionStep` object and use
 `initWithStep:` to initialize it. To receive the result of the question, and to determine
 when to dismiss the view controller, implement `ORKStepViewControllerDelegate`.
 */

ORK_CLASS_AVAILABLE
@interface ORKQuestionStepViewController : ORKStepViewController

@end

NS_ASSUME_NONNULL_END


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

<TITLE>
HqmeError
</TITLE>

<META NAME="date" CONTENT="2011-09-20">

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

      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | ENUM CONSTANTS | FIELD | METHOD

DETAIL: ENUM CONSTANTS | FIELD | METHOD

com.hqme.cm

Enum HqmeError

java.lang.Object
  java.lang.Enum<HqmeError>
      com.hqme.cm.HqmeError

All Implemented Interfaces:
java.io.Serializable, java.lang.Comparable<HqmeError>

public enum HqmeError
extends java.lang.Enum<HqmeError>

Enum Constant Summary

ERR_CANCEL_FAILED

ERR_GENERAL

ERR_INVALID_ARGUMENT

ERR_INVALID_POLICY

ERR_INVALID_PROPERTY

ERR_INVALID_REQUEST_ID

ERR_IO

ERR_NOT_FOUND

ERR_NOT_SUPPORTED

ERR_PENDING_OPERATION

ERR_PERMISSION_DENIED

ERR_RESUME_FAILED

ERR_SUSPEND_FAILED

ERR_TIMEOUT

ERR_UNKNOWN

ERR_VSD_UNAVAILABLE

STATUS_SUCCESS

Method Summary

static HqmeError
fromInt(int i)

 int
getCode()

 java.lang.String
getDescription()

static HqmeError
valueOf(java.lang.String name)

          Returns the enum constant of this type with the specified name.

static HqmeError[]
values()

          Returns an array containing the constants of this enum type, in
the order they are declared.

Methods inherited from class java.lang.Enum

compareTo, equals, getDeclaringClass, hashCode, name, ordinal, toString, valueOf

Methods inherited from class java.lang.Object

getClass, notify, notifyAll, wait, wait, wait

Enum Constant Detail

STATUS_SUCCESS

public static final HqmeError STATUS_SUCCESS

ERR_INVALID_ARGUMENT

public static final HqmeError ERR_INVALID_ARGUMENT

ERR_NOT_FOUND

public static final HqmeError ERR_NOT_FOUND

ERR_TIMEOUT

public static final HqmeError ERR_TIMEOUT

ERR_PENDING_OPERATION

public static final HqmeError ERR_PENDING_OPERATION

ERR_IO

public static final HqmeError ERR_IO

ERR_NOT_SUPPORTED

public static final HqmeError ERR_NOT_SUPPORTED

ERR_PERMISSION_DENIED

public static final HqmeError ERR_PERMISSION_DENIED

ERR_VSD_UNAVAILABLE

public static final HqmeError ERR_VSD_UNAVAILABLE

ERR_INVALID_REQUEST_ID

public static final HqmeError ERR_INVALID_REQUEST_ID

ERR_CANCEL_FAILED

public static final HqmeError ERR_CANCEL_FAILED

ERR_SUSPEND_FAILED

public static final HqmeError ERR_SUSPEND_FAILED

ERR_RESUME_FAILED

public static final HqmeError ERR_RESUME_FAILED

ERR_INVALID_POLICY

public static final HqmeError ERR_INVALID_POLICY

ERR_INVALID_PROPERTY

public static final HqmeError ERR_INVALID_PROPERTY

ERR_GENERAL

public static final HqmeError ERR_GENERAL

ERR_UNKNOWN

public static final HqmeError ERR_UNKNOWN

Method Detail

values

public static HqmeError[] values()

Returns an array containing the constants of this enum type, in
the order they are declared.  This method may be used to iterate
over the constants as follows:

for (HqmeError c : HqmeError.values())
    System.out.println(c);

Returns:
an array containing the constants of this enum type, in
the order they are declared

valueOf

public static HqmeError valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.
The string must match exactly an identifier used to declare an
enum constant in this type.  (Extraneous whitespace characters are
not permitted.)

Parameters:
name - the name of the enum constant to be returned.

Returns:
the enum constant with the specified name

Throws:

java.lang.IllegalArgumentException - if this enum type has no constant
with the specified name

java.lang.NullPointerException - if the argument is null

fromInt

public static HqmeError fromInt(int i)

getDescription

public java.lang.String getDescription()

getCode

public int getCode()

      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | ENUM CONSTANTS | FIELD | METHOD

DETAIL: ENUM CONSTANTS | FIELD | METHOD


text:
package edu.hm.cs.jenkins.web.callback;

import edu.hm.cs.jenkins.web.callback.adapter.LastBuildCallbackAdapter;
import edu.hm.cs.jenkins.web.model.Build;
import edu.hm.cs.jenkins.web.model.Job;
import org.junit.Test;

/**
 * Tests the class {@link edu.hm.cs.jenkins.web.callback.adapter.LastBuildCallbackAdapter}.
 *
 * @author Tobias Wochinger
 */
public class LastBuildCallbackAdapterTest extends AbstractBuildCallbackAdapterTest {

    /**
     * Tests if the objects are processed by the adapter.
     */
    @Test
    public void testAdapter() {
        Job job = createTestJob();
        LastBuildCallbackAdapter adapter = new LastBuildCallbackAdapter(job, getCallback());
        job.setLastBuild(new Build());
        adapter.success(createJobWithBuild(), null);

        verifyCorrectPassing(job);
    }

    private Job createJobWithBuild() {
        Job job = new Job();
        job.setLastBuild(new Build());
        return job;
    }
}


text:
@implementation Test_UIProgressView

- (void)dealloc
{
	[self unloadTemplate];
}

- (void)viewDidLoad {

	[super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.

	[self loadTemplate:@"/www/html/Test_UIProgressView.html"];
}

- (void)didReceiveMemoryWarning {

	[super didReceiveMemoryWarning];
	// Dispose of any resources that can be recreated.
}

#pragma mark -

- (void)onTemplateLoading
{

}

- (void)onTemplateLoaded
{

}

- (void)onTemplateFailed
{

}

- (void)onTemplateCancelled
{

}

@end


text:
// <copyright file="WebDavResult.cs" company="Fubar Development Junker">
// Copyright (c) Fubar Development Junker. All rights reserved.
// </copyright>

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

using FubarDev.WebDavServer.Model;

namespace FubarDev.WebDavServer
{
    /// <summary>
    /// The result of a WebDAV operation
    /// </summary>
    public class WebDavResult : IWebDavResult
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="WebDavResult"/> class.
        /// </summary>
        /// <param name="statusCode">The WebDAV status code</param>
        public WebDavResult(WebDavStatusCode statusCode)
        {
            StatusCode = statusCode;
        }

        /// <inheritdoc />
        public WebDavStatusCode StatusCode { get; }

        /// <summary>
        /// Gets the header values to be set for the response
        /// </summary>
        public Dictionary<string, IEnumerable<string>> Headers { get; } = new Dictionary<string, IEnumerable<string>>();

        /// <inheritdoc />
        public virtual Task ExecuteResultAsync(IWebDavResponse response, CancellationToken ct)
        {
            IImmutableDictionary<string, IEnumerable<string>> headers = ImmutableDictionary<string, IEnumerable<string>>.Empty;

            foreach (var webDavClass in response.Dispatcher.SupportedClasses)
                headers = AddHeaderValues(headers, webDavClass.DefaultResponseHeaders);

            headers = AddHeaderValues(headers, Headers);

            foreach (var header in headers)
            {
                response.Headers[header.Key] = header.Value.ToArray();
            }

            return Task.FromResult(0);
        }

        /// <summary>
        /// Adds header values to the current header dictionary
        /// </summary>
        /// <param name="currentHeaders">The current header dictionary</param>
        /// <param name="headersToAdd">The headers to add</param>
        /// <returns>The updated header dictionary</returns>
        protected IImmutableDictionary<string, IEnumerable<string>> AddHeaderValues(
            IImmutableDictionary<string, IEnumerable<string>> currentHeaders,
            IReadOnlyDictionary<string, IEnumerable<string>> headersToAdd)
        {
            foreach (var header in headersToAdd)
            {
                IEnumerable<string> oldValues;
                currentHeaders = currentHeaders.SetItem(
                    header.Key,
                    currentHeaders.TryGetValue(header.Key, out oldValues) ? oldValues.Union(header.Value) : header.Value);
            }

            return currentHeaders;
        }
    }
}


text:
import CodeBlockWriter from "code-block-writer";
import {expect} from "chai";
import {FunctionDefinition, MethodDefinitions, ClassMethodDefinition, ClassStaticMethodDefinition} from "./../../definitions";
import {createFunction, createClassMethod, createClassStaticMethod} from "./../../createFunctions";
import {FunctionWriter} from "./../../writers";
import {WriteFlags} from "./../../WriteFlags";
import * as mocks from "./mocks";

describe(nameof(FunctionWriter), () => {
    function createObjects(def: FunctionDefinition | MethodDefinitions) {
        const writer = new CodeBlockWriter();
        const defWriter = new FunctionWriter(
            writer,
            mocks.getBaseDefinitionWriter(writer, def),
            mocks.getDocumentationedWriter(writer, [...def.overloadSignatures, def]),
            mocks.getDecoratorsWriter(writer, [def as ClassMethodDefinition]),
            mocks.getExportableWriter(writer, def as FunctionDefinition),
            mocks.getAmbientableWriter(writer, def as FunctionDefinition),
            mocks.getAsyncableWriter(writer, def as FunctionDefinition),
            mocks.getScopeWriter(writer, [(def as ClassMethodDefinition).scope]),
            mocks.getCallSignatureWriter(writer, def.overloadSignatures),
            mocks.getTypeParametersWriter(writer, def.typeParameters),
            mocks.getParametersWriter(writer, [def]),
            mocks.getFunctionBodyWriter(writer, [def as FunctionDefinition], [false]),
            mocks.getFunctionReturnTypeWriter(writer, [def]));
        return {writer, defWriter};
    }

    describe(nameof<FunctionWriter>(w => w.write), () => {
        const prefix = "{start}";
        const suffix = "{end}";

        describe(nameof(FunctionDefinition), () => {
            const callSignatureStart = (writeFlags: number) => `{doc-comment}{export-keyword:${writeFlags}}{declare-keyword}{async-keyword}`;
            const functionStart = (writeFlags: number) => `{doc-comment}{decorators:${writeFlags}:newline}{export-keyword:${writeFlags}}{declare-keyword}{async-keyword}`;
            const functionEnd = (writeFlags: number) => `{type-parameters}({parameters:${writeFlags}}){function-return-type}{function-body};`;

            it("should write out the function", () => {
                const def = createFunction({
                    name: "Name"
                });
                const {writer, defWriter} = createObjects(def);
                defWriter.write(def, WriteFlags.None);
                const expected = `${prefix}${functionStart(0)}function Name${functionEnd(0)}${suffix}`;
                expect(writer.toString()).to.equal(expected);
            });

            it("should write out the function with * when generator", () => {
                const def = createFunction({
                    name: "Name",
                    isGenerator: true
                });
                const {writer, defWriter} = createObjects(def);
                defWriter.write(def, WriteFlags.None);
                const expected = `${prefix}${functionStart(0)}function* Name${functionEnd(0)}${suffix}`;
                expect(writer.toString()).to.equal(expected);
            });

            it("should write out the function with overload signatures", () => {
                const def = createFunction({
                    name: "Name",
                    overloadSignatures: [{}, {}]
                });
                const {writer, defWriter} = createObjects(def);
                defWriter.write(def, WriteFlags.None);
                const expected = prefix +
                    `${callSignatureStart(0)}function Name{call-signature:0};\n` +
                    `${callSignatureStart(0)}function Name{call-signature:0};\n` +
                    `${functionStart(0)}function Name${functionEnd(0)}${suffix}`;
                expect(writer.toString()).to.equal(expected);
            });

            it(`should write out the function without the implementation when there are more than one overload signatures and ${WriteFlags.HideFunctionImplementations} is set`, () => {
                const def = createFunction({
                    name: "Name",
                    overloadSignatures: [{}]
                });
                const {writer, defWriter} = createObjects(def);
                defWriter.write(def, WriteFlags.HideFunctionImplementations);
                const expected = `${prefix}${callSignatureStart(64)}function Name{call-signature:64};${suffix}`;
                expect(writer.toString()).to.equal(expected);
            });

            it(`should write out the function with the implementation when there are zero overload signatures and ${WriteFlags.HideFunctionImplementations} is set`, () => {
                const def = createFunction({
                    name: "Name"
                });
                const {writer, defWriter} = createObjects(def);
                defWriter.write(def, WriteFlags.HideFunctionImplementations);
                const expected = `${prefix}${functionStart(64)}function Name${functionEnd(64)}${suffix}`;
                expect(writer.toString()).to.equal(expected);
            });
        });

        describe(nameof(ClassMethodDefinition), () => {
            it("should write out the method", () => {
                const def = createClassMethod({
                    name: "Name"
                });
                const {writer, defWriter} = createObjects(def);
                defWriter.write(def, WriteFlags.None);
                const expected = `${prefix}{doc-comment}{decorators:0:newline}{scope}{async-keyword}Name{type-parameters}({parameters:0})` +
                    `{function-return-type}{function-body};${suffix}`;
                expect(writer.toString()).to.equal(expected);
            });

            it("should write out the abstract method with abstract keyword", () => {
                const def = createClassMethod({
                    name: "Name",
                    isAbstract: true
                });
                const {writer, defWriter} = createObjects(def);
                defWriter.write(def, WriteFlags.None);
                const expected = `${prefix}{doc-comment}{decorators:0:newline}{scope}abstract {async-keyword}Name{type-parameters}({parameters:0})` +
                    `{function-return-type}{function-body};${suffix}`;
                expect(writer.toString()).to.equal(expected);
            });
        });

        describe(nameof(ClassStaticMethodDefinition), () => {
            it("should write out the static method with static keyword", () => {
                const def = createClassStaticMethod({
                    name: "Name"
                });
                const {writer, defWriter} = createObjects(def);
                defWriter.write(def, WriteFlags.None);
                const expected = `${prefix}{doc-comment}{decorators:0:newline}{scope}static {async-keyword}Name{type-parameters}({parameters:0})` +
                    `{function-return-type}{function-body};${suffix}`;
                expect(writer.toString()).to.equal(expected);
            });
        });
    });
});


text:
ioconsole
=========
NOTE: It is in alpha version (specially help command).
A simple console made in batch, with some scripts.


text:
package net.stickycode.stereotype.failure.resolver;

/**
 * You tried to do something like this
 *
 * <pre>
 * new SomeException("Some {} message", "param 1", "param 2");
 * </pre>
 *
 * Obviously param 2 will disappear which is very annoying, to this error warns you about that.
 */
@SuppressWarnings("serial")
class TooManyArgumentsException
    extends RuntimeException {

  public TooManyArgumentsException(Object[] parameters, int placeHolderCount, String message) {
    super(String.format(
        "Found %s parameters " +
            "but only %s places for them in '%s'. " +
            "Add some placeholders or remove some arguments. " +
            "The parameters were %s",
        parameters.length, placeHolderCount, message,
        parameters));
  }

}


text:
<?xml version="1.0"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You 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.
-->
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>

<configuration>
  <property>
    <name>yarn.log-aggregation-enable</name>
    <value>true</value>
  </property>

  <property>
    <name>yarn.resourcemanager.address</name>
    <value>memex-rm.xdata.data-tactics-corp.com:8032</value>
  </property>

  <property>
    <name>yarn.resourcemanager.scheduler.address</name>
    <value>memex-rm.xdata.data-tactics-corp.com:8030</value>
  </property>

  <property>
    <name>yarn.resourcemanager.resource-tracker.address</name>
    <value>memex-rm.xdata.data-tactics-corp.com:8031</value>
  </property>

  <property>
    <name>yarn.resourcemanager.admin.address</name>
    <value>memex-rm.xdata.data-tactics-corp.com:8033</value>
  </property>

  <property>
    <name>yarn.web-proxy.address</name>
    <value>memex-rm.xdata.data-tactics-corp.com:8034</value>
  </property>

  <property>
    <name>yarn.nodemanager.address</name>
    <value>0.0.0.0:45454</value>
  </property>

  <property>
    <name>yarn.resourcemanager.webapp.address</name>
    <value>memex-rm.xdata.data-tactics-corp.com:8088</value>
  </property>

  <property>
    <name>yarn.scheduler.minimum-allocation-mb</name>
    <value>21504</value>
  </property>

  <property>
    <name>yarn.scheduler.maximum-allocation-mb</name>
    <value>301056</value>
  </property>

  <property>
    <name>yarn.scheduler.minimum-allocation-vcores</name>
    <value>1</value>
  </property>

  <property>
    <name>yarn.scheduler.maximum-allocation-vcores</name>
    <value>12</value>
  </property>

  <property>
    <name>yarn.nodemanager.resource.memory-mb</name>
    <value>301056</value>
  </property>

  <property>
    <name>yarn.nodemanager.resource.cpu-vcores</name>
    <value>20</value>
  </property>

  <property>
    <name>yarn.nodemanager.vmem-pmem-ratio</name>
    <value>2.1</value>
  </property>

  <property>
    <name>yarn.nodemanager.local-dirs</name>
    <value>/data0/yarn/local,/data1/yarn/local,/data2/yarn/local,/data3/yarn/local,/data4/yarn/local,/data5/yarn/local,/data6/yarn/local</value>
  </property>

  <property>
    <name>yarn.nodemanager.log-dirs</name>
    <value>/data0/yarn/logs,/data1/yarn/logs,/data2/yarn/logs,/data3/yarn/logs,/data4/yarn/logs,/data5/yarn/logs,/data6/yarn/logs</value>
  </property>

  <property>
    <name>yarn.nodemanager.remote-app-log-dir</name>
    <value>/var/log/hadoop-yarn/apps</value>
  </property>

  <property>
    <name>yarn.nodemanager.remote-app-log-dir-suffix</name>
    <value>logs</value>
  </property>

  <property>
    <name>yarn.nodemanager.aux-services</name>
    <value>mapreduce_shuffle</value>
  </property>

  <property>
    <name>yarn.nodemanager.aux-services.mapreduce_shuffle.class</name>
    <value>org.apache.hadoop.mapred.ShuffleHandler</value>
  </property>

  <property>
    <description>Classpath for typical applications.</description>
     <name>yarn.application.classpath</name>
     <value>
        $HADOOP_CONF_DIR,
        $HADOOP_COMMON_HOME/*,$HADOOP_COMMON_HOME/lib/*,
        $HADOOP_HDFS_HOME/*,$HADOOP_HDFS_HOME/lib/*,
        $HADOOP_MAPRED_HOME/*,$HADOOP_MAPRED_HOME/lib/*,
        $YARN_HOME/*,$YARN_HOME/lib/*
     </value>
  </property>
</configuration>