text:
/**
 * Fake XMLHttpRequest implementation for node.
 *
 * Modified from the code for node-xmlhttprequest to enable
 * support for returning XML etc.
 *
 * See https://github.com/driverdan/node-XMLHttpRequest
 * for the original code.
 *
 * Credits for the original code:
 *
 * @author Dan DeFelippi <dan@driverdan.com>
 * @contributor David Ellis <d.f.ellis@ieee.org>
 * @license MIT
 */

var Url = require("url");
var spawn = require("child_process").spawn;
var fs = require('fs');

// pass in the http and https implementations; returns a class
// suitable for replacing XMLHttpRequest in a node.js context
var construct = function (http, https) {
  return function () {
    /**
     * Private variables
     */
    var self = this;

    this.FAKED = true;

    // Holds http.js objects
    var request;
    var response;

    // Request settings
    var settings = {};

    // Disable header blacklist.
    // Not part of XHR specs.
    var disableHeaderCheck = false;

    // Set some default headers
    var defaultHeaders = {
      "User-Agent": "fake-XMLHttpRequest",
      "Accept": "*/*",
    };

    var headers = defaultHeaders;

    // These headers are not user setable.
    // The following are allowed but banned in the spec:
    // * user-agent
    var forbiddenRequestHeaders = [
      "accept-charset",
      "accept-encoding",
      "access-control-request-headers",
      "access-control-request-method",
      "connection",
      "content-length",
      "content-transfer-encoding",
      "cookie",
      "cookie2",
      "date",
      "expect",
      "host",
      "keep-alive",
      "origin",
      "referer",
      "te",
      "trailer",
      "transfer-encoding",
      "upgrade",
      "via"
    ];

    // These request methods are not allowed
    var forbiddenRequestMethods = [
      "TRACE",
      "TRACK",
      "CONNECT"
    ];

    // Send flag
    var sendFlag = false;
    // Error flag, used when errors occur or abort is called
    var errorFlag = false;

    // Event listeners
    var listeners = {};

    /**
     * Constants
     */

    this.UNSENT = 0;
    this.OPENED = 1;
    this.HEADERS_RECEIVED = 2;
    this.LOADING = 3;
    this.DONE = 4;

    /**
     * Public vars
     */

    // Current state
    this.readyState = this.UNSENT;

    // default ready state change handler in case one is not set or is set late
    this.onreadystatechange = null;

    // Result & response
    this.responseText = "";
    this.responseXML = "";
    this.status = null;
    this.statusText = null;

    /**
     * Private methods
     */

    /**
     * Check if the specified header is allowed.
     *
     * @param string header Header to validate
     * @return boolean False if not allowed, otherwise true
     */
    var isAllowedHttpHeader = function(header) {
      return disableHeaderCheck || (header && forbiddenRequestHeaders.indexOf(header.toLowerCase()) === -1);
    };

    /**
     * Check if the specified method is allowed.
     *
     * @param string method Request method to validate
     * @return boolean False if not allowed, otherwise true
     */
    var isAllowedHttpMethod = function(method) {
      return (method && forbiddenRequestMethods.indexOf(method) === -1);
    };

    /**
     * Public methods
     */

    /**
     * Open the connection. Currently supports local server requests.
     *
     * @param string method Connection method (eg GET, POST)
     * @param string url URL for the connection.
     * @param boolean async Asynchronous connection. Default is true.
     * @param string user Username for basic authentication (optional)
     * @param string password Password for basic authentication (optional)
     */
    this.open = function(method, url, async, user, password) {
      this.abort();
      errorFlag = false;

      // Check for valid request method
      if (!isAllowedHttpMethod(method)) {
        throw "SecurityError: Request method not allowed";
      }

      settings = {
        "method": method,
        "url": url.toString(),
        "async": (typeof async !== "boolean" ? true : async),
        "user": user || null,
        "password": password || null
      };

      setState(this.OPENED);
    };

    /**
     * Disables or enables isAllowedHttpHeader() check the request. Enabled by default.
     * This does not conform to the W3C spec.
     *
     * @param boolean state Enable or disable header checking.
     */
    this.setDisableHeaderCheck = function(state) {
      disableHeaderCheck = state;
    };

    /**
     * Sets a header for the request.
     *
     * @param string header Header name
     * @param string value Header value
     */
    this.setRequestHeader = function(header, value) {
      if (this.readyState != this.OPENED) {
        throw "INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN";
      }
      if (!isAllowedHttpHeader(header)) {
        console.warn('Refused to set unsafe header "' + header + '"');
        return;
      }
      if (sendFlag) {
        throw "INVALID_STATE_ERR: send flag is true";
      }
      headers[header] = value;
    };

    /**
     * Gets a header from the server response.
     *
     * @param string header Name of header to get.
     * @return string Text of the header or null if it doesn't exist.
     */
    this.getResponseHeader = function(header) {
      if (typeof header === "string"
        && this.readyState > this.OPENED
        && response.headers[header.toLowerCase()]
        && !errorFlag
      ) {
        return response.headers[header.toLowerCase()];
      }

      return null;
    };

    /**
     * Gets all the response headers.
     *
     * @return string A string with all response headers separated by CR+LF
     */
    this.getAllResponseHeaders = function() {
      if (this.readyState < this.HEADERS_RECEIVED || errorFlag) {
        return "";
      }
      var result = "";

      for (var i in response.headers) {
        // Cookie headers are excluded
        if (i !== "set-cookie" && i !== "set-cookie2") {
          result += i + ": " + response.headers[i] + "\r\n";
        }
      }
      return result.substr(0, result.length - 2);
    };

    /**
     * Gets a request header
     *
     * @param string name Name of header to get
     * @return string Returns the request header or empty string if not set
     */
    this.getRequestHeader = function(name) {
      // @TODO Make this case insensitive
      if (typeof name === "string" && headers[name]) {
        return headers[name];
      }

      return "";
    };

    /**
     * Sends the request to the server.
     *
     * @param string data Optional data to send as request body.
     */
    this.send = function(data) {
      if (this.readyState != this.OPENED) {
        throw "INVALID_STATE_ERR: connection must be opened before send() is called";
      }

      if (sendFlag) {
        throw "INVALID_STATE_ERR: send has already been called";
      }

      var ssl = false, local = false;
      var url = Url.parse(settings.url);

      var host;
      // Determine the server
      switch (url.protocol) {
        case 'https:':
          ssl = true;
          // SSL & non-SSL both need host, no break here.
        case 'http:':
          host = url.hostname;
          break;

        case 'file:':
          local = true;
          break;

        default:
          host = "localhost";
          break;
      }

      // Load files off the local filesystem (file://)
      if (local) {
        if (settings.method !== "GET") {
          throw "XMLHttpRequest: Only GET method is supported";
        }

        if (settings.async) {
          fs.readFile(url.pathname, 'utf8', function(error, data) {
            if (error) {
              self.handleError(error);
            } else {
              self.status = 200;
              self.responseText = data;
              self.responseXML = data;
              setState(self.DONE);
            }
          });
        } else {
          try {
            this.responseText = fs.readFileSync(url.pathname, 'utf8');
            this.responseXML = this.responseText;
            this.status = 200;
            setState(self.DONE);
          } catch(e) {
            this.handleError(e);
          }
        }

        return;
      }

      // Default to port 80. If accessing localhost on another port be sure
      // to use http://localhost:port/path
      var port = url.port || (ssl ? 443 : 80);
      // Add query string if one is used
      var uri = url.pathname + (url.search ? url.search : '');

      // Set the Host header or the server may reject the request
      headers["Host"] = host;
      if (!((ssl && port === 443) || port === 80)) {
        headers["Host"] += ':' + url.port;
      }

      // Set Basic Auth if necessary
      if (settings.user) {
        if (typeof settings.password == "undefined") {
          settings.password = "";
        }
        var authBuf = new Buffer(settings.user + ":" + settings.password);
        headers["Authorization"] = "Basic " + authBuf.toString("base64");
      }

      // Set content length header
      if (settings.method === "GET" || settings.method === "HEAD") {
        data = null;
      } else if (data) {
        headers["Content-Length"] = Buffer.isBuffer(data) ? data.length : Buffer.byteLength(data);

        if (!headers["Content-Type"]) {
          headers["Content-Type"] = "text/plain;charset=UTF-8";
        }
      } else if (settings.method === "POST") {
        // For a post with no data set Content-Length: 0.
        // This is required by buggy servers that don't meet the specs.
        headers["Content-Length"] = 0;
      }

      var options = {
        host: host,
        port: port,
        path: uri,
        method: settings.method,
        headers: headers,
        agent: false
      };

      // Reset error flag
      errorFlag = false;

      // Handle async requests
      if (settings.async) {
        // Use the proper protocol
        var doRequest = ssl ? https.request : http.request;

        // Request is being sent, set send flag
        sendFlag = true;

        // As per spec, this is called here for historical reasons.
        self.dispatchEvent("readystatechange");

        // Handler for the response
        function responseHandler(resp) {
          // Set response var to the response we got back
          // This is so it remains accessable outside this scope
          response = resp;
          // Check for redirect
          // @TODO Prevent looped redirects
          if (response.statusCode === 302 || response.statusCode === 303 || response.statusCode === 307) {
            // Change URL to the redirect location
            settings.url = response.headers.location;
            var url = Url.parse(settings.url);
            // Set host var in case it's used later
            host = url.hostname;
            // Options for the new request
            var newOptions = {
              hostname: url.hostname,
              port: url.port,
              path: url.path,
              method: response.statusCode === 303 ? 'GET' : settings.method,
              headers: headers
            };

            // Issue the new request
            request = doRequest(newOptions, responseHandler).on('error', errorHandler);
            request.end();
            // @TODO Check if an XHR event needs to be fired here
            return;
          }

          response.setEncoding("utf8");

          setState(self.HEADERS_RECEIVED);
          self.status = response.statusCode;

          response.on('data', function(chunk) {
            // Make sure there's some data
            if (chunk) {
              self.responseText += chunk;
              self.responseXML += chunk;
            }
            // Don't emit state changes if the connection has been aborted.
            if (sendFlag) {
              setState(self.LOADING);
            }
          });

          response.on('end', function() {
            if (sendFlag) {
              // Discard the 'end' event if the connection has been aborted
              setState(self.DONE);
              sendFlag = false;
            }
          });

          response.on('error', function(error) {
            self.handleError(error);
          });
        }

        // Error handler for the request
        function errorHandler(error) {
          self.handleError(error);
        }

        // Create the request
        request = doRequest(options, responseHandler).on('error', errorHandler);

        // Node 0.4 and later won't accept empty data. Make sure it's needed.
        if (data) {
          request.write(data);
        }

        request.end();

        self.dispatchEvent("loadstart");
      } else { // Synchronous
        // Create a temporary file for communication with the other Node process
        var contentFile = ".node-xmlhttprequest-content-" + process.pid;
        var syncFile = ".node-xmlhttprequest-sync-" + process.pid;
        fs.writeFileSync(syncFile, "", "utf8");
        // The async request the other Node process executes
        var execString = "var http = require('./http-fake.helper'), https = http, fs = require('fs');"
          + "var doRequest = http" + (ssl ? "s" : "") + ".request;"
          + "var options = " + JSON.stringify(options) + ";"
          + "var responseText = '';"
          + "var responseXML = '';"
          + "var req = doRequest(options, function(response) {"
          + "response.setEncoding('utf8');"
          + "response.on('data', function(chunk) {"
          + "  responseText += chunk;"
          + "  responseXML += chunk;"
          + "});"
          + "response.on('end', function() {"
          + "fs.writeFileSync('" + contentFile + "', 'NODE-XMLHTTPREQUEST-STATUS:' + response.statusCode + ',' + responseText, 'utf8');"
          + "fs.unlinkSync('" + syncFile + "');"
          + "});"
          + "response.on('error', function(error) {"
          + "fs.writeFileSync('" + contentFile + "', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');"
          + "fs.unlinkSync('" + syncFile + "');"
          + "});"
          + "}).on('error', function(error) {"
          + "fs.writeFileSync('" + contentFile + "', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');"
          + "fs.unlinkSync('" + syncFile + "');"
          + "});"
          + (data ? "req.write('" + data.replace(/'/g, "\\'") + "');":"")
          + "req.end();";
        // Start the other Node Process, executing this string
        var syncProc = spawn(process.argv[0], ["-e", execString]);
        var statusText;
        while(fs.existsSync(syncFile)) {
          // Wait while the sync file is empty
        }
        self.responseText = fs.readFileSync(contentFile, 'utf8');
        self.responseXML = self.responseText;
        // Kill the child process once the file has data
        syncProc.stdin.end();
        // Remove the temporary file
        fs.unlinkSync(contentFile);
        if (self.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)) {
          // If the file returned an error, handle it
          var errorObj = self.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/, "");
          self.handleError(errorObj);
        } else {
          // If the file returned okay, parse its data and move to the DONE state
          self.status = self.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:([0-9]*),.*/, "$1");
          self.responseText = self.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/, "$1");
          self.responseXML = self.responseText;
          setState(self.DONE);
        }
      }
    };

    /**
     * Called when an error is encountered to deal with it.
     */
    this.handleError = function(error) {
      this.status = 503;
      this.statusText = error;
      this.responseText = error.stack;
      this.responseXML = error.stack;
      errorFlag = true;
      setState(this.DONE);
    };

    /**
     * Aborts a request.
     */
    this.abort = function() {
      if (request) {
        request.abort();
        request = null;
      }

      headers = defaultHeaders;
      this.responseText = "";
      this.responseXML = "";

      errorFlag = true;

      if (this.readyState !== this.UNSENT
          && (this.readyState !== this.OPENED || sendFlag)
          && this.readyState !== this.DONE) {
        sendFlag = false;
        setState(this.DONE);
      }
      this.readyState = this.UNSENT;
    };

    /**
     * Adds an event listener. Preferred method of binding to events.
     */
    this.addEventListener = function(event, callback) {
      if (!(event in listeners)) {
        listeners[event] = [];
      }
      // Currently allows duplicate callbacks. Should it?
      listeners[event].push(callback);
    };

    /**
     * Remove an event callback that has already been bound.
     * Only works on the matching funciton, cannot be a copy.
     */
    this.removeEventListener = function(event, callback) {
      if (event in listeners) {
        // Filter will return a new array with the callback removed
        listeners[event] = listeners[event].filter(function(ev) {
          return ev !== callback;
        });
      }
    };

    /**
     * Dispatch any events, including both "on" methods and events attached using addEventListener.
     */
    this.dispatchEvent = function(event) {
      if (typeof self["on" + event] === "function") {
        self["on" + event]();
      }
      if (event in listeners) {
        for (var i = 0, len = listeners[event].length; i < len; i++) {
          listeners[event][i].call(self);
        }
      }
    };

    /**
     * Changes readyState and calls onreadystatechange.
     *
     * @param int state New state
     */
    var setState = function(state) {
      if (self.readyState !== state) {
        self.readyState = state;

        if (settings.async || self.readyState < self.OPENED || self.readyState === self.DONE) {
          self.dispatchEvent("readystatechange");
        }

        if (self.readyState === self.DONE && !errorFlag) {
          self.dispatchEvent("load");
          // @TODO figure out InspectorInstrumentation::didLoadXHR(cookie)
          self.dispatchEvent("loadend");
        }
      }
    };
  };
};

module.exports = construct(require("http"), require("https"));


text:
package com.betfair.testing.utils.misc;

import com.betfair.testing.utils.cougar.misc.TimingHelpers;
import org.junit.Test;

import static junit.framework.Assert.assertEquals;

/**
 *
 */
public class TestTimingHelpers {

    @Test
    public void summerTimeUTCConversion() {
        String date1 = TimingHelpers.convertUTCDateTimeToCougarFormat((int) 2009, (int) 6, (int) 1, (int) 13, (int) 50, (int) 0, (int) 0);
        assertEquals("2009-06-01T13:50:00.000Z",date1);
    }
}

redpajama_set_name: RedPajamaGithub


text:
module GreenhouseIoc

  autoload :VERSION,              'greenhouse_ioc/version'
  autoload :Kernel,                'greenhouse_ioc/kernel'

end


text:
using System.Collections.ObjectModel;
using EcsRx.Entities;

namespace EcsRx.Lookups
{
    public class EntityLookup : KeyedCollection<int, IEntity>
    {
        protected override int GetKeyForItem(IEntity item) => item.Id;

        public IEntity GetByIndex(int index) => Items[index];
    }
}


text:
<#
.Synopsis
    Uploads from a VSTS release build layout to python.org
.Description
    Given the downloaded/extracted build artifact from a release
    build run on python.visualstudio.com, this script uploads
    the files to the correct locations.
.Parameter build
    The location on disk of the extracted build artifact.
.Parameter user
    The username to use when logging into the host.
.Parameter server
    The host or PuTTY session name.
.Parameter target
    The subdirectory on the host to copy files to.
.Parameter tests
    The path to run download tests in.
.Parameter doc_htmlhelp
    Optional path besides -build to locate CHM files.
.Parameter embed
    Optional path besides -build to locate ZIP files.
.Parameter skipupload
    Skip uploading
.Parameter skippurge
    Skip purging the CDN
.Parameter skiptest
    Skip the download tests
.Parameter skiphash
    Skip displaying hashes
#>
param(
    [Parameter(Mandatory=$true)][string]$build,
    [Parameter(Mandatory=$true)][string]$user,
    [string]$server="python-downloads",
    [string]$target="/srv/www.python.org/ftp/python",
    [string]$tests=${env:TEMP},
    [string]$doc_htmlhelp=$null,
    [string]$embed=$null,
    [switch]$skipupload,
    [switch]$skippurge,
    [switch]$skiptest,
    [switch]$skiphash
)

if (-not $build) { throw "-build option is required" }
if (-not $user) { throw "-user option is required" }

$tools = $script:MyInvocation.MyCommand.Path | Split-Path -parent;

if (-not ((Test-Path "$build\win32\python-*.exe") -or (Test-Path "$build\amd64\python-*.exe"))) {
    throw "-build argument does not look like a 'build' directory"
}

function find-putty-tool {
    param ([string]$n)
    $t = gcm $n -EA 0
    if (-not $t) { $t = gcm ".\$n" -EA 0 }
    if (-not $t) { $t = gcm "${env:ProgramFiles}\PuTTY\$n" -EA 0 }
    if (-not $t) { $t = gcm "${env:ProgramFiles(x86)}\PuTTY\$n" -EA 0 }
    if (-not $t) { throw "Unable to locate $n.exe. Please put it on $PATH" }
    return gi $t.Path
}

$p = gci -r "$build\python-*.exe" | `
    ?{ $_.Name -match '^python-(\d+\.\d+\.\d+)((a|b|rc)\d+)?-.+' } | `
    select -first 1 | `
    %{ $Matches[1], $Matches[2] }

"Uploading version $($p[0]) $($p[1])"
"  from: $build"
"    to: $($server):$target/$($p[0])"
""

if (-not $skipupload) {
    # Upload files to the server
    $pscp = find-putty-tool "pscp"
    $plink = find-putty-tool "plink"

    "Upload using $pscp and $plink"
    ""

    if ($doc_htmlhelp) {
        pushd $doc_htmlhelp
    } else {
        pushd $build
    }
    $chm = gci python*.chm, python*.chm.asc
    popd

    $d = "$target/$($p[0])/"
    & $plink -batch $user@$server mkdir $d
    & $plink -batch $user@$server chgrp downloads $d
    & $plink -batch $user@$server chmod g-x,o+rx $d
    & $pscp -batch $chm.FullName "$user@${server}:$d"
    if (-not $?) { throw "Failed to upload $chm" }

    $dirs = gci "$build" -Directory
    if ($embed) {
        $dirs = ($dirs, (gi $embed)) | %{ $_ }
    }

    foreach ($a in $dirs) {
        "Uploading files from $($a.FullName)"
        pushd "$($a.FullName)"
        $exe = gci *.exe, *.exe.asc, *.zip, *.zip.asc
        $msi = gci *.msi, *.msi.asc, *.msu, *.msu.asc
        popd

        if ($exe) {
            & $pscp -batch $exe.FullName "$user@${server}:$d"
            if (-not $?) { throw "Failed to upload $exe" }
        }

        if ($msi) {
            $sd = "$d$($a.Name)$($p[1])/"
            & $plink -batch $user@$server mkdir $sd
            & $plink -batch $user@$server chgrp downloads $sd
            & $plink -batch $user@$server chmod g-x,o+rx $sd
            & $pscp -batch $msi.FullName "$user@${server}:$sd"
            if (-not $?) { throw "Failed to upload $msi" }
            & $plink -batch $user@$server chgrp downloads $sd*
            & $plink -batch $user@$server chmod g-x,o+r $sd*
        }
    }

    & $plink -batch $user@$server chgrp downloads $d*
    & $plink -batch $user@$server chmod g-x,o+r $d*
    & $pscp -ls "$user@${server}:$d"
}

if (-not $skippurge) {
    # Run a CDN purge
    py $tools\purge.py "$($p[0])$($p[1])"
}

if (-not $skiptest) {
    # Use each web installer to produce a layout. This will download
    # each referenced file and validate their signatures/hashes.
    gci "$build\*-webinstall.exe" -r -File | %{
        $d = mkdir "$tests\$($_.BaseName)" -Force
        gci $d -r -File | del
        $ic = copy $_ $d -PassThru
        "Checking layout for $($ic.Name)"
        Start-Process -wait $ic "/passive", "/layout", "$d\layout", "/log", "$d\log\install.log"
        if (-not $?) {
            Write-Error "Failed to validate layout of $($inst.Name)"
        }
    }
}

if (-not $skiphash) {
    # Display MD5 hash and size of each downloadable file
    pushd $build
    $files = gci python*.chm, *\*.exe, *\*.zip
    if ($doc_htmlhelp) {
        cd $doc_htmlhelp
        $files = ($files, (gci python*.chm)) | %{ $_ }
    }
    if ($embed) {
        cd $embed
        $files = ($files, (gci *.zip)) | %{ $_ }
    }
    popd

    $hashes = $files | `
        Sort-Object Name | `
        Format-Table Name, @{Label="MD5"; Expression={(Get-FileHash $_ -Algorithm MD5).Hash}}, Length -AutoSize | `
        Out-String -Width 4096
    $hashes | clip
    $hashes
}


text:
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"><title>Infinity</title>

Infinity()

语法

Result.f = Infinity()

概要

Returns the special floating-point value representing positive infinity. Negative infinity can
be calculated using "-Infinity()".

参数

无.

返回值

Returns the value representing infinity. The result is a float or double value depending on whether
it is assigned to a float or double variable.

备注

Infinity and negative infinity are special values. They behave in calculations in the way you would
generally expect. For example dividing infinity by any positive number (except 0 or infinity) will result in
infinity again. The IsInfinity() function can be used to check if a value represents
positive or negative infinity.

示例

  Debug IsInfinity(Infinity() / 1000) ; will display 1

参阅

IsInfinity(), NaN()

已支持操作系统
所有

<- Exp() - Math Index - Int() ->


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

package kr.co.bitnine.octopus.schema.metamodel;

import kr.co.bitnine.octopus.meta.model.MetaTable;
import kr.co.bitnine.octopus.schema.OctopusTable;
import org.apache.calcite.linq4j.AbstractEnumerable;
import org.apache.calcite.linq4j.Enumerable;
import org.apache.calcite.linq4j.QueryProvider;
import org.apache.calcite.linq4j.Queryable;
import org.apache.calcite.linq4j.tree.Expression;
import org.apache.calcite.linq4j.Enumerator;
import org.apache.calcite.plan.RelOptTable;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.schema.SchemaPlus;
import org.apache.calcite.schema.Schemas;
import org.apache.calcite.schema.TranslatableTable;
import org.apache.calcite.schema.impl.AbstractTableQueryable;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public final class OctopusMetaModelTable extends OctopusTable
        implements TranslatableTable {
    private static final Log LOG = LogFactory.getLog(OctopusMetaModelTable.class);
    private OctopusMetaModelDataSource dataSource;
    private OctopusMetaModelTableScan octopusMetaModelTableScan;

    public OctopusMetaModelTable(MetaTable metaTable, OctopusMetaModelSchema schema) {
        super(metaTable, schema);

        dataSource = (OctopusMetaModelDataSource) schema.getDataSource();

        LOG.debug("create OctopusMetaModelTable. tableName: " + getName());
    }

    @Override
    public String toString() {
        return "MetaModelTable {" + getName() + "}";
    }

    @Override
    public <T> Queryable<T> asQueryable(QueryProvider queryProvider,
                                        SchemaPlus schema, String tableName) {
        return new OctopusMetaModelQueryable<T>(queryProvider, schema, this, tableName);
    }

    @Override
    public RelNode toRel(RelOptTable.ToRelContext context, RelOptTable relOptTable) {
        octopusMetaModelTableScan = new OctopusMetaModelTableScan(context.getCluster(), relOptTable);
        return octopusMetaModelTableScan;
    }

    public Expression getExpression(SchemaPlus schema, String tableName,
                                    Class clazz) {
        return Schemas.tableExpression(schema, getElementType(), tableName, clazz);
    }

    public Enumerable<Object> project() {
        return new AbstractEnumerable<Object>() {
            public Enumerator<Object> enumerator() {
                return new OctopusMetaModelEnumerator(dataSource, getName(), octopusMetaModelTableScan);
            }
        };
    }

    private class OctopusMetaModelQueryable<T> extends AbstractTableQueryable<T> {
        OctopusMetaModelQueryable(QueryProvider queryProvider, SchemaPlus schema,
                                  OctopusMetaModelTable table, String tableName) {
            super(queryProvider, schema, table, tableName);
        }

        @Override
        public Enumerator<T> enumerator() {
            final Enumerable<T> enumerable =
                    (Enumerable<T>) getTable().project();
            return enumerable.enumerator();
        }

        private OctopusMetaModelTable getTable() {
            return (OctopusMetaModelTable) table;
        }
    }
}


text:
package io.gravitee.common.util;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EmptySource;
import org.junit.jupiter.params.provider.ValueSource;

/**
 * @author Yann TAVERNIER (yann.tavernier at graviteesource.com)
 * @author GraviteeSource Team
 */
class LinkedMultiValueMapTest {

    Map<String, KeyObject> testObjectHolder;

    @BeforeEach
    void setUp() {
        testObjectHolder = new HashMap<>();
        testObjectHolder.put("first", new KeyObject());
        testObjectHolder.put("second", new KeyObject());
        testObjectHolder.put("third", new KeyObject());
        testObjectHolder.put("fourth", new KeyObject());
    }

    @ParameterizedTest
    @ValueSource(strings = { "first", "second", "third" })
    public void shouldContainsKeyCaseInsensitive(String keyName) {
        final LinkedMultiValueMap<KeyObject, String> map = new LinkedMultiValueMap<>();
        map.set(testObjectHolder.get("first"), "value");
        map.set(testObjectHolder.get("second"), "value");
        map.set(testObjectHolder.get("third"), "value");

        assertThat(map.containsKey(testObjectHolder.get(keyName))).isTrue();
    }

    @ParameterizedTest
    @ValueSource(strings = { "first,fifth", "fifth", "fourth,first,third,second,fifth" })
    public void shouldNotContainsAllKeysCaseInsensitive(String keysName) {
        final LinkedMultiValueMap<KeyObject, String> map = new LinkedMultiValueMap<>();
        map.set(testObjectHolder.get("first"), "value");
        map.set(testObjectHolder.get("second"), "value");
        map.set(testObjectHolder.get("third"), "value");
        map.set(testObjectHolder.get("fourth"), "value");

        final List<KeyObject> toBeContained = Arrays
            .stream(keysName.split(","))
            .map(key -> testObjectHolder.get(key))
            .collect(Collectors.toList());

        assertThat(map.containsAllKeys(toBeContained)).isFalse();
    }

    @ParameterizedTest
    @ValueSource(strings = { "first,second", "first", "first,third,second", "fourth,first,third,second" })
    public void shouldContainsAllKeysCaseInsensitive(String keysName) {
        final LinkedMultiValueMap<KeyObject, String> map = new LinkedMultiValueMap<>();
        map.set(testObjectHolder.get("first"), "value");
        map.set(testObjectHolder.get("second"), "value");
        map.set(testObjectHolder.get("third"), "value");
        map.set(testObjectHolder.get("fourth"), "value");

        final List<KeyObject> toBeContained = Arrays
            .stream(keysName.split(","))
            .map(key -> testObjectHolder.get(key))
            .collect(Collectors.toList());

        assertThat(map.containsAllKeys(toBeContained)).isTrue();
    }

    @ParameterizedTest
    @EmptySource
    public void shouldContainsAllKeysCaseInsensitiveEmptyParameter(List<KeyObject> keys) {
        final LinkedMultiValueMap<KeyObject, String> map = new LinkedMultiValueMap<>();
        map.set(testObjectHolder.get("first"), "value");
        map.set(testObjectHolder.get("second"), "value");
        map.set(testObjectHolder.get("third"), "value");
        map.set(testObjectHolder.get("fourth"), "value");

        assertThat(map.containsAllKeys(keys)).isTrue();
    }

    private static class KeyObject {

        public KeyObject() {}
    }
}


text:
require_relative 'spec_helper'

describe '#HTML Element Label' do

  before(:each) do
    file = File.join(File.dirname(__FILE__),"../","htdocs/label.html")
    @page = @metz.get "file://#{file}"
  end

  it 'should display a label' do
    label = @page.labels.first
    expect(label.text).to eq 'Label'
  end

end


text:
app.service('webModelerStencilService', [ 'webModelerConfigService',
    function (config) {

        joint.shapes.bpmn.Flow2 = joint.shapes.bpmn.Flow.extend({

            defaults: _.defaultsDeep({
                router: {
                    name: 'normal'
                },
                connector: {
                    name: 'normal'
                }
            }, joint.shapes.bpmn.Flow.prototype.defaults)
        });

        /**
         * Stencil
         */
        var startShape = new joint.shapes.bpmn.Event({
            attrs: {
                '.': {
                    'data-tooltip': '시작'
                },
                '.label': {
                    text: '',
                    'ref-dy': '13'
                }
            },
            eventType: "start",
            custom: {
                changeOnPaperList: [
                    {
                        target: 'attrs/.label/text',
                        value: 'start'
                    }
                ],
                clickedAction: config.CONSTANT.CLICKED_ACTION.INSPECTOR
            }
        });

        var endShape = new joint.shapes.bpmn.Event({
            attrs: {
                '.': {
                    'data-tooltip': '끝'
                },
                '.label': {
                    text: '',
                    'ref-dy': '13'
                }
            },
            eventType: "end",
            custom: {
                changeOnPaperList: [
                    {
                        target: 'attrs/.label/text',
                        value: 'end'
                    }
                ]
            },
            custom: {
                clickedAction: config.CONSTANT.CLICKED_ACTION.INSPECTOR
            }
        });

        var activityShape = new joint.shapes.bpmn.Activity({
            attrs: {
                '.': {
                    'data-tooltip': '단위업무'
                }
            },
            custom: {
                clickedAction: config.CONSTANT.CLICKED_ACTION.POPUP,
                notationType: config.CONSTANT.ACTS_TYPE.ACTIVITY
            }
        });

        var subActivityShape = new joint.shapes.bpmn.Activity({
            attrs: {
                '.': {
                    'data-tooltip': '연관업무'
                }
            },
            subProcess: true,
            custom: {
                clickedAction: config.CONSTANT.CLICKED_ACTION.POPUP,
                notationType: config.CONSTANT.ACTS_TYPE.SUB_PROC
            }
        });

        var callActivityShape = new joint.shapes.bpmn.Activity({
            attrs: {
                '.': {
                    'data-tooltip': '외부단위업무'
                }
            },
            activityType: 'call-activity',
            custom: {
                clickedAction: config.CONSTANT.CLICKED_ACTION.POPUP,
                notationType: config.CONSTANT.ACTS_TYPE.EXT_ACTIVITY
            }
        });

        var callSubActivityShape = new joint.shapes.bpmn.Activity({
            attrs: {
                '.': {
                    'data-tooltip': '외부연관업무'
                }
            },
            subProcess: true,
            activityType: 'call-activity',
            custom: {
                clickedAction: config.CONSTANT.CLICKED_ACTION.POPUP,
                notationType: config.CONSTANT.ACTS_TYPE.EXT_SUB_PROC
            }
        });

        var gatewayShape = new joint.shapes.bpmn.Gateway({
            attrs: {
                '.': {
                    'data-tooltip': '게이트웨이'
                },
                '.label': {
                    text: '',
                    'ref-dy': '13'
                }
            },
            custom: {
                clickedAction: config.CONSTANT.CLICKED_ACTION.POPUP,
                notationType: config.CONSTANT.ACTS_TYPE.TRANSITION
            }
        });

        /* pool 해드 제거 */
        joint.shapes.bpmn.Pool.prototype.markup = [
            '<g class="rotatable">',
            '<g class="scalable"><rect class="body"/></g>',
            '<svg overflow="hidden" class="blackbox-wrap"><text class="blackbox-label"/></svg>',
            '<g class="lanes"/>', "</g>"
        ].join("");

        joint.shapes.bpmn.PoolView.prototype.renderLanes = function(a) {
            a = a || {}, this.index = 0;
            var b = _.isUndefined(a.headerWidth) ? this.options.headerWidth : a.headerWidth;
            if (a.label === 'REMOVE_POOL_HEADER') b = 1;
            this.lanesAttrs = {
                ".header": {
                    width: b
                },
                ".label": {
                    text: a.label || ""
                }
            }, this.$lanes.empty(), a.sublanes && this.renderSublanes(a.sublanes, b, 0, 1, "lanes"), this.update(this.model, _.merge({}, this.model.get("attrs"), this.lanesAttrs))
        }

        var poolShape = new joint.shapes.bpmn.Pool({
            attrs: {
                '.': {
                    magnet: false,
                    'data-tooltip': '풀'
                },
                '.header': {
                    fill: '#5799DA'
                },
                ".lane-header": {
                    fill: "#5799DA"
                },
                '.lane-label': {
                    fill: 'none'
                }
            },
            lanes: {
                label: 'REMOVE_POOL_HEADER',
                sublanes: [
                    {
                        label: 'lane 1',
                        name: 'myClass' // this lane has an unique css class and therefore can be targeted
                                        // in attrs above
                    },
                    {
                        label: 'lane 2',
                        name: 'myClass' // this lane has an unique css class and therefore can be targeted
                                        // in attrs above
                    },
                    {
                        label: 'lane 3',
                        name: 'myClass' // this lane has an unique css class and therefore can be targeted
                                        // in attrs above
                    }
                ]
            },
            custom: {
                changeOnPaperList: [
                    {
                        target: 'attrs/.lane-label/fill',
                        value: '#000'
                    }
                ],
                clickedAction: config.CONSTANT.CLICKED_ACTION.INSPECTOR
            }
        });

        var annotationShape = new joint.shapes.bpmn.Annotation({
            attrs: {
                '.': {
                    magnet: false,
                    'data-tooltip': '주석'
                }
            },
            custom: {
                clickedAction: config.CONSTANT.CLICKED_ACTION.INSPECTOR
            }
        });

        var groupShape = new joint.shapes.bpmn.Group({
            attrs: {
                '.': {
                    magnet: false,
                    'data-tooltip': '그룹'
                },
                '.label': {
                    text: 'Group'
                }
            },
            custom: {
                clickedAction: config.CONSTANT.CLICKED_ACTION.INSPECTOR
            }
        });

        var choreographyShape = new joint.shapes.bpmn.Choreography({
            attrs: {
                '.': {
                    magnet: false,
                    'data-tooltip': 'Choreography'
                }
            },
            participants: ['Participant 1', 'Participant 2'],
            custom: {
                clickedAction: config.CONSTANT.CLICKED_ACTION.INSPECTOR
            }
        });

        var dataObjectShape = new joint.shapes.bpmn.DataObject({
            attrs: {
                '.': {
                    magnet: false,
                    'data-tooltip': '데이터'
                }
            },
            custom: {
                clickedAction: config.CONSTANT.CLICKED_ACTION.INSPECTOR
            }
        });

        joint.shapes.bpmn.System = joint.dia.Element.extend({

            markup: '<g class="rotatable"><g class="scalable">'
            + '<path class="body" d="M-11.06,-12.36v5q0,1,4,1t4,-1v-5q0,1,-4,1t-4,-1q0,-1,4,-1t4,1t-4,1t-4,-1Z" style="fill:#fff; stroke:black; vector-effect:non-scaling-stroke;stroke-width:1px;" id="e1_shape" transform="matrix(7.5 0 0 7.5 83 100.25)"></path>'
            + '</g><text class="label"/></g>',

            defaults: joint.util.deepSupplement({

                type: 'bpmn.System',
                size: {
                    width: 60,
                    height: 80
                },
                attrs: {
                    '.body': {
                        points: '20,0 60,0 60,80 0,80 0,20 20,0 20,20 0,20',
                        stroke: '#000000',
                        fill: '#ffffff'
                    },
                    '.label': {
                        ref: '.body',
                        'ref-x': .5,
                        'ref-dy': 5,
                        text: '',
                        'text-anchor': 'middle'
                    },
                    'data-tooltip': 'system'
                }

            }, joint.dia.Element.prototype.defaults)
        });

        var systemShape = new joint.shapes.bpmn.System({
            attrs: {
                '.': {
                    magnet: false,
                    'data-tooltip': '시스템'
                }
            },
            custom: {
                clickedAction: config.CONSTANT.CLICKED_ACTION.INSPECTOR
            }
        });

        var elements = [
            activityShape,
            subActivityShape,
            callActivityShape,
            callSubActivityShape,
            gatewayShape,
            annotationShape,
            poolShape,
            dataObjectShape,
            systemShape
        ];

        function changeCellAttrOnPaper(cell) {

            var custom = cell.get('custom');
            if (!custom) return;
            var changeOnPaperList = custom.changeOnPaperList;

            for (var idx in changeOnPaperList) {
                var action = changeOnPaperList[idx];
                cell.prop(action.target, action.value);
            }
        }

        function changeCellSizeOnPaper(cell) {

            var type = cell.get('type');

            // some types of the elements need resizing after they are dropped
            var sizeMultiplier = {
                'bpmn.Pool': 8,
                'bpmn.Choreography': 2,
                'bpmn.Activity': 2
            }[type];

            if (sizeMultiplier) {
                var originalSize = cell.get('size');
                cell.set('size', {
                    width: originalSize.width * sizeMultiplier,
                    height: originalSize.height * sizeMultiplier
                }, {
                    silent: true
                });

                // Selector `foreignObject' doesn't work accross all browsers, we'r using class selector instead.
                // We have to clone size as we don't want attributes.div.style to be same object as attributes.size.
                var size = {
                    width: originalSize.width * sizeMultiplier,
                    height: originalSize.height * sizeMultiplier
                };

                cell.attr({
                    ".fobj": joint.util.assign({}, size),
                    div: {
                        style: joint.util.assign({}, size)
                    }
                });
            }
        }

        function getStencilElement(elementName) {
            switch (elementName) {
                case 'bpmn.Pool': return poolShape; break;
            }
        }

        return {
            elements: elements,
            changeCellAttrOnPaper: changeCellAttrOnPaper,
            changeCellSizeOnPaper: changeCellSizeOnPaper,
            getStencilElement: getStencilElement
        }
    }]);


text:
#ifndef _TEMPLATE_EXALGO_H
#define _TEMPLATE_EXALGO_H

#include "defines.h"
#include "dr_api.h"

/* typdefs */

/*instrumentation routines*/

/* for the entire process */
void <client_name>_init(client_id_t id, const char * name,
	const char * arguments);
void <client_name>_exit_event(void);

/* for basic blocks */
dr_emit_flags_t <client_name>_bb_instrumentation(void *drcontext, void *tag, instrlist_t *bb,
	instr_t *instr, bool for_trace, bool translating,
	void *user_data);
dr_emit_flags_t
<client_name>_bb_analysis(void *drcontext, void *tag, instrlist_t *bb,
bool for_trace, bool translating,
OUT void **user_data);
dr_emit_flags_t
<client_name>_bb_app2app(void *drcontext, void *tag, instrlist_t *bb,
bool for_trace, bool translating);

/* for threads */
void <client_name>_thread_init(void *drcontext);
void <client_name>_thread_exit(void *drcontext);

#endif


text:
/**
 * Provide common utils for parser implementation.
 */
package org.onosproject.yangutils.parser.impl.parserutils;


text:
package me.mazeika.explodingkittens.game.states;

import javax.annotation.ParametersAreNonnullByDefault;

@ParametersAreNonnullByDefault
public interface IAbstractGameStateManager extends GameStateManager
{
    /**
     * Switches to the state specified by the registered class of the state.
     * Appropriate begin and end methods are called and commands are registered
     * and unregistered where needed.
     *
     * @param clazz the registered class of the state to switch to
     */
    void switchTo(Class clazz);

    /**
     * Begins the current state.
     */
    void beginCurrent();

    /**
     * Ends the current state.
     */
    void endCurrent();
}


text:
package com.svbio.cloudkeeper.model.runtime.element;

import com.svbio.cloudkeeper.model.Immutable;
import com.svbio.cloudkeeper.model.bare.element.BarePackage;
import com.svbio.cloudkeeper.model.util.ImmutableList;

import java.net.URI;

/**
 * Linked and verified CloudKeeper package.
 */
public interface RuntimePackage extends RuntimeElement, BarePackage, Immutable {
    @Override
    ImmutableList<? extends RuntimePluginDeclaration> getDeclarations();

    /**
     * Returns the name of the bundle that provides this pacakge.
     *
     * @return name of bundle that provides this package, guaranteed to be non-null
     * @see RuntimeBundle#getBundleIdentifier()
     */
    URI getBundleIdentifier();
}


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

package com.google.cloud.aiplatform.v1;

public final class PredictionServiceProto {
  private PredictionServiceProto() {}

  public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {}

  public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) {
    registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry);
  }

  static final com.google.protobuf.Descriptors.Descriptor
      internal_static_google_cloud_aiplatform_v1_PredictRequest_descriptor;
  static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_cloud_aiplatform_v1_PredictRequest_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
      internal_static_google_cloud_aiplatform_v1_PredictResponse_descriptor;
  static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_cloud_aiplatform_v1_PredictResponse_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
      internal_static_google_cloud_aiplatform_v1_RawPredictRequest_descriptor;
  static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_cloud_aiplatform_v1_RawPredictRequest_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
      internal_static_google_cloud_aiplatform_v1_ExplainRequest_descriptor;
  static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_cloud_aiplatform_v1_ExplainRequest_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
      internal_static_google_cloud_aiplatform_v1_ExplainResponse_descriptor;
  static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_cloud_aiplatform_v1_ExplainResponse_fieldAccessorTable;

  public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() {
    return descriptor;
  }

  private static com.google.protobuf.Descriptors.FileDescriptor descriptor;

  static {
    java.lang.String[] descriptorData = {
      "\n3google/cloud/aiplatform/v1/prediction_"
          + "service.proto\022\032google.cloud.aiplatform.v"
          + "1\032\034google/api/annotations.proto\032\027google/"
          + "api/client.proto\032\037google/api/field_behav"
          + "ior.proto\032\031google/api/httpbody.proto\032\031go"
          + "ogle/api/resource.proto\032,google/cloud/ai"
          + "platform/v1/explanation.proto\032\034google/pr"
          + "otobuf/struct.proto\"\252\001\n\016PredictRequest\022<"
          + "\n\010endpoint\030\001 \001(\tB*\340A\002\372A$\n\"aiplatform.goo"
          + "gleapis.com/Endpoint\022.\n\tinstances\030\002 \003(\0132"
          + "\026.google.protobuf.ValueB\003\340A\002\022*\n\nparamete"
          + "rs\030\003 \001(\0132\026.google.protobuf.Value\"\321\001\n\017Pre"
          + "dictResponse\022+\n\013predictions\030\001 \003(\0132\026.goog"
          + "le.protobuf.Value\022\031\n\021deployed_model_id\030\002"
          + " \001(\t\0226\n\005model\030\003 \001(\tB\'\340A\003\372A!\n\037aiplatform."
          + "googleapis.com/Model\022\035\n\020model_version_id"
          + "\030\005 \001(\tB\003\340A\003\022\037\n\022model_display_name\030\004 \001(\tB"
          + "\003\340A\003\"z\n\021RawPredictRequest\022<\n\010endpoint\030\001 "
          + "\001(\tB*\340A\002\372A$\n\"aiplatform.googleapis.com/E"
          + "ndpoint\022\'\n\thttp_body\030\002 \001(\0132\024.google.api."
          + "HttpBody\"\235\002\n\016ExplainRequest\022<\n\010endpoint\030"
          + "\001 \001(\tB*\340A\002\372A$\n\"aiplatform.googleapis.com"
          + "/Endpoint\022.\n\tinstances\030\002 \003(\0132\026.google.pr"
          + "otobuf.ValueB\003\340A\002\022*\n\nparameters\030\004 \001(\0132\026."
          + "google.protobuf.Value\022V\n\031explanation_spe"
          + "c_override\030\005 \001(\01323.google.cloud.aiplatfo"
          + "rm.v1.ExplanationSpecOverride\022\031\n\021deploye"
          + "d_model_id\030\003 \001(\t\"\230\001\n\017ExplainResponse\022=\n\014"
          + "explanations\030\001 \003(\0132\'.google.cloud.aiplat"
          + "form.v1.Explanation\022\031\n\021deployed_model_id"
          + "\030\002 \001(\t\022+\n\013predictions\030\003 \003(\0132\026.google.pro"
          + "tobuf.Value2\274\005\n\021PredictionService\022\310\001\n\007Pr"
          + "edict\022*.google.cloud.aiplatform.v1.Predi"
          + "ctRequest\032+.google.cloud.aiplatform.v1.P"
          + "redictResponse\"d\202\323\344\223\002>\"9/v1/{endpoint=pr"
          + "ojects/*/locations/*/endpoints/*}:predic"
          + "t:\001*\332A\035endpoint,instances,parameters\022\257\001\n"
          + "\nRawPredict\022-.google.cloud.aiplatform.v1"
          + ".RawPredictRequest\032\024.google.api.HttpBody"
          + "\"\\\202\323\344\223\002A\"</v1/{endpoint=projects/*/locat"
          + "ions/*/endpoints/*}:rawPredict:\001*\332A\022endp"
          + "oint,http_body\022\332\001\n\007Explain\022*.google.clou"
          + "d.aiplatform.v1.ExplainRequest\032+.google."
          + "cloud.aiplatform.v1.ExplainResponse\"v\202\323\344"
          + "\223\002>\"9/v1/{endpoint=projects/*/locations/"
          + "*/endpoints/*}:explain:\001*\332A/endpoint,ins"
          + "tances,parameters,deployed_model_id\032M\312A\031"
          + "aiplatform.googleapis.com\322A.https://www."
          + "googleapis.com/auth/cloud-platformB\332\001\n\036c"
          + "om.google.cloud.aiplatform.v1B\026Predictio"
          + "nServiceProtoP\001ZDgoogle.golang.org/genpr"
          + "oto/googleapis/cloud/aiplatform/v1;aipla"
          + "tform\252\002\032Google.Cloud.AIPlatform.V1\312\002\032Goo"
          + "gle\\Cloud\\AIPlatform\\V1\352\002\035Google::Cloud:"
          + ":AIPlatform::V1b\006proto3"
    };
    descriptor =
        com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(
            descriptorData,
            new com.google.protobuf.Descriptors.FileDescriptor[] {
              com.google.api.AnnotationsProto.getDescriptor(),
              com.google.api.ClientProto.getDescriptor(),
              com.google.api.FieldBehaviorProto.getDescriptor(),
              com.google.api.HttpBodyProto.getDescriptor(),
              com.google.api.ResourceProto.getDescriptor(),
              com.google.cloud.aiplatform.v1.ExplanationProto.getDescriptor(),
              com.google.protobuf.StructProto.getDescriptor(),
            });
    internal_static_google_cloud_aiplatform_v1_PredictRequest_descriptor =
        getDescriptor().getMessageTypes().get(0);
    internal_static_google_cloud_aiplatform_v1_PredictRequest_fieldAccessorTable =
        new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
            internal_static_google_cloud_aiplatform_v1_PredictRequest_descriptor,
            new java.lang.String[] {
              "Endpoint", "Instances", "Parameters",
            });
    internal_static_google_cloud_aiplatform_v1_PredictResponse_descriptor =
        getDescriptor().getMessageTypes().get(1);
    internal_static_google_cloud_aiplatform_v1_PredictResponse_fieldAccessorTable =
        new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
            internal_static_google_cloud_aiplatform_v1_PredictResponse_descriptor,
            new java.lang.String[] {
              "Predictions", "DeployedModelId", "Model", "ModelVersionId", "ModelDisplayName",
            });
    internal_static_google_cloud_aiplatform_v1_RawPredictRequest_descriptor =
        getDescriptor().getMessageTypes().get(2);
    internal_static_google_cloud_aiplatform_v1_RawPredictRequest_fieldAccessorTable =
        new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
            internal_static_google_cloud_aiplatform_v1_RawPredictRequest_descriptor,
            new java.lang.String[] {
              "Endpoint", "HttpBody",
            });
    internal_static_google_cloud_aiplatform_v1_ExplainRequest_descriptor =
        getDescriptor().getMessageTypes().get(3);
    internal_static_google_cloud_aiplatform_v1_ExplainRequest_fieldAccessorTable =
        new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
            internal_static_google_cloud_aiplatform_v1_ExplainRequest_descriptor,
            new java.lang.String[] {
              "Endpoint", "Instances", "Parameters", "ExplanationSpecOverride", "DeployedModelId",
            });
    internal_static_google_cloud_aiplatform_v1_ExplainResponse_descriptor =
        getDescriptor().getMessageTypes().get(4);
    internal_static_google_cloud_aiplatform_v1_ExplainResponse_fieldAccessorTable =
        new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
            internal_static_google_cloud_aiplatform_v1_ExplainResponse_descriptor,
            new java.lang.String[] {
              "Explanations", "DeployedModelId", "Predictions",
            });
    com.google.protobuf.ExtensionRegistry registry =
        com.google.protobuf.ExtensionRegistry.newInstance();
    registry.add(com.google.api.ClientProto.defaultHost);
    registry.add(com.google.api.FieldBehaviorProto.fieldBehavior);
    registry.add(com.google.api.AnnotationsProto.http);
    registry.add(com.google.api.ClientProto.methodSignature);
    registry.add(com.google.api.ClientProto.oauthScopes);
    registry.add(com.google.api.ResourceProto.resourceReference);
    com.google.protobuf.Descriptors.FileDescriptor.internalUpdateFileDescriptor(
        descriptor, registry);
    com.google.api.AnnotationsProto.getDescriptor();
    com.google.api.ClientProto.getDescriptor();
    com.google.api.FieldBehaviorProto.getDescriptor();
    com.google.api.HttpBodyProto.getDescriptor();
    com.google.api.ResourceProto.getDescriptor();
    com.google.cloud.aiplatform.v1.ExplanationProto.getDescriptor();
    com.google.protobuf.StructProto.getDescriptor();
  }

  // @@protoc_insertion_point(outer_class_scope)
}


text:
<?php
// class to browse images in a folder (for CKEditor plugin)
// from: http://coursesweb.net/javascript/
class imgbrowse {
  // IN $root - REPLACE "/imgup" WITH THE PATH TO THE FOLDER WITH IMAGES RELATIVE TO ROOT OF YOUR WEBSITE ON SERVER
  protected $root = '/uploads/images/';
  protected $imgext = ['bmp', 'gif', 'jpg', 'jpe', 'jpeg', 'png'];    // allowed image extensions
  protected $imgdr = '';     // current folder (in $root) with images

  function __construct() {
    if(isset($_POST['imgroot'])) $this->root = trim(strip_tags($_POST['imgroot']));
    $this->root = trim($this->root, '/') .'/';
    $this->imgdr = isset($_POST['imgdr']) ? trim(trim(strip_tags($_POST['imgdr'])), '/') .'/' : '';
  }

  // return two-dimensional array with folders-list and images in specified $imgdr
  public function getMenuImgs() {
    $re = ['menu'=>'', 'imgs'=>''];
    try{
      $obdr = new DirectoryIterator($_SERVER['DOCUMENT_ROOT'] .'/'. $this->root . $this->imgdr);         // object of the dir
    }
    catch(Exception $e) {
      return '
ERROR from PHP:

'. $e->getMessage() .'

Check the $root value in imgbrowse.php to see if it is the correct path to the image folder; RELATIVE TO ROOT OF YOUR WEBSITE ON SERVER
';
    }

    // get protocol and host name to add absolute path in
    $protocol = !empty($_SERVER['HTTPS']) ? 'https://' : 'http://';
    $site = $protocol. $_SERVER['SERVER_NAME'] .'/';

    // traverse the $obdr
    foreach($obdr as $fileobj) {
      $name = $fileobj->getFilename();

      // if image file, else, directory (but not . or ..), add data in $re
      if($fileobj->isFile() && in_array($fileobj->getExtension(), $this->imgext)) $re['imgs'] .= 'root . $this->imgdr . $name .'" alt="'. $name .'" height="50" />'. $name .'';
      else if($fileobj->isDir() && !$fileobj->isDot()) $re['menu'] .= '
imgdr . $name .'">'. $name .'
';
    }
    if($re['menu'] != '') $re['menu'] = '
'. $re['menu'] .'
';
    if($re['imgs'] == '') $re['imgs'] = '
No Images
';
    return $re;
  }
}

// uses the imgbrowse class
$obj = new imgbrowse;
$content = $obj->getMenuImgs();
echo json_encode($content);


text:
ACCEPTED

#### According to
Euro+Med Plantbase

#### Published in
null

#### Original name
Anthemis oretana Carretero

### Remarks
null


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Linq;
using Tridion.ContentDelivery.AmbientData;

namespace Sdl.Web.Tridion.Context
{
    /// <summary>
    /// Based on https://github.com/NunoLinhares/TridionContextEngineWrapper/tree/master/Sdl.Tridion.Context
    /// </summary>
    public class ContextEngine
    {
        private readonly BrowserClaims _browser;
        private readonly DeviceClaims _device;
        private readonly OsClaims _os;

        public ContextEngine(Dictionary<Uri, object> claims)
        {
            _browser = new BrowserClaims(claims);
            _device = new DeviceClaims(claims);
            _os = new OsClaims(claims);
        }

        public ContextEngine()
        {
            Dictionary<Uri, object> claims = (Dictionary<Uri, object>)AmbientDataContext.CurrentClaimStore.GetAll();
            _browser = new BrowserClaims(claims);
            _device = new DeviceClaims(claims);
            _os = new OsClaims(claims);
        }

        public BrowserClaims Browser { get { return _browser; } }
        public DeviceClaims Device { get { return _device; } }
        public OsClaims Os { get { return _os; } }

        public string DeviceFamily
        {
            get { return GetDeviceFamily(); }
        }

        private string _deviceFamily;

        private string GetDeviceFamily()
        {
            // check configuration
            // evaluate conditions from top to bottom
            // return current device family

            // if families.xml does not exist will use defaults

            // YUCK

            if (_deviceFamily != null) return _deviceFamily;

            // Could use: string path = VirtualPathUtility.ToAbsolute("~/App_Data/somedata.xml");
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin", "Families.xml");
            if (File.Exists(path))
            {
                XDocument families = XDocument.Load(path);
                foreach (var i in families.Descendants("devicefamily"))
                {
                    string family = i.Attribute("name").Value;
                    bool inFamily = true;
                    foreach (var c in i.Descendants("condition"))
                    {
                        Uri uri = new Uri(c.Attribute("uri").Value);
                        string expectedValue = c.Attribute("value").Value;

                        if (expectedValue.StartsWith("<"))
                        {
                            int value = Convert.ToInt32(expectedValue.Replace("<", String.Empty));
                            int claimValue = Convert.ToInt32(AmbientDataContext.CurrentClaimStore.Get<string>(uri));
                            if (claimValue >= value)
                                inFamily = false;
                        }
                        else if (expectedValue.StartsWith(">"))
                        {
                            int value = Convert.ToInt32(expectedValue.Replace(">", String.Empty));
                            int claimValue = Convert.ToInt32(AmbientDataContext.CurrentClaimStore.Get<string>(uri));
                            if (claimValue <= value)
                                inFamily = false;
                        }
                        else
                        {
                            string stringClaimValue = AmbientDataContext.CurrentClaimStore.Get<string>(uri);
                            if (!stringClaimValue.Equals(expectedValue))
                                inFamily = false; // move on to next family
                        }
                    }
                    if (inFamily)
                    {
                        _deviceFamily = family;
                        break;
                    }
                    // Need to evaluate if all conditions are true.
                }
            }
            else
            {
                // Defaults
                if (!Device.IsMobile && !Device.IsTablet) _deviceFamily = "desktop";
                if (Device.IsTablet) _deviceFamily = "tablet";
                if (Device.IsMobile && !Device.IsTablet)
                {
                    _deviceFamily = Device.DisplayWidth > 319 ? "smartphone" : "featurephone";
                }
            }

            return _deviceFamily;
        }
    }
}


text:
/*eslint: no-extra-parens:0*/

// native imports
// ...

// libraries
import classer from 'classer';
import arginfo from 'arginfo';
import extend from 'extend';
import sparqljs from 'sparqljs';
import request from 'request';
import rapunzel from 'rapunzel';

// local modules
import overloader from './overloader';
import query_builder from './query-builder';
import n3_document from './n3-document';

//
const sparql_parser = sparqljs.Parser;

/**
* private static:
**/

// log levels
const H_LOG_LEVELS = {
	'silent': 0,
	'error': 2,
	'warn': 3,
	'info': 4,
	'debug': 5,
};

// inspried by: http://www.w3.org/TeamSubmission/n3/
const H_PREDICATE_ALIASES = new Map([
	['a', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'],
	['=', 'http://www.w3.org/2002/07/owl#sameAs'],
	['=>', 'http://www.w3.org/2000/10/swap/log#implies'],
	// ['<=', 'http://www.w3.org/2000/10/swap/log#implies'], // not supported
]);

//
const map_to_hash = (h_map) => {

	// create plain object (hash)
	var h_hash = {};

	// iterate keys of map
	for(let [s_key, z_value] of h_map) {

		// push each key/value pair to hahs
		h_hash[s_key] = z_value;
	}

	//
	return h_hash;
};

//
const P_XSD_NAMESPACE = 'http://www.w3.org/2001/XMLSchema#';

const R_TTL_LITERAL = /^"((?:[^"\\]|\\.)*)"(?:\^\^([^]+))?$/;

//
const A_VALID_TABLE_HTTP_METHODS = ['get', 'post'];
const A_VALID_GRAPH_HTTP_METHODS = ['get', 'post'];
const A_VALID_UPDATE_HTTP_METHODS = ['post', 'put'];

//
const setup_remote = (h_engine) => {

	// prepare http method to use for table-result queries
	let s_table_method = A_VALID_TABLE_HTTP_METHODS[0];

	// prepare http method to use for graph-result queries
	let s_graph_method = A_VALID_GRAPH_HTTP_METHODS[0];

	// prepare http method to use for update queries
	let s_update_method = A_VALID_UPDATE_HTTP_METHODS[0];

	// prepare results parser
	let f_parser = (s_body) => {
		return new Promise((f_resolve, f_reject) => {
			try {
				f_resolve(
					JSON.parse(s_body)
				);
			}
			catch(e) {
				f_reject('response body could not be parsed: '+e);
			}
		});
	};

	// engine gives method option
	if(h_engine.http_methods) {

		// ref http methods
		let h_http_methods = h_engine.http_methods;

		// http method to use for table-result queries
		if(h_http_methods.table) {

			// invalid http method for table-result queries
			if(-1 === A_VALID_TABLE_HTTP_METHODS.indexOf(h_http_methods.table)) {
				return local.fail('invalid HTTP method to use for table-result queries: '+h_http_methods.table);
			}

			// set http method for table-result queries
			s_table_method = h_http_methods.table;
		}

		// http method to use for graph-result queries
		if(h_http_methods.graph) {

			// ref http method
			let s_method = h_http_methods.graph.toLowerCase();

			// invalid http method for table-result queries
			if(-1 === A_VALID_GRAPH_HTTP_METHODS.indexOf(s_method)) {
				return local.fail('invalid HTTP method to use for graph-result queries: '+s_method);
			}

			// set http method for graph-result queries
			s_graph_method = s_method;
		}

		// http method to use for update queries
		if(h_http_methods.update) {

			// ref http method
			let s_method = h_http_methods.update.toLowerCase();

			// invalid http method for table-result queries
			if(-1 === A_VALID_UPDATE_HTTP_METHODS.indexOf(s_method)) {
				return local.fail('invalid HTTP method to use for update queries: '+s_method);
			}

			// set http method for graph-result queries
			s_update_method = s_method;
		}
	}

	// engine interface function
	let k_engine = (s_sparql, s_type) => {

		// prepare http method
		let s_method;

		// prepare http accept header
		let s_accept;

		// prepare http path (default to query)
		let s_path = '/query';

		// prepare http parameter for sparql string
		let s_sparql_parameter = 'query';

		// tabular result query (ASK, SELECT)
		if('table' === s_type) {
			s_method = s_table_method;
			s_accept = 'application/sparql-results+json';
		}
		// graph result query (DESCRIBE)
		else if('graph' === s_type) {
			s_method = s_graph_method;
			s_accept = 'application/ld+json';
		}
		// update action
		else if('update' === s_type) {
			s_method = s_update_method;
			s_accept = 'text/plain';
			s_path = '/update';
			s_sparql_parameter = 'update';
		}
		// invalid execution type
		else {
			return local.fail('invalid SPARQL execution type: '+s_type);
		}

		// prep url for request
		let s_url = h_engine.url + s_path;

		// prepare request options
		let h_request = {
			method: s_method,
			url: s_url,
			headers: {
				Accept: s_accept,
				'Content-Type': 'application/x-www-form-urlencoded',
			},
		};

		// set data
		let h_data = {
			[s_sparql_parameter]: s_sparql,
		};

		// GET method
		if('get' === s_method) {

			// set query string
			h_request.qs = h_data;
		}
		// POST method
		else if('post' === s_method) {

			// set form data
			h_request.form = h_data;
		}

		//
		return new Promise((f_resolve, f_reject) => {

			// wrap rejector with http request info
			let f_reject_http = (s_msg) => {
				delete h_request.form;
				f_reject(s_msg+'\nrequest: '+arginfo(h_request)+'\n\nquery: '+s_sparql);
			};

			// submit request
			request(h_request, (h_err, d_http_message, s_body) => {

				//
				if(h_err) {
					return f_reject_http(h_err);
				}

				// not okay response
				if(200 !== d_http_message.statusCode) {
					return f_reject_http('Bad HTTP response from host: '+d_http_message.statusCode+' - '+d_http_message.statusMessage+'\n\n -- Server message: --\n'+s_body+'\n');
				}

				// get content type
				let s_content_type = d_http_message.headers['content-type'].split(';')[0];

				// response is JSON
				if(s_content_type.endsWith('json')) {

					// parse body
					f_parser(s_body)
						// success
						.then((h_json) => {

							// forward to callback
							f_resolve(h_json);
						})
						// parse error
						.catch((e) => {

							// decide how to handle errors
							f_reject(e);
						});
				}
				// response is other
				else {

					// acceptable
					if('update' === s_type) {
						f_resolve(s_body);
					}
					// unacceptable
					else {
						f_reject('expected response to be JSON; instead got Content-Type: "'+s_content_type+'"');
					}
				}
			});
		});
	};

	//
	return k_engine;
};

// engine setup router
const setup_engine = (h_engine) => {

	// remote engine type
	if('remote' === h_engine.type) {
		return setup_remote(h_engine);
	}

	//
	local.fail('unknown engine type "'+h_engine.type+'": '+arginfo(h_engine));
};

/**
* class:
**/
const local = classer('Spaz', function(h_config) {

	/**
	* private:
	**/

	// log level
	let n_log_level = 0;

	// prefixes
	let hm_prologue_prefixes = new Map([

		// defaults
		['xsd', 'http://www.w3.org/2001/XMLSchema#'],
		['rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'],
		['rdfs', 'http://www.w3.org/2000/01/rdf-schema#'],
		['owl', 'http://www.w3.org/2002/07/owl#'],
	]);

	//
	const add_prefix_item = (s_name, s_iri, b_allow_override=false) => {

		// prefix already defined
		if(!b_allow_override && hm_prologue_prefixes.has(s_name)) {

			// prefixes are not identical
			if(hm_prologue_prefixes.get(s_name) !== s_iri) {

				// issue warning
				local.warn(`overwriting a global prefix will not change the final uris of prefixed names committed to the graph pattern prior! I hope you understand what this means...\n changing '${s_name}' prefix from <${hm_prologue_prefixes.get(s_name)}> to <${s_iri}>`);
			}
		}
		// prefix not yet defined
		else {
			hm_prologue_prefixes.set(s_name, s_iri);
		}
	};

	//
	const add_prologue_prefix = (z_prefix, b_init=false) => {

		// SPARQL string prefix
		if('string' === typeof z_prefix) {

			// split prefix name from iri
			let [s_name, s_iri] = z_prefix.trim().split(/\s+/);

			// match prefix regex
			let m_name = R_PREFIX.exec(s_name);

			// bad prefix name
			if(!m_name) {
				return local.fail('failed to match SPARQL prefix name: '+arginfo(s_name));
			}

			// match iri regex
			let m_iri = R_IRI.exec(s_iri);

			// bad iri
			if(!m_iri) {
				return local.fail('failed to match SPARQL prefix iri: '+arginfo(s_iri));
			}

			//
			add_prefix_item(m_name[1], m_iri[1], b_init);
		}
		// hash
		else if('object' === typeof z_prefix) {

			//
			let f_add_hash = (h_prefix) => {

				// each item
				for(let s_name in h_prefix) {

					// ref iri
					let s_iri = h_prefix[s_name];

					// assert string
					if('string' !== typeof s_iri) {
						return local.fail('prefix iri must be [string]. for "'+s_name+'" key it received: '+arginfo(s_iri));
					}

					//
					add_prefix_item(s_name, s_iri, b_init);
				}
			};

			// array
			if(Array.isArray(z_prefix)) {
				z_prefix.forEach((h_prefix) => {
					f_add_hash(h_prefix);
				});
			}
			// single hash
			else {
				f_add_hash(z_prefix);
			}
		}
		// other
		else {
			return local.fail('prefix argument must be [string] or [object]. instead got: '+arginfo(z_prefix));
		}
	};

	//
	let k_engine;

	// initialization
	(() => {

		// config
		if(h_config) {

			// verbosity
			if(h_config.verbosity) {

				// ref verbosity
				let s_verbosity = h_config.verbosity;

				// no such verbosity level
				if(!H_LOG_LEVELS.hasOwnProperty(s_verbosity)) {
					return local.fail(`no such verbosity level "${s_verbosity}"`);
				}

				// set log level
				n_log_level = H_LOG_LEVELS[s_verbosity];
			}

			// prefixes
			if(h_config.prefixes) {
				add_prologue_prefix(h_config.prefixes, true);
			}

			// engine
			if(h_config.engine) {

				// ref config engine hash
				let h_config_engine = h_config.engine;

				// prepare engine hash
				let h_engine = {};

				// remote engine
				if(h_config_engine.endpoint) {

					// set remote engine type
					h_engine.type = 'remote';

					// ref endpoint
					let z_endpoint = h_config_engine.endpoint;

					// endpoint type is string
					if('string' === typeof z_endpoint) {
						h_engine.url = z_endpoint;
					}
					// endpoint type is object
					else if('object' === typeof z_endpoint) {

						// not yet supported
						return local.fail('endpoint hash argument not yet supported');
					}
					// invalid type
					else {

						// not yet supported
						return local.fail(`unexpected 'engine.endpoint' value type: ${arginfo(z_endpoint)}`);
					}

					// set http methods
					if(h_config_engine.http_methods) {

						// ref methods
						let z_http_methods = h_config_engine.http_methods;

						// http methods type is string
						if('string' === typeof z_http_methods) {

							// ref method
							let s_method = z_http_methods.toLowerCase();

							// shortcut sets table and graph methods at once
							if(-1 !== ['get', 'post'].indexOf(s_method)) {
								h_engine.http_methods = {
									table: s_method,
									graph: s_method,
								};
							}
							// invalid shortcut name
							else {
								local.fail('no such HTTP method shortcut named "'+s_method+'"');
							}
						}
						// http methods type is object
						else if('object' === typeof z_http_methods) {

							// set directly
							h_engine.http_methods = z_http_methods;
						}
						// unknown type
						else {
							local.fail(`unexpected 'engine.http_methods' value type: ${arginfo(z_http_methods)}`);
						}
					}
				}

				// prepare descriptive hash for setting up endpoint
				k_engine = setup_engine(h_engine);
			}
		}
	})();

	/**
	* public operator() ():
	**/

	// parse a SPARQL string and return a query-builder
	let operator = function(z_query) {

		// assume SPARQL hash
		let h_query = z_query;

		// SPARQL string
		if('string' === typeof z_query) {

			// prepare to inject prefixes
			let s_injected_prefixes = '';

			// build prefix strings
			for(let [s_prefix, p_iri] of hm_prologue_prefixes) {
				s_injected_prefixes += `prefix ${s_prefix}: <${p_iri}>`;
			}

			//
			h_query = (new sparql_parser()).parse(s_injected_prefixes+z_query);
		}

		//
		return query_builder({
			parent: operator,
			type: h_query.queryType,
			query: h_query,
		});
	};

	// simple group patterns
	['group', 'union', 'minus', 'optional'].forEach((s_pattern_type) => {
		operator[s_pattern_type] = function(...a_patterns) {
			return function() {
				return this.serialize_pattern(s_pattern_type, a_patterns);
			};
		};
	});

	const spo_hash = (z_group) => {
		if(Array.isArray(z_group)) {
			return {
				subject: z_group[0],
				predicate: z_group[1],
				object: z_group[2],
			};
		}
		else {
			local.fail('unsupported group type: '+arginfo(z_group));
		}
	};

	/**
	* public:
	**/
	operator = extend(operator, {

		// adds prefixes to this instance's internal map
		prefix: overloader({

			// add new prefixes
			add: (...a_prefixes) => {
				a_prefixes.forEach(add_prologue_prefix);
			},

			// clear global prefixes, then add new ones
			clear: () => {

				// clear global prefixes
				hm_prologue_prefixes.clear();
			},

			// returns global prefixes as hash
			fetch: () => {
				return map_to_hash(hm_prologue_prefixes);
			},

			// allow getter access to underlying map
			map: hm_prologue_prefixes,
		}),

		/**
		* immediate query constructor shortcuts
		**/

		silently: {
			drop: {
				graph: (s_graph, f_okay) => {
					operator.submit(`drop silent graph <${operator.expand(s_graph)}>`, 'update', f_okay || function(){});
				},
			},
		},

		/**
		* query-builder constructor shortcuts
		**/

		// new ttl document
		ttl(...a_args) {

			// create new n3 document
			let q_document = n3_document({
				parent: operator,
				prefixes: hm_prologue_prefixes,
			});

			// args were given
			if(a_args.length) {
				// forward arguments
				q_document.add(...a_args);
			}

			// return document
			return q_document;
		},

		// new ASK query
		ask(...a_args) {

			// create new query builder
			let q_query = query_builder({
				parent: operator,
				type: 'ask',
			});

			// args were given
			if(a_args.length) {
				// forward arguments
				return q_query.where(...a_args);
			}

			// return query builder
			return q_query;
		},

		// new SELECT query
		select(...a_args) {

			// create new query builder
			let q_query = query_builder({
				parent: operator,
				type: 'select',
			});

			// args were given
			if(a_args.length) {
				// forward arguments
				return q_query.select(...a_args);
			}

			// return query builder
			return q_query;
		},

		// new DESCRIBE query
		describe(...a_args) {

			// create new query builder
			let q_query = query_builder({
				parent: operator,
				type: 'describe',
			});

			// args were given
			if(a_args.length) {
				// forward arguments
				return q_query.describe(...a_args);
			}

			// return query builder
			return q_query;
		},

		// new INSERT query
		insert: Object.defineProperties((...a_quads) => {

			///
			let q_query = query_builder({
				parent: operator,
				type: 'insert',
			});

			// args were given
			if(a_quads.length) {
				// forward arguments
				return q_query.insert(...a_quads);
			}

			// return query builder
			return q_query;
		}, {

			// new INSERT DATA query
			into: {
				enumerable: true,
				value: (...a_args) => {

					// create new query builder
					let q_query = query_builder({
						parent: operator,
						type: 'insert-data',
					});

					// args were given
					if(a_args.length) {
						// forward arguments
						return q_query.into(...a_args);
					}

					// return query builder
					return q_query;
				},
			},
		}),

		// query builder
		build(s_type) {
			switch(s_type) {
				case 'ask':
				case 'select':
					return query_builder({
						parent: operator,
						type: s_type,
					});
				case 'insert':
				case 'update':
				default:
					return exports.fail('cannot build "'+s_type+'". That alias is not recognized');
			}
		},

		/**
		* query-builder WHERE helpers
		**/

		// basic graph pattern
		bgp(a_triples) {
			return {
				type: 'bgp',
				triples: a_triples,
			};
		},

		// minus block
		minus(...a_triples) {
			return {
				type: 'minus',
				patterns: [
					{
						type: 'bgp',
						triples: a_triples.map(spo_hash),
					}
				]
			};
		},

		// graph block
		graph(s_graph_iri, ...a_triples) {
			return {
				type: 'graph',
				graph: s_graph_iri,
				patterns: [
					{
						type: 'bgp',
						triples: a_triples.map(spo_hash),
					}
				],
			};
		},

		// rdf:collection
		list(a_items) {

			// empty list
			if(!a_items.length) {
				return operator.expand('rdf:nil');
			}
			// non-empty list
			else {
				return '('+a_items.map(operator.turtle).join(' ')+')';
			}
		},

		// alias
		collection: operator.list,

		// iri
		iri(z_thing) {

			//
			if('string' === typeof z_thing) {
				return '<'+z_thing+'>';
			}
			else if('object' === typeof z_thing) {
				if('iri' === z_thing.type) {
					return '<'+(z_thing.value || z_thing.iri)+'>';
				}
				else {
					local.fail('invalid iri [object]: '+arginfo(z_thing));
				}
			}
			else {
				local.fail('invalid iri: '+arginfo(z_thing));
			}
		},

		// triple
		triple(...a_args) {

			//
			if('string' === typeof a_args[0]) {
				return ['<'+a_args[0]+'>', '<'+a_args[1]+'>', '<'+a_args[2]+'>'];
			}
			else {
				local.fail('invalid use of $$.triple');
			}
		},

		// add bind statement
		bind(s_expr, s_var) {

			//
			return {
				type: 'bind',
				variable: s_var,
				expression: s_expr,
			};
		},

		// construct a literal
		val(z_value, s_type) {

			// prep value string; default to input arg `value`
			let s_value = z_value;

			// no explicit type given
			if('undefined' === typeof s_type) {
				// boolean
				if('boolean' === typeof z_value) {
					s_type = P_XSD_NAMESPACE+'boolean';
				}
				// numeric
				else if('number' === typeof z_value) {
					// integer
					if(Number.isInteger(z_value)) {
						s_type = P_XSD_NAMESPACE+'integer';
					}
					// non-finite / NaN
					else if(isNaN(z_value) || !isFinite(z_value)) {
						return local.fail('cannot create numeric value for non-finite / NaN type: '+arginfo(z_value));
					}
					// float
					else {
						s_type = P_XSD_NAMESPACE+'decimal';
					}
				}
				// string
				else if('string' === typeof z_value) {
					// escape double quote chars
					s_value = z_value.replace(/"/g, '\\"');

					// set string type
					s_type = P_XSD_NAMESPACE+'string';
				}
				// hash
				else if(Object === z_value.constructor) {
					// set value from hash; escape double quote chars
					s_value = z_value.value.replace(/"/g, '\\"');

					// set type from hash
					s_type = z_value.datatype;
				}
				// Date
				else if(Date === z_value.constructor) {
					// set value from ISO serialization
					s_value = z_value.toISOString();

					// set type for xsd:dateTime
					s_type = P_XSD_NAMESPACE+'dateTime';
				}
				// unsupported type
				else {
					return local.fail('.val method does not support this type of value: '+arginfo(z_value));
				}
			}
			// bad type
			else if('string' !== typeof s_type) {
				return local.fail('cannot use non-string to describe type of val: '+arginfo(s_type));
			}

			//
			return '"'+s_value+'"^^'+operator.shorten(s_type);
		},

		// constructs a shortened
		n3v(z_value, s_type) {

		},

		// create a filter block
		filter(...a_exprs) {

			//
			let s_expression = a_exprs.map((z_expr) => {

				// SPARQL string
				if('string' === typeof z_expr) {

					// simple concatenation
					return z_expr;
				}
				// array indicates special meaning
				else if(Array.isArray(z_expr)) {

					// ref last arg
					let z_val = z_expr[z_expr.length-1];

					//
					if('object' === typeof z_val) {

						// regex
						if(z_val instanceof RegExp) {

							// must be two args
							if(2 !== z_expr.length) {
								local.fail('filter with regular expression must have exactly 2 arguments. instead got '+z_expr.length+': '+arginfo(z_expr));
							}

							// ref test arg
							let s_test = z_expr[0];

							// `test` arg needs to be a string
							if('string' !== typeof s_test) {
								local.fail('filter with regular expression expects [string] for `test` argument. instead got: '+arginfo(s_test));
							}

							return `regex(${s_test},"${z_val.source.replace(/"/g, '\\"')}","${z_val.flags}")`;

							//
							// return {
							// 	type: 'operation',
							// 	operator: 'regex',
							// 	args: [s_test, z_val.source, z_val.flags],
							// };
						}
					}
				}
			}).join(' ');

			//
			return {
				type: 'filter',
				expression: s_expression,
			};
		},

		// filter exists
		exists(...a_groups) {

			//
			return function() {
				return this.serialize_filter('exists', a_groups);
			};
		},

		// semantic chaining for operations preceeded by 'not'
		not: {

			// 'not exists'
			exists(...a_groups) {

				// post-serialization
				return function() {
					return this.serialize_filter('not exists', a_groups);
				};
			},
		},

		//
		sub(h_sub) {

			//
			local.warn('the `sub` function is not yet fully supported');

			//
			return function() {
				return {
					type: 'query',
					queryType: 'SELECT',
					variables: h_sub.select,
					where: this.serialize_pattern('where', h_sub.where),
				};
			};
		},

		/**
		* general helper methods
		**/

		// general expand
		expand(s_iri) {

			// split by colon
			let [s_name, s_path] = s_iri.split(':');

			// attempt globally defined prefix
			let s_ref_base = hm_prologue_prefixes.get(s_name);

			// not defined globally
			if(!s_ref_base) {
				return local.fail('no such prefix defined "'+s_name+'"');
			}

			// build full iri
			return s_ref_base+s_path;
		},

		// general shorten
		shorten(p_iri) {

			//
			let s_best_prefix = '';
			let n_longest_url = 0;

			//
			for(let [s_prefix, p_url] of hm_prologue_prefixes) {
				if(p_iri.startsWith(p_url) && p_url.length > n_longest_url) {
					s_best_prefix = s_prefix;
					n_longest_url = p_url.length;
				}
			}

			//
			if(n_longest_url) {
				// compute suffix
				let s_suffix = p_iri.substr(n_longest_url);

				// make sure it is a valid suffix
				if(/^[a-zA-z_][a-zA-z_0-9\-]*$/.test(s_suffix)) {
					return s_best_prefix+':'+s_suffix;
				}
			}

			// when all else fails
			return '<'+p_iri+'>';
		},

		// converts hash into ttl-style string; does nothing on [string], casts [boolean], [number] to [string]
		turtle(z_thing) {

			// ref thing type
			let s_type = typeof z_thing;

			//
			switch(s_type) {
				case 'string':
				case 'number':
				case 'boolean':
					return z_thing+'';

				case 'undefined':
					return 'UNDEF';

				case 'object':
					switch(z_thing.type) {
						case 'variable':
							return '?'+z_thing.name;

						case 'bnode':
							return z_thing.id;

						case 'iri':
							return '<'+z_thing.iri+'>';

						case 'uri':
							return '<'+z_thing.value+'>';

						case 'literal':
						case 'typed-literal':
							return '"'+z_thing.value.replace(/"/g, '\\"')+'"'+(z_thing.datatype? '^^<'+z_thing.datatype+'>': '');

						default:
							local.fail('invalid turtle type "'+z_thing.type+'" from: '+arginfo(z_thing));
					}
			}
		},

		// converts n3 string into a hash
		rabbit(s_thing) {
			if('?' === s_thing[0]) {
				return {
					type: 'variable',
					name: s_thing.substr(1),
					value: s_thing,
				};
			}
			else if(s_thing.startsWith('_:')) {
				return {
					type: 'bnode',
					id: s_thing,
				};
			}
			else if('"' === s_thing[0]) {
				let m_literal = R_TTL_LITERAL.exec(s_thing);
				return {
					type: 'literal',
					value: m_literal[1],
					datatype: m_literal[2]? m_literal[2].replace(/^<|>$/g, ''): P_XSD_NAMESPACE+'string',
				};
			}
			else {
				return {
					type: 'iri',
					iri: s_thing.replace(/^<|>$/g, ''),
				};
			}
		},

		// tests if entity is an iri
		isIri(z_entity) {
			return (
				'string' === typeof z_entity
				&& '?' !== z_entity[0]
				&& '"' !== z_entity[0]
				&& !z_entity.startsWith('_:')
			);
		},

		// tests is entity is blanknode
		isBlanknode(z_entity) {
			return (
				'string' === typeof z_entity
				&& z_entity.startsWith('_:')
			);
		},

		//
		isNamedPredicate(s_predicate) {
			return ('?' !== s_predicate[0] && !H_PREDICATE_ALIASES.has(s_predicate));
		},

		// execution methods
		submit(s_sparql, s_type, f_okay) {

			// no sparql engine!
			if(!k_engine) return local.fail('cannot execute query; no SPARQL engine was specified!');

			// execute query!
			k_engine(s_sparql, s_type)
				// engine responded
				.then((h_json) => {

					// escape the grips of the promise
					setImmediate(() => {

						// forward json to callback
						f_okay(h_json);
					});
				})
				// error
				.catch((s_msg) => {
					local.fail('SPARQL engine failure:\n'+s_msg);
				});
		},

		//
		stringify(z_thing) {

			//
			let stringify_thing = function(add, z_item) {

				// ref thing type
				let s_type = typeof z_item;

				// string
				if('string' === s_type) {
					add(`'${z_item.replace(/'/g, '\\\'')}'`, true);
				}
				// array
				else if(Array.isArray(z_item)) {
					add.open('[ ', ',', true);
					for(let i_item in z_item) {
						add('');
						stringify_thing(add, z_item[i_item]);
					}
					add.close(']');
				}
				// object / function
				else if('object' === s_type || 'function' === s_type) {

					add.open('{', ',', true);
					for(let s_property in z_item) {
						add(`'${s_property.replace(/'/g, '\\\'')}': `);
						stringify_thing(add, z_item[s_property]);
					}
					add.close('}');
				}
			};

			let k_code = rapunzel({
				body(add) {
					return stringify_thing(add, z_thing);
				},
			}, ['body']);

			//
			return k_code.produce({
				indent: '    ',
			});
		}
	});

	// alias prefix
	operator.prefixes = operator.prefix;

	//
	return operator;
}, {

	/**
	* public static:
	**/
	val(z_value, s_type) {

		// prep value string; default to input arg `value`
		let s_value = z_value;

		// no explicit type given
		if('undefined' === typeof s_type) {

			// boolean
			if('boolean' === typeof z_value) {
				s_type = P_XSD_NAMESPACE+'boolean';
			}
			// numeric
			else if('number' === typeof z_value) {
				// integer
				if(Number.isInteger(z_value)) {
					s_type = P_XSD_NAMESPACE+'integer';
				}
				// non-finite / NaN
				else if(isNaN(z_value) || !isFinite(z_value)) {
					return local.fail('cannot create numeric value for non-finite / NaN type: '+arginfo(z_value));
				}
				// float
				else {
					s_type = P_XSD_NAMESPACE+'decimal';
				}
			}
			// string
			else if('string' === typeof z_value) {
				// escape double quote chars
				s_value = z_value.replace(/"/g, '\\"');

				// set string type
				s_type = P_XSD_NAMESPACE+'string';
			}
			// hash
			else if(Object === z_value.constructor) {
				// set value from hash; escape double quote chars
				s_value = z_value.value.replace(/"/g, '\\"');

				// set type from hash
				s_type = z_value.datatype;
			}
			// Date
			else if(Date === z_value.constructor) {
				// set value from ISO serialization
				s_value = z_value.toISOString();

				// set type for xsd:dateTime
				s_type = P_XSD_NAMESPACE+'dateTime';
			}
			// unsupported type
			else {
				return local.fail('.val method does not support this type of value: '+arginfo(z_value));
			}
		}
		// bad type
		else if('string' !== typeof s_type) {
			return local.fail('cannot use non-string to describe type of val: '+arginfo(s_type));
		}

		//
		return '"'+s_value+'"^^<'+s_type+'>';
	},
});

export default local;


text:
using System;

namespace ExtensionMethods
{
    public static class CalendaryExtensionMethods
    {
        public static DateTime Tomorrow(this DateTime date)
        {
            return date.AddDays(1);
        }
        public static DateTime Yesterday(this DateTime date)
        {
            return date.AddDays(-1);
        }
        public static int Age(this DateTime date)
        {
            var now = DateTime.Now;
            var age = now.Year - date.Year;
            if (now.Month > date.Month || (now.Month == date.Month && now.Day < date.Day))
                age -= 1;
            return age;

        }
        public static int AgeInDays(this DateTime date)
        {
            TimeSpan ts = DateTime.Now - date;
            return ts.Duration().Days;
        }
        public static double RemainingDaysInYear(this DateTime date)
        {
            TimeSpan ts = new DateTime(date.Year, 12, 31).Date - date.Date;
            return ts.Duration().TotalDays;
        }
        public static double RemainingDaysInMonth(this DateTime date)
        {
            TimeSpan ts = new DateTime(date.Year, date.Month, 1).AddMonths(1).AddDays(-1).Date - date.Date;
            return ts.Duration().TotalDays;
        }
        public static double RemainingHoursInYear(this DateTime date)
        {
            TimeSpan ts = new DateTime(date.Year, 12, 31, 23, 59, 59, 999) - date;
            return ts.Duration().TotalHours;
        }
        public static double RemainingHoursInMonth(this DateTime date)
        {
            TimeSpan ts = new DateTime(date.Year, date.Month, 1).AddMonths(1).AddDays(-1) - date;
            return ts.Duration().TotalHours;
        }
        public static double RemainingHoursInDay(this DateTime date)
        {
            TimeSpan ts = new DateTime(date.Year, date.Month, date.Day, 23, 59, 59, 999) - date;
            return ts.Duration().TotalHours;
        }
        public static double RemainingMinutesInYear(this DateTime date)
        {
            TimeSpan ts = new DateTime(date.Year, 12, 31, 23, 59, 59, 999) - date;
            return ts.Duration().TotalMinutes;
        }
        public static double RemainingMinutesInMonth(this DateTime date)
        {
            TimeSpan ts = new DateTime(date.Year, date.Month, 1, 23, 59, 59, 999).AddMonths(1).AddDays(-1) - date;
            return ts.Duration().TotalMinutes;
        }
        public static double RemainingMinutesInDay(this DateTime date)
        {
            TimeSpan ts = new DateTime(date.Year, date.Month, date.Day, 23, 59, 59, 999) - date;
            return ts.Duration().TotalMinutes;
        }
        public static double RemainingMinutesInHour(this DateTime date)
        {
            TimeSpan ts = new DateTime(date.Year, date.Month, date.Day, date.Hour, 0, 0).AddHours(1) - date;
            return ts.Duration().TotalMinutes;
        }

        public static bool Between(this DateTime date, DateTime first, DateTime last)
        {
            return (date.Date >= first.Date && date.Date <= last.Date) ? true : false;
        }

        public static bool IsBirthday(this DateTime date, DateTime dateToCheck)
        {
            if (dateToCheck.Year <= date.Year)
            {
                return false;
            }
            return dateToCheck.Month == date.Month && dateToCheck.Day == date.Day;
        }
        public static bool IsBirthday(this DateTime date)
        {
            if (DateTime.Now.Year <= date.Year)
            {
                return false;
            }
            return DateTime.Now.Month == date.Month && DateTime.Now.Day == date.Day;
        }

        public static bool IsFuture(this DateTime date)
        {
            return (date.Date > DateTime.Now) ? true : false;
        }
        public static bool IsPast(this DateTime date)
        {
            return (date.Date < DateTime.Now) ? true : false;
        }

        public static bool IsSunday(this DateTime date)
        {
            return (date.DayOfWeek.Equals(DayOfWeek.Sunday)) ? true : false;
        }
        public static bool IsMonday(this DateTime date)
        {
            return (date.DayOfWeek.Equals(DayOfWeek.Monday)) ? true : false;
        }
        public static bool IsTuesday(this DateTime date)
        {
            return (date.DayOfWeek.Equals(DayOfWeek.Tuesday)) ? true : false;
        }
        public static bool IsWednesday(this DateTime date)
        {
            return (date.DayOfWeek.Equals(DayOfWeek.Wednesday)) ? true : false;
        }
        public static bool IsThursday(this DateTime date)
        {
            return (date.DayOfWeek.Equals(DayOfWeek.Thursday)) ? true : false;
        }
        public static bool IsFriday(this DateTime date)
        {
            return (date.DayOfWeek.Equals(DayOfWeek.Friday)) ? true : false;
        }
        public static bool IsSaturday(this DateTime date)
        {
            return (date.DayOfWeek.Equals(DayOfWeek.Saturday)) ? true : false;
        }
        public static DateTime NextSunday(this DateTime date)
        {
            return CheckNextDayOfWeek(date, DayOfWeek.Sunday);
        }
        public static DateTime NextMonday(this DateTime date)
        {
            return CheckNextDayOfWeek(date, DayOfWeek.Monday);
        }
        public static DateTime NextTuesday(this DateTime date)
        {
            return CheckNextDayOfWeek(date, DayOfWeek.Tuesday);
        }
        public static DateTime NextWednesday(this DateTime date)
        {
            return CheckNextDayOfWeek(date, DayOfWeek.Wednesday);
        }
        public static DateTime NextThursday(this DateTime date)
        {
            return CheckNextDayOfWeek(date, DayOfWeek.Thursday);
        }
        public static DateTime NextFriday(this DateTime date)
        {
            return CheckNextDayOfWeek(date, DayOfWeek.Friday);
        }
        public static DateTime NextSaturday(this DateTime date)
        {
            return CheckNextDayOfWeek(date, DayOfWeek.Saturday);
        }

        private static DateTime CheckNextDayOfWeek(DateTime date, DayOfWeek returnDay)
        {
            int i = 0;
            while (!date.DayOfWeek.Equals(returnDay))
            {
                date = date.AddDays(1);
                i++;
            }

            return (i == 0) ? date.AddDays(7) : date;
        }

        public static DateTime LastSunday(this DateTime date)
        {
            return CheckLastDayOfWeek(date, DayOfWeek.Sunday);
        }
        public static DateTime LastMonday(this DateTime date)
        {
            return CheckLastDayOfWeek(date, DayOfWeek.Monday);
        }
        public static DateTime LastTuesday(this DateTime date)
        {
            return CheckLastDayOfWeek(date, DayOfWeek.Tuesday);
        }
        public static DateTime LastWednesday(this DateTime date)
        {
            return CheckLastDayOfWeek(date, DayOfWeek.Wednesday);
        }
        public static DateTime LastThursday(this DateTime date)
        {
            return CheckLastDayOfWeek(date, DayOfWeek.Thursday);
        }
        public static DateTime LastFriday(this DateTime date)
        {
            return CheckLastDayOfWeek(date, DayOfWeek.Friday);
        }
        public static DateTime LastSaturday(this DateTime date)
        {
            return CheckLastDayOfWeek(date, DayOfWeek.Saturday);
        }

        private static DateTime CheckLastDayOfWeek(DateTime date, DayOfWeek returnDay)
        {
            int i = 0;
            while (!date.DayOfWeek.Equals(returnDay))
            {
                date = date.AddDays(-1);
                i++;
            }

            return (i == 0) ? date.AddDays(-7) : date;
        }
    }
}