text:
            {{lang 'cart.checkout.item'}}
            {{lang 'cart.checkout.price'}}
            {{lang 'cart.checkout.quantity'}}
            {{lang 'cart.checkout.total'}}

        {{#each cart.items}}

                    {{#if type '==' 'GiftCertificate'}}

                    {{else}}

                    {{/if}}

                    {{#if brand.name}}

{{brand.name}}

                    {{/if}}

{{name}}

                    {{#if release_date}}

({{release_date}})

                    {{/if}}

                    {{#if configurable_fields}}

                            {{#each configurable_fields}}

{{name}}:

                                    {{#if is_file}}
                                        {{{value}}}
                                    {{else}}
                                        {{{value}}}
                                    {{/if}}

                            {{/each}}

                    {{/if}}

                    {{#if options}}

                            {{#each options}}

{{name}}:

                                    {{#if is_file}}
                                        {{{value}}}
                                    {{else}}
                                        {{{value}}}
                                    {{/if}}

                            {{/each}}

                    {{/if}}

                    {{#or options configurable_fields}}
                        {{lang 'cart.checkout.change'}}
                    {{/or}}

                    {{#if type '==' 'GiftCertificate'}}
                        {{lang 'cart.checkout.change'}}
                    {{/if}}
                    {{> components/cart/item-giftwrap this}}
                    {{#if event_date}}

                                {{event_date.name}}

                                {{event_date.date}}

                    {{/if}}

                    {{lang 'cart.checkout.price'}}
                    {{price.formatted}}
                    {{#if price_discounted}}
                        {{price_discounted.formatted}}
                    {{/if}}

                    {{lang 'products.quantity'}}

                        {{# if can_modify}}
                            <button class="button button--icon" data-cart-update data-cart-itemid="{{id}}" data-action="dec">
                                {{lang 'products.quantity_decrease'}}
                                <svg><use xlink:href="#icon-keyboard-arrow-down" /></svg>
                            </button>
                        {{/if}}
                        <input class="form-input form-input--incrementTotal"
                               id="qty-{{id}}"
                               name="qty-{{id}}"
                               type="tel"
                               value="{{quantity}}"
                               data-quantity-min="{{min_purchase_quantity}}"
                               data-quantity-max="{{max_purchase_quantity}}"
                               data-quantity-min-error="{{lang 'products.quantity_min' quantity=min_purchase_quantity}}"
                               data-quantity-max-error="{{lang 'products.quantity_max' quantity=max_purchase_quantity}}"
                               min="1"
                               pattern="[0-9]*"
                               aria-live="polite"{{#unless can_modify}} disabled{{/unless}}>
                        {{# if can_modify}}
                            <button class="button button--icon" data-cart-update data-cart-itemid="{{id}}" data-action="inc">
                                {{lang 'products.quantity_increase'}}
                                <svg><use xlink:href="#icon-keyboard-arrow-up" /></svg>
                            </button>
                        {{/if}}

                    {{lang 'cart.checkout.total'}}
                    {{total.formatted}}
                    {{#if total_discounted}}
                        {{total_discounted.formatted}}
                    {{/if}}
                    {{# if can_modify}}

                            <svg><use xlink:href="#icon-close"></use></svg>

                    {{else}}
                        {{#if type '==' 'GiftCertificate'}}

                                <svg><use xlink:href="#icon-close"></use></svg>

                        {{/if}}

                    {{/if}}

        {{/each}}


text:
Has sido registrado en SUCE!

				Se ha creado una cuenta para ti en el Sistema Universitario de Control Escolar,
				para que puedas acceder a ella debes ingresar a SUCE.

				Tus datos de acceso son:

				Usuario: {user}

				Password: {passwd}

				Si tienes alguna duda o problema contacta a tu profesor, o al administrador del sistema.

redpajama_set_name: RedPajamaGithub


text:
/// <reference path="../_reference.js" />

function Figure(colour, type, fieldPositionX, fieldPositionY) {
    this.type = type;
    this.colour = colour;
    var figureName = colour + type;
    this.image=new Kinetic.Image({
        x: BORDER_SIZE+FIELD_SIZE*fieldPositionX,
        y: BORDER_SIZE + FIELD_SIZE * fieldPositionY,
        image: IMAGES[figureName],
        width: FIELD_SIZE,
        height: FIELD_SIZE
    });
    this.isMoved = false;
}
//This function changes the ONLY Image position of the figure
Figure.prototype.moveImage = function (fieldPositionX, fieldPositionY) {

    this.image.position({
        x: fieldPositionX * FIELD_SIZE + BORDER_SIZE,
        y: fieldPositionY*FIELD_SIZE+BORDER_SIZE
    })
    return this;
    //You need to redraw after using this function for the change to take visual effect
}
Figure.prototype.deleteImage = function () {
    this.image.destroy();
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout ="vertical" ="@id/friend_row" ="@color/green" ="fill_parent" ="fill_parent"
  xmlns:android="http://schemas.android.com/apk/res/android">
    <com.quizup.lib.widgets.listEntries.FriendListEntry ="@id/friend_list_entry" ="fill_parent" ="wrap_content" ="@dimen/side_margin_width" ="@dimen/side_margin_width" />
    <ImageView ="@id/message_shadow" ="@drawable/bottom_shadow" ="fill_parent" ="@dimen/card_bottom_shadow_height" ="@string/shadow_desc" />
</LinearLayout>


text:
<InterchangeAssessmentMetadata xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://ed-fi.org/0100"
    xsi:schemaLocation="http://ed-fi.org/0100 ../../../../../../../sli/edfi-schema/src/main/resources/edfiXsd-SLI/SLI-Interchange-AssessmentMetadata.xsd">
    <AssessmentFamily>
        <AssessmentFamilyTitle>Update AF then Delete A</AssessmentFamilyTitle>
        <AssessmentFamilyIdentificationCode IdentificationSystem="Test Contractor">
            <ID>Updated</ID>
        </AssessmentFamilyIdentificationCode>
    </AssessmentFamily>
    <AssessmentItem>
        <AssessmentReference>
            <AssessmentIdentity>
                <AssessmentTitle>2013-Kindergarten Assessment 2 Item</AssessmentTitle>
                <AcademicSubject>Writing</AcademicSubject>
                <GradeLevelAssessed>Kindergarten</GradeLevelAssessed>
            </AssessmentIdentity>
        </AssessmentReference>
        <IdentificationCode>2013-Kindergarten Assessment 2#1 Item</IdentificationCode>
        <ItemCategory>True-False</ItemCategory>
        <MaxRawScore>88</MaxRawScore>
        <CorrectResponse>true</CorrectResponse>
        <Nomenclature>nonenclature</Nomenclature>
    </AssessmentItem>
</InterchangeAssessmentMetadata>


text:
package plainview;

import clojure.lang.ISeq;
import clojure.lang.Var;
import clojure.lang.RT;

public class Producer {

    private static final Var SYMBOL  = RT.var("clojure.core", "symbol");
    private static final Var REQUIRE = RT.var("clojure.core", "require");
    private static final Var MAIN    = RT.var("plainview.producer", "-main");

    public static void main(String... args) {
        REQUIRE.invoke(SYMBOL.invoke("plainview.producer"));
        MAIN.invoke(args);
    }
}


text:
use std::sync::atomic::*;
use std::ptr;

fn main() {
    let x = AtomicBool::new(false);
    let x = *&x; //~ ERROR: cannot move out of a shared reference
    let x = AtomicIsize::new(0);
    let x = *&x; //~ ERROR: cannot move out of a shared reference
    let x = AtomicUsize::new(0);
    let x = *&x; //~ ERROR: cannot move out of a shared reference
    let x: AtomicPtr<usize> = AtomicPtr::new(ptr::null_mut());
    let x = *&x; //~ ERROR: cannot move out of a shared reference
}


text:
namespace Cot
{
	ComponentExt(SpriteRenderer, IRenderComponent, COT_API)
	{
		COT_COMPONENT(SpriteRenderer);
	protected:
		Texture*	_texture;

	public:
		SpriteRenderer* Init(const string& filename);
		SpriteRenderer* Init(const string& caif, const string& key);

		void Reset() override;
		void Update(Time& time) override;
		void OnDestroy() override;

		void SetTexture(Texture* texture);
		void SetTexture(const string& filename);
		void SetTexture(const string& caif, const string& key);
		Texture* GetTexture() { return _texture; }

	};
}


text:
import {Component} from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {TableData, LineGraphData} from "jigsaw/mobile_public_api";

@Component({
    templateUrl: './demo.component.html',
    styleUrls: ['./demo.component.css']
})
export class JigsawMobileTabsDemoComponent {
    fruitList: TableData = new TableData(
        [
            ["banana", "$12.0", "The banana is an edible fruit – botanically a berry – produced by several kinds of large herbaceous flowering plants in the genus Musa.", "Southeast Asia"],
            ["apple", "$21.0", "The apple tree is a deciduous tree in the rose family best known for its sweet, pomaceous fruit, the apple.", "Shan Dong, China"],
            ["strawberry", "$31.0", "The garden strawberry is a widely grown hybrid species of the genus Fragaria, collectively known as the strawberries. It is cultivated worldwide for its fruit.", "Southeast Asia"],
            ["watermelon", "$13.0", "Watermelon Citrullus lanatus var. lanatus is a scrambling and trailing vine in the flowering plant family Cucurbitaceae.", "Southeast Asia"],
            ["pineapple", "$33.0", "The pineapple is a tropical plant with an edible multiple fruit consisting of coalesced berries, also called pineapples.", "Southeast Asia"],
            ["pear", "$11.0", "The pear is any of several tree and shrub species of genus Pyrus, in the family Rosaceae. It is also the name of the pomaceous fruit of the trees. ", "Southeast Asia"],
        ],
        ["name", "price", "desc", "origin"],
        ["Name", "Price", "Description", "Origin"]
    );

    testEvent(value) {
        console.info(value);
    }

    selectedIndexChange($event) {
        console.log($event);
    }

    public lineBarGraphData: LineGraphData;

    constructor(http: HttpClient) {
        this.lineBarGraphData = new LineGraphData();
        this.lineBarGraphData.http = http;
        this.lineBarGraphData.fromAjax('mock-data/marketing');
    }

    // ====================================================================
    // ignore the following lines, they are not important to this demo
    // ====================================================================
    summary: string = '此demo主要描述tab的加载机制';
    description: string = require('!!raw-loader!./readme.md').default;
}


text:
#include "config.h"
#include "JSCell.h"

#include "ArrayBufferView.h"
#include "JSFunction.h"
#include "JSString.h"
#include "JSObject.h"
#include "NumberObject.h"
#include "Operations.h"
#include <wtf/MathExtras.h>

namespace JSC {

STATIC_ASSERT_IS_TRIVIALLY_DESTRUCTIBLE(JSCell);

void JSCell::destroy(JSCell* cell)
{
    cell->JSCell::~JSCell();
}

void JSCell::copyBackingStore(JSCell*, CopyVisitor&, CopyToken)
{
}

bool JSCell::getString(ExecState* exec, String& stringValue) const
{
    if (!isString())
        return false;
    stringValue = static_cast<const JSString*>(this)->value(exec);
    return true;
}

String JSCell::getString(ExecState* exec) const
{
    return isString() ? static_cast<const JSString*>(this)->value(exec) : String();
}

JSObject* JSCell::getObject()
{
    return isObject() ? asObject(this) : 0;
}

const JSObject* JSCell::getObject() const
{
    return isObject() ? static_cast<const JSObject*>(this) : 0;
}

CallType JSCell::getCallData(JSCell*, CallData& callData)
{
    callData.js.functionExecutable = 0;
    callData.js.scope = 0;
    callData.native.function = 0;
    return CallTypeNone;
}

ConstructType JSCell::getConstructData(JSCell*, ConstructData& constructData)
{
    constructData.js.functionExecutable = 0;
    constructData.js.scope = 0;
    constructData.native.function = 0;
    return ConstructTypeNone;
}

void JSCell::put(JSCell* cell, ExecState* exec, PropertyName identifier, JSValue value, PutPropertySlot& slot)
{
    if (cell->isString()) {
        JSValue(cell).putToPrimitive(exec, identifier, value, slot);
        return;
    }
    JSObject* thisObject = cell->toObject(exec, exec->lexicalGlobalObject());
    thisObject->methodTable()->put(thisObject, exec, identifier, value, slot);
}

void JSCell::putByIndex(JSCell* cell, ExecState* exec, unsigned identifier, JSValue value, bool shouldThrow)
{
    if (cell->isString()) {
        PutPropertySlot slot(shouldThrow);
        JSValue(cell).putToPrimitive(exec, Identifier::from(exec, identifier), value, slot);
        return;
    }
    JSObject* thisObject = cell->toObject(exec, exec->lexicalGlobalObject());
    thisObject->methodTable()->putByIndex(thisObject, exec, identifier, value, shouldThrow);
}

bool JSCell::deleteProperty(JSCell* cell, ExecState* exec, PropertyName identifier)
{
    JSObject* thisObject = cell->toObject(exec, exec->lexicalGlobalObject());
    return thisObject->methodTable()->deleteProperty(thisObject, exec, identifier);
}

bool JSCell::deletePropertyByIndex(JSCell* cell, ExecState* exec, unsigned identifier)
{
    JSObject* thisObject = cell->toObject(exec, exec->lexicalGlobalObject());
    return thisObject->methodTable()->deletePropertyByIndex(thisObject, exec, identifier);
}

JSValue JSCell::toThis(JSCell* cell, ExecState* exec, ECMAMode ecmaMode)
{
    if (ecmaMode == StrictMode)
        return cell;
    return cell->toObject(exec, exec->lexicalGlobalObject());
}

JSValue JSCell::toPrimitive(ExecState* exec, PreferredPrimitiveType preferredType) const
{
    if (isString())
        return static_cast<const JSString*>(this)->toPrimitive(exec, preferredType);
    return static_cast<const JSObject*>(this)->toPrimitive(exec, preferredType);
}

bool JSCell::getPrimitiveNumber(ExecState* exec, double& number, JSValue& value) const
{
    if (isString())
        return static_cast<const JSString*>(this)->getPrimitiveNumber(exec, number, value);
    return static_cast<const JSObject*>(this)->getPrimitiveNumber(exec, number, value);
}

double JSCell::toNumber(ExecState* exec) const
{
    if (isString())
        return static_cast<const JSString*>(this)->toNumber(exec);
    return static_cast<const JSObject*>(this)->toNumber(exec);
}

JSObject* JSCell::toObject(ExecState* exec, JSGlobalObject* globalObject) const
{
    if (isString())
        return static_cast<const JSString*>(this)->toObject(exec, globalObject);
    ASSERT(isObject());
    return jsCast<JSObject*>(const_cast<JSCell*>(this));
}

void slowValidateCell(JSCell* cell)
{
    ASSERT_GC_OBJECT_LOOKS_VALID(cell);
}

JSValue JSCell::defaultValue(const JSObject*, ExecState*, PreferredPrimitiveType)
{
    RELEASE_ASSERT_NOT_REACHED();
    return jsUndefined();
}

bool JSCell::getOwnPropertySlot(JSObject*, ExecState*, PropertyName, PropertySlot&)
{
    RELEASE_ASSERT_NOT_REACHED();
    return false;
}

bool JSCell::getOwnPropertySlotByIndex(JSObject*, ExecState*, unsigned, PropertySlot&)
{
    RELEASE_ASSERT_NOT_REACHED();
    return false;
}

void JSCell::getOwnPropertyNames(JSObject*, ExecState*, PropertyNameArray&, EnumerationMode)
{
    RELEASE_ASSERT_NOT_REACHED();
}

void JSCell::getOwnNonIndexPropertyNames(JSObject*, ExecState*, PropertyNameArray&, EnumerationMode)
{
    RELEASE_ASSERT_NOT_REACHED();
}

String JSCell::className(const JSObject*)
{
    RELEASE_ASSERT_NOT_REACHED();
    return String();
}

const char* JSCell::className()
{
    return classInfo()->className;
}

void JSCell::getPropertyNames(JSObject*, ExecState*, PropertyNameArray&, EnumerationMode)
{
    RELEASE_ASSERT_NOT_REACHED();
}

bool JSCell::customHasInstance(JSObject*, ExecState*, JSValue)
{
    RELEASE_ASSERT_NOT_REACHED();
    return false;
}

bool JSCell::defineOwnProperty(JSObject*, ExecState*, PropertyName, const PropertyDescriptor&, bool)
{
    RELEASE_ASSERT_NOT_REACHED();
    return false;
}

ArrayBuffer* JSCell::slowDownAndWasteMemory(JSArrayBufferView*)
{
    RELEASE_ASSERT_NOT_REACHED();
    return 0;
}

PassRefPtr<ArrayBufferView> JSCell::getTypedArrayImpl(JSArrayBufferView*)
{
    RELEASE_ASSERT_NOT_REACHED();
    return 0;
}

} // namespace JSC


text:
      <div class="bg-category" style="background: url('<?php echo base_url() ?>assets/uploads/destination/<?php echo $data->id ?>/<?php echo $data->images ?>'); background-size:cover ">

          <?php echo $data->title ?>

                <?php echo $data->description ?>

Program Destination

                <?php foreach ($program as $key) {
                 ?>

          <a href="<?php echo site_url() ?>/program/category/<?php echo $data->id ?>/<?php echo $key->category->id ?>/<?php echo url_title($key->category->title) ?>" class="text-decoration-none popup-with-move-anim">

                <span class="thumb-info-background" style="background-image: url('<?php echo base_url() ?>assets/uploads/category_program/<?php echo $key->category->id ?>/<?php echo $key->category->images ?>');">
                <?php echo $key->category->title ?>

                <?php } ?>

                <a class="btn btn-primary mt-xl mb-sm" href="<?php echo site_url() ?>/destination/category/<?php echo $data->id ?>/<?php echo str_replace(" ", "-",$data->title) ?>">See More

        <?php foreach ($program_top1 as $key) {
         ?>
        <section class="section section-text-light section-background" style="background-image: url(<?php echo base_url() ?>assets/uploads/album_program/<?php echo $key->id_image ?>/<?php echo $key->image ?>);background-position:center; margin-top: 95px; background-size: cover;">

Top Destination in <?php echo $data->title ?>

<?php echo $key->title ?> *5

Start from IDR
                  <?php if($key->disc>0){ ?>
                       <?php echo idr($key->price1) ?>
                      <?php $a=($key->price1/100)*$key->disc; $b=$key->price1-$a; echo idr($b);  ?>
                      <?php }else{ ?>
                      <?php echo idr($key->price1) ?>
                      <?php } ?>

                <?php echo $key->summary ?>

                <a href="<?php echo site_url('program/detail/'.$key->id."/".url_title($key->title)) ?>" class="btn btn-danger mr-xs mb-sm pl-xlg pr-xlg" style="border-radius:30px">Book Now

        <?php } ?>

          <?php $no=0; foreach ($program_top4 as $key) {
            $no++;
          ?>

                <img src="<?php echo base_url() ?>assets/uploads/album_program/<?php echo $key->id_image ?>/<?php echo $key->image ?>" alt="" class="img-responsive" style="width:100%">

                <a href="<?php echo site_url('program/detail/'.$key->id."/".url_title($key->title)) ?>">
<?php echo $key->title ?> *<?php echo $no ?>

                  Start From
                  Rp
                  <?php if($key->disc>0){ ?>
                      <?php echo idr($key->price1) ?>
                      <?php $a=($key->price1/100)*$key->disc; $b=$key->price1-$a; echo idr($b);  ?>
                      <?php }else{ ?>
                      <?php echo idr($key->price1) ?>
                      <?php } ?>

          <?php } ?>

          <a class="btn btn-primary mt-xl mb-sm" href="<?php echo site_url('program') ?>">See More

Recent Articles

            <?php foreach ($article as $key) {
              ?>

                <a href="<?php echo site_url('article/detail/'.$key->id."/".url_title($key->title)) ?>" class="text-decoration-none popup-with-move-anim">

                      <span class="thumb-info-background" style="background-image: url('<?php echo base_url() ?>/assets/uploads/news/<?php echo $key->id ?>/<?php echo $key->images ?>');">
                      <?php echo $key->title ?>

<?php echo substr($key->summary, 0,250) ?>.... Red More

          <?php } ?>

            <a class="btn btn-primary mt-xl mb-sm" href="<?php echo site_url('article') ?>">See More

 Program Berkaitan

        <?php foreach ($program_related as $key) {
         ?>

            <a href="<?php echo site_url() ?>/program/detail/<?php echo $key->id ?>/<?php echo url_title($key->title) ?>" class="text-decoration-none">

                  <img alt="" class="img-responsive" src="<?php echo base_url() ?>assets/uploads/album_program/<?php echo $key->id_image ?>/<?php echo $key->image ?>">

                    <?php echo $key->category ?>

<?php echo $key->title ?>

 <?php echo substr($key->summary,0,150) . "..."; ?>

                    Start From
                    Rp
                    <?php if($key->disc>0){ ?>
                      <?php echo idr($key->price1) ?>
                      <?php $a=($key->price1/100)*$key->disc; $b=$key->price1-$a; echo idr($b);  ?>
                      <?php }else{ ?>
                      <?php echo idr($key->price1) ?>
                      <?php } ?>

          <?php } ?>


text:
/*!
 * Copyright (c) 2018 by Contributors
 * \file tensorrt_pass.cc
 * \brief Replace TRT compatible subgraphs by TRT engines
 * \author Clement Fuji Tsang
 */

#if MXNET_USE_TENSORRT

#include <NvInfer.h>
#include <mxnet/base.h>
#include <mxnet/op_attr_types.h>
#include <mxnet/operator.h>
#include <nnvm/graph_attr_types.h>
#include <onnx/onnx_pb.h>

#include "../operator/contrib/nnvm_to_onnx-inl.h"
#include "./exec_pass.h"
#include "./onnx_to_tensorrt.h"

namespace mxnet {
namespace exec {

using NodePtr = nnvm::NodePtr;

/*!
 * \brief Custom graph class, which will contain bi-directional nodes
 * we need to compute DFS and reverse DFS for graph partitioning
 */
class BidirectionalGraph {
 public:
  struct Node {
    nnvm::Node* nnvmptr;
    std::vector<Node*> inputs;
    std::vector<Node*> outputs;
  };
  std::vector<Node> nodes;
  std::unordered_map<nnvm::Node*, uint32_t> nnvm2nid;
  std::vector<Node*> outputs;
  static const std::unordered_set<std::string> unconditionalTRTop;

  explicit BidirectionalGraph(const Graph &g) {
    auto& idx = g.indexed_graph();
    auto num_nodes = idx.num_nodes();
    nodes.reserve(num_nodes);
    nnvm2nid.reserve(num_nodes);
    outputs.reserve(idx.outputs().size());
    DFSVisit(g.outputs, [this](const nnvm::NodePtr& n) {
      BidirectionalGraph::Node new_node;
      new_node.nnvmptr = n.get();
      nnvm2nid[n.get()] = static_cast<uint32_t>(nodes.size());
      nodes.emplace_back(std::move(new_node));
    });
    for (const auto& it : nnvm2nid) {
      nnvm::Node* nnvmnode = it.first;
      uint32_t nid = it.second;
      for (auto& n : nnvmnode->inputs) {
        uint32_t input_nid = nnvm2nid[n.node.get()];
        nodes[input_nid].outputs.emplace_back(&nodes[nid]);
        nodes[nid].inputs.emplace_back(&nodes[input_nid]);
      }
    }
    for (auto& e : g.outputs) {
      uint32_t nid = nnvm2nid[e.node.get()];
      outputs.emplace_back(&nodes[nid]);
    }
  }

  template <typename FVisit>
  void DFS(const std::vector<Node*>& heads, bool reverse, FVisit fvisit) {
    std::unordered_set<Node*> visited;
    std::vector<Node*> vec(heads.begin(), heads.end());
    visited.reserve(heads.size());
    while (!vec.empty()) {
      Node* vertex = vec.back();
      vec.pop_back();
      if (visited.count(vertex) == 0) {
        visited.insert(vertex);
        fvisit(vertex);
        std::vector<Node*> nexts = reverse ? vertex->inputs : vertex->outputs;
        for (Node* node : nexts) {
          if (visited.count(node) == 0) {
            vec.emplace_back(node);
          }
        }
      }
    }
  }

  using t_pairset = std::pair<std::unordered_set<Node*>, std::unordered_set<Node*>>;
  using t_pairvec = std::pair<std::vector<Node*>, std::vector<Node*>>;
  using t_uncomp_map = std::unordered_map<Node*, std::unordered_set<Node*>>;

  std::unordered_set<Node*> naive_grow_subgraph(Node* head,
                                                std::unordered_set<Node*>* set_unused,
                                                t_uncomp_map* uncomp_map) {
    std::unordered_set<Node*> subgraph;
    std::unordered_set<Node*> uncomp_set;
    std::deque<Node*> stack;
    stack.emplace_back(head);
    while (!stack.empty()) {
      Node* vertex = stack.back();
      stack.pop_back();
      if (set_unused->count(vertex) && !uncomp_set.count(vertex)) {
        set_unused->erase(vertex);
        subgraph.insert(vertex);
        uncomp_set.insert((*uncomp_map)[vertex].begin(), (*uncomp_map)[vertex].end());
        for (Node* input : vertex->inputs) {
          if (set_unused->count(input) && !uncomp_set.count(input)) {
            stack.emplace_back(input);
          }
        }
        for (Node* output : vertex->outputs) {
          if (set_unused->count(output) && !uncomp_set.count(output)) {
            stack.emplace_back(output);
          }
        }
      }
    }
    return subgraph;
  }

  std::vector<std::unordered_set<Node*>> get_subsets(
    std::unordered_map<std::string, NDArray>* const params_map) {
    std::vector<std::unordered_set<Node*>> subgraphs;
    std::unordered_set<Node*> set_nonTRTnodes;
    std::unordered_set<Node*> set_allnodes(nodes.size());
    std::vector<t_pairset> separation_sets;
    for (Node& node : nodes) {
      if (!IsTRTCompatible(node.nnvmptr)) {
        set_nonTRTnodes.insert(&node);
        std::unordered_set<Node*> in_graph;
        std::unordered_set<Node*> out_graph;
        std::vector<Node*> dummy_head;
        dummy_head.emplace_back(&node);
        DFS(dummy_head, false, [&out_graph](Node* node) {
          out_graph.insert(node);
        });
        DFS(dummy_head, true, [&in_graph](Node* node) {
          in_graph.insert(node);
        });
        separation_sets.emplace_back(std::make_pair(in_graph, out_graph));
      }
      set_allnodes.emplace(&node);
    }
    t_uncomp_map uncomp_map;
    std::unordered_set<Node*> set_TRTnodes;
    set_TRTnodes.insert(set_allnodes.begin(), set_allnodes.end());
    for (Node* n : set_nonTRTnodes) {
      set_TRTnodes.erase(n);
    }
    for (Node* n : set_TRTnodes) {
      for (t_pairset p : separation_sets) {
        if (p.first.count(n)) {
          uncomp_map[n].insert(p.second.begin(), p.second.end());
        } else if (p.second.count(n)) {
          uncomp_map[n].insert(p.first.begin(), p.first.end());
        }
      }
      for (Node* nonTRTn : set_nonTRTnodes) {
        uncomp_map[n].erase(nonTRTn);
      }
    }
    std::unordered_set<Node*> set_unused;
    set_unused.reserve(set_TRTnodes.size());

    for (auto& n : set_TRTnodes) {
      if (n->nnvmptr->attrs.op != nullptr || params_map->count(n->nnvmptr->attrs.name)) {
        set_unused.insert(n);
      }
    }
    std::unordered_set<Node*> visited;
    std::deque<Node*> stack(outputs.begin(), outputs.end());
    while (!stack.empty()) {
      Node* vertex = stack.front();
      stack.pop_front();
      if (!visited.count(vertex)) {
        visited.insert(vertex);
        if (set_unused.count(vertex)) {
          subgraphs.emplace_back(naive_grow_subgraph(vertex, &set_unused, &uncomp_map));
        }
        for (Node* input : vertex->inputs) {
          stack.emplace_back(input);
        }
      }
    }

    return subgraphs;
  }

 private:
  friend class Graph;

  bool IsTRTCompatible(nnvm::Node* nodeptr) {
    if (nodeptr->op() == nullptr) {
      return true;
    }

    const std::string op_name = nodeptr->op()->name;
    if (op_name == "Pooling") {
      return (nodeptr->attrs.dict.at("pool_type") == "avg" ||
          nodeptr->attrs.dict.at("pool_type") == "max");
    }

    if (unconditionalTRTop.count(op_name)) {
      return true;
    }

    if (op_name == "Activation") {
      return nodeptr->attrs.dict.at("act_type") == "relu" ||
        nodeptr->attrs.dict.at("act_type") == "tanh" ||
        nodeptr->attrs.dict.at("act_type") == "sigmoid";
    }

    return false;
  }
};  // class BidirectionalGraph

/*!
 * \brief function which transform std::vector<dmlc::any> back to Attrs (dmlc::any)
 */
const std::unordered_set<std::string> BidirectionalGraph::unconditionalTRTop = {
  "Convolution",
  "BatchNorm",
  "elemwise_add",
  "elemwise_sub",
  "elemwise_mul",
  "rsqrt",
  "pad",
  "Pad",
  "mean",
  "FullyConnected",
  "Flatten",
  "SoftmaxOutput",
};

using NodeEntrySet = std::unordered_set<nnvm::NodeEntry, nnvm::NodeEntryHash,
                                        nnvm::NodeEntryEqual>;

/*!
 * \brief get the output nodes of the subgraph in the main graph
 * \return a vector of the output nodes
*/
std::vector<nnvm::NodeEntry> GetSubgraphNodeEntries(Graph g,
    std::unordered_set<nnvm::Node*> set_subgraph) {
  std::vector<nnvm::NodeEntry> outputs;
  NodeEntrySet _outputs;
  for (auto& e : g.outputs) {
    if (set_subgraph.count(e.node.get())) {
      _outputs.insert(e);
    }
  }
  DFSVisit(g.outputs, [&set_subgraph, &_outputs](const nnvm::NodePtr &node){
    if (!set_subgraph.count(node.get())) {
      for (auto& e : node->inputs) {
        if (set_subgraph.count(e.node.get())) {
          _outputs.insert(e);
        }
      }
    }
  });
  outputs.insert(outputs.begin(), _outputs.begin(), _outputs.end());
  return outputs;
}

/*!
 * \brief get the nodes outside of the subgraph for which outputs are used in the subgraph
 * \return a vector the nodes
*/
std::vector<nnvm::NodeEntry> GetSubgraphInterfaceNodes(Graph g,
    std::unordered_set<nnvm::Node*> set_subgraph) {
  std::vector<nnvm::NodeEntry> inputs;
  NodeEntrySet _inputs;
  DFSVisit(g.outputs, [&set_subgraph, &_inputs](const nnvm::NodePtr &node){
    if (set_subgraph.count(node.get())) {
      for (auto& e : node->inputs) {
        if (!set_subgraph.count(e.node.get())) {
          _inputs.insert(e);
        }
      }
    }
  });
  inputs.insert(inputs.begin(), _inputs.begin(), _inputs.end());
  return inputs;
}

std::unordered_map<uint32_t, uint32_t> GetGraphInputsMap(const Graph& g) {
  std::unordered_map<uint32_t, uint32_t> outputs;
  auto& idx = g.indexed_graph();
  outputs.reserve(idx.num_nodes());
  std::vector<uint32_t> input_nodes = idx.input_nodes();
  for (size_t i = 0; i < input_nodes.size(); ++i) {
    outputs[input_nodes[i]] = static_cast<uint32_t>(i);
  }
  return outputs;
}

/*!
 * \brief Dummy function which creates a fake TensorRT Node
 */
nnvm::NodePtr ConvertNnvmGraphToOnnx(const nnvm::Graph &g,
                                     std::unordered_map<std::string, NDArray>* const params_map) {
  auto p = nnvm::Node::Create();
  p->attrs.op = nnvm::Op::Get("_trt_op");
  op::ONNXParam onnx_param = op::nnvm_to_onnx::ConvertNnvmGraphToOnnx(g, params_map);
  p->attrs.dict["serialized_output_map"] = onnx_param.serialized_output_map;
  p->attrs.dict["serialized_input_map"]  = onnx_param.serialized_input_map;
  p->attrs.dict["serialized_onnx_graph"] = onnx_param.serialized_onnx_graph;
  if (p->op()->attr_parser != nullptr) {
    p->op()->attr_parser(&(p->attrs));
  }
  return p;
}

/*!
 * \brief Update attributes of the graph (such as some inputs properties)
 */
Graph UpdateSubgraphAttrs(Graph&& subgraph, const Graph& g,
                          const std::unordered_map<nnvm::Node*, nnvm::NodePtr>& old2new,
                          const nnvm::NodeEntryMap<nnvm::NodeEntry>& main_input_entry_to_sub) {
  const auto& idx     = g.indexed_graph();
  const auto& sub_idx = subgraph.indexed_graph();

  const auto& shape               = g.GetAttr<mxnet::ShapeVector>("shape");
  const auto& dtype               = g.GetAttr<nnvm::DTypeVector>("dtype");
  const auto& storage_type        = g.GetAttr<StorageTypeVector>("storage_type");
  const auto& shape_inputs        = g.GetAttr<mxnet::ShapeVector>("shape_inputs");
  const auto& dtype_inputs        = g.GetAttr<nnvm::DTypeVector>("dtype_inputs");
  const auto& storage_type_inputs = g.GetAttr<StorageTypeVector>("storage_type_inputs");

  mxnet::ShapeVector sub_shape(sub_idx.num_node_entries());
  nnvm::DTypeVector sub_dtype(sub_idx.num_node_entries());
  StorageTypeVector sub_storage_type(sub_idx.num_node_entries());
  mxnet::ShapeVector sub_shape_inputs(sub_idx.input_nodes().size());
  nnvm::DTypeVector sub_dtype_inputs(sub_idx.input_nodes().size());
  StorageTypeVector sub_storage_type_inputs(sub_idx.input_nodes().size());

  const std::unordered_map<uint32_t, uint32_t> inputsindex2pos     = GetGraphInputsMap(g);
  const std::unordered_map<uint32_t, uint32_t> sub_inputsindex2pos = GetGraphInputsMap(subgraph);
  // map attributes from graph to subgraph
  for (auto& p : old2new) {
    const uint32_t nid     = idx.node_id(p.first);
    const uint32_t sub_nid = sub_idx.node_id(p.second.get());
    const nnvm::Op* op = sub_idx[sub_nid].source->op();
    if (op == nullptr) {  // if it's an input node, there is only one output node entry
      const uint32_t sub_i       = sub_idx.entry_id(sub_nid, 0);
      const uint32_t sub_input_i = sub_inputsindex2pos.at(sub_nid);
      const uint32_t i           = idx.entry_id(nid, 0);

      sub_shape[sub_i] = shape[i];
      sub_dtype[sub_i] = dtype[i];
      sub_storage_type[sub_i]       = storage_type[i];
      sub_shape_inputs[sub_input_i] = shape_inputs[inputsindex2pos.at(nid)];
      sub_dtype_inputs[sub_input_i] = dtype_inputs[inputsindex2pos.at(nid)];
      sub_storage_type_inputs[sub_input_i] = storage_type_inputs[inputsindex2pos.at(nid)];

    } else {
      for (size_t oi = 0; oi < op->num_outputs; ++oi) {
        const uint32_t sub_i = sub_idx.entry_id(sub_nid, oi);
        const uint32_t i = idx.entry_id(nid, oi);
          sub_shape[sub_i] = shape[i];
          sub_dtype[sub_i] = dtype[i];
          sub_storage_type[sub_i] = storage_type[i];
      }
    }
  }
  // old2new doesn't contain placeholder / interfaces
  for (auto& p : main_input_entry_to_sub) {
    nnvm::NodeEntry main_entry = p.first;
    nnvm::NodeEntry sub_entry = p.second;
    const uint32_t sub_nid = sub_idx.node_id(sub_entry.node.get());
    const uint32_t sub_i = sub_idx.entry_id(sub_entry);
    const uint32_t i = idx.entry_id(main_entry);
    const uint32_t sub_input_i = sub_inputsindex2pos.at(sub_nid);
    sub_shape[sub_i] = shape[i];
    sub_dtype[sub_i] = dtype[i];
    sub_storage_type[sub_i] = storage_type[i];
    sub_shape_inputs[sub_input_i] = sub_shape[sub_i];
    sub_dtype_inputs[sub_input_i] = sub_dtype[sub_i];
    sub_storage_type_inputs[sub_input_i] = sub_storage_type[sub_i];
  }
  subgraph.attrs["shape"] =
      std::make_shared<dmlc::any>(std::move(sub_shape));
  subgraph.attrs["dtype"] =
      std::make_shared<dmlc::any>(std::move(sub_dtype));
  subgraph.attrs["storage_type"] =
      std::make_shared<dmlc::any>(std::move(sub_storage_type));
  subgraph.attrs["shape_inputs"] =
      std::make_shared<dmlc::any>(std::move(sub_shape_inputs));
  subgraph.attrs["dtype_inputs"] =
      std::make_shared<dmlc::any>(std::move(sub_dtype_inputs));
  subgraph.attrs["storage_type_inputs"] =
      std::make_shared<dmlc::any>(std::move(sub_storage_type_inputs));

  return subgraph;
}

/*!
 * \brief Generate a name for a new TRT node, avoid collision if some TRT_nodes are already defined
 */
const std::string GetNewTrtName(const Graph& g, const Graph& subgraph) {
  const std::string name_prefix("TRT_node");
  std::unordered_set<std::string> name_set;
  DFSVisit(g.outputs, [&name_set, &name_prefix](const nnvm::NodePtr& node) {
    if (node->attrs.name.compare(0, name_prefix.size(), name_prefix) == 0) {
      name_set.insert(node->attrs.name);
    }
  });
  // name inside the subgraph will be avaible as they will be removed
  DFSVisit(subgraph.outputs, [&name_set, &name_prefix](const nnvm::NodePtr& node) {
    if (node->attrs.name.compare(0, name_prefix.size(), name_prefix) == 0) {
      name_set.erase(node->attrs.name);
    }
  });
  uint32_t name_suffix = 0;
  std::string full_name = name_prefix + std::to_string(name_suffix);
  while (name_set.count(full_name)) {
    full_name = name_prefix + std::to_string(++name_suffix);
  }
  return full_name;
}

/*!
 * \brief helper function to display what nodes are in a specific subset
 */
void dispNodesSet(Graph g, std::unordered_set<nnvm::Node*> s) {
  DFSVisit(g.outputs, [&s](const nnvm::NodePtr n){
    if (s.count(n.get())) {
      std::cout << "  Y " << n->attrs.name << std::endl;
    } else {
      std::cout << "  N " << n->attrs.name << std::endl;
    }
  });
}

/*!
 * \brief Replace a set of nodes by a TensorRT node
 */
Graph ReplaceSubgraph(Graph&& g,
                      const std::unordered_set<nnvm::Node*>& set_subgraph,
                      std::unordered_map<std::string, NDArray>* const params_map) {
  // Create MXNet subgraph
  Graph subgraph;

  const auto sub_outputs_in_main = GetSubgraphNodeEntries(g, set_subgraph);
  subgraph.outputs = sub_outputs_in_main;
  // old2new will link raw pointer of the nodes in the graph to
  // the corresponding shared_ptr of the nodes in the generated subgraph
  std::unordered_map<nnvm::Node*, nnvm::NodePtr> old2new;
  std::deque<nnvm::Node*> stack;
  std::unordered_set<nnvm::Node*> visited;
  int32_t reservation = set_subgraph.size();
  old2new.reserve(reservation);
  visited.reserve(reservation);

  // Create the shared_ptr using the same raw pointer don't really matter
  for (auto& n : set_subgraph) {
    old2new[n] = std::make_shared<nnvm::Node>(*n);
  }

  // To generate a subgraph an input have to be replace by data node (no op)
  // and it have to be agnostic to the node from which it's an output
  // (For exemple even if two inputs are two different outputs from the same node)
  nnvm::NodeEntryMap<nnvm::NodeEntry> main_input_entry_to_sub;
  for (auto& e : GetSubgraphInterfaceNodes(g, set_subgraph)) {
    auto node = nnvm::Node::Create();
    node->attrs.name = e.node->attrs.name + "_" + std::to_string(e.index);
    auto new_e = nnvm::NodeEntry{node, 0, 0};
    main_input_entry_to_sub[e] = new_e;
  }

  for (nnvm::NodeEntry& e : subgraph.outputs) {
    e.node = old2new[e.node.get()];
    stack.emplace_back(e.node.get());
  }
  // link all nodes in the subgraph to nodes in the subgraph instead of main graph
  while (!stack.empty()) {
    auto vertex = stack.front();
    stack.pop_front();
    if (!visited.count(vertex)) {
      visited.insert(vertex);
      for (auto& e : vertex->inputs) {
        auto it = main_input_entry_to_sub.find(e);
        if (it != main_input_entry_to_sub.end()) {
          e = it->second;
        } else {
          e.node = old2new[e.node.get()];
        }
      stack.emplace_back(e.node.get());
      }
    }
  }
  // Remove the control dependencies of the subgraph to nodes that are not in the subgraph
  DFSVisit(subgraph.outputs, [&set_subgraph, &old2new](const nnvm::NodePtr& node) {
    std::remove_if(node->control_deps.begin(),
                   node->control_deps.end(),
                   [&set_subgraph](nnvm::NodePtr n_ptr) {
                    return !set_subgraph.count(n_ptr.get());
                   });
    for (nnvm::NodePtr& n_ptr : node->control_deps) {
      n_ptr = old2new[n_ptr.get()];
    }
  });

  subgraph = UpdateSubgraphAttrs(std::move(subgraph), g, old2new, main_input_entry_to_sub);
  auto& sub_idx = subgraph.indexed_graph();

  auto trtnodeptr = ConvertNnvmGraphToOnnx(subgraph, params_map);
  trtnodeptr->attrs.name = GetNewTrtName(g, subgraph);

  // Insert new trt node and unplug replaced nodes
  std::unordered_map<uint32_t, nnvm::NodeEntry> sub_input_entryid_to_main;
  for (auto& p : main_input_entry_to_sub) {
    sub_input_entryid_to_main[sub_idx.entry_id(p.second)] = p.first;
  }

  // Plug the nodes from the main graph as inputs of the trt node
  trtnodeptr->inputs.resize(main_input_entry_to_sub.size());
  {
    uint32_t counter = 0;
    for (uint32_t i : sub_idx.input_nodes()) {
      auto it = sub_input_entryid_to_main.find(sub_idx.entry_id(i, 0));
      if (it != sub_input_entryid_to_main.end()) {
        trtnodeptr->inputs[counter++] = it->second;
      }
    }
  }
  nnvm::NodeEntryMap<uint32_t> sub_outputs_in_main_to_pos;
  for (uint32_t i = 0; i < sub_outputs_in_main.size(); ++i) {
    sub_outputs_in_main_to_pos[sub_outputs_in_main[i]] = i;
  }
  // Plug the trt node as inputs to the main graph nodes
  DFSVisit(g.outputs, [&sub_outputs_in_main_to_pos, &trtnodeptr](const nnvm::NodePtr& n) {
    for (auto& e : n->inputs) {
      auto it = sub_outputs_in_main_to_pos.find(e);
      if (it != sub_outputs_in_main_to_pos.end()) {
        e.index = it->second;
        e.node = trtnodeptr;
      }
    }
  });

  for (auto& output : g.outputs) {
    auto it = sub_outputs_in_main_to_pos.find(output);
    if (it != sub_outputs_in_main_to_pos.end()) {
      output.index = it->second;
      output.node = trtnodeptr;
    }
  }

  Graph new_graph;
  new_graph.outputs = g.outputs;
  return new_graph;
}

std::vector<std::unordered_set<nnvm::Node*>> GetTrtCompatibleSubsets(const Graph& g,
    std::unordered_map<std::string, NDArray>* const params_map) {
  BidirectionalGraph biG = BidirectionalGraph(g);
  std::vector<std::unordered_set<BidirectionalGraph::Node*>> subsets = biG.get_subsets(params_map);
  std::vector<std::unordered_set<nnvm::Node*>> nnvm_subsets(subsets.size(),
                                                            std::unordered_set<nnvm::Node*>());
  for (size_t i = 0; i < subsets.size(); ++i) {
    nnvm_subsets[i].reserve(subsets[i].size());
    for (auto& n : subsets[i]) {
      nnvm_subsets[i].insert(n->nnvmptr);
    }
  }
  return nnvm_subsets;
}

}  // namespace exec
}  // namespace mxnet

#endif  // MXNET_USE_TENSORRT


text: Este Repositorio es una prueba para GitHub


text:
package org.xtreemfs.babudb.sandbox;

import java.io.File;
import java.util.Map.Entry;

import org.xtreemfs.babudb.api.database.ResultSet;
import org.xtreemfs.babudb.index.DefaultByteRangeComparator;
import org.xtreemfs.babudb.index.LSMTree;
import org.xtreemfs.babudb.index.writer.DiskIndexWriter;

public class LSMTreePerformanceTest {

    public static void main(String[] args) throws Exception {

        if (args.length != 4) {
            System.out.println("usage: java " + LSMTreePerformanceTest.class.getCanonicalName()
                + " <db_file> <num_entries> <num_inserts> <num_lookups>");
            System.exit(1);
        }

        final String path = args[0];
        final int entriesPerBlock = 16;

        final int minStrLen = 1;
        final int maxStrLen = 8;
        final char minChar = 48;
        final char maxChar = 122;

        final int size = Integer.parseInt(args[1]);
        final int inserts = Integer.parseInt(args[2]);
        final int lookups = Integer.parseInt(args[3]);

        // TODO: make configurable
        final int blockFileSize = 1024 * 1024 * 1024;

        if (size != 0) {
            // delete old index file
            new File(path).delete();

            System.out.println("creating new database with " + size + " random entries ...");

            // write the map to a disk index
            DiskIndexWriter index = new DiskIndexWriter(path, entriesPerBlock, false, blockFileSize);
            index.writeIndex(new ResultSet<Object, Object>() {

                private int    count;

                private String next = minChar + "";

                @Override
                public boolean hasNext() {
                    return count < size;
                }

                @Override
                public Entry<Object, Object> next() {

                    count++;
                    next = createNextString(next, minStrLen, maxStrLen, minChar, maxChar);

                    return new Entry<Object, Object>() {

                        @Override
                        public Object getKey() {
                            return next.getBytes();
                        }

                        @Override
                        public Object getValue() {
                            return next.getBytes();
                        }

                        @Override
                        public Object setValue(Object value) {
                            throw new UnsupportedOperationException();
                        }

                    };
                }

                @Override
                public void remove() {
                    throw new UnsupportedOperationException();
                }

                @Override
                public void free() {

                }

            });
        }

        // read the LSM tree
        LSMTree tree = new LSMTree(path, new DefaultByteRangeComparator(), false, 16, 1024 * 1024 * 512, true, -1);

        System.out.println("inserting " + inserts + " random elements ...");
        for (int i = 0; i < inserts; i++) {
            byte[] entry = createRandomString(minChar, maxChar, minStrLen, maxStrLen).getBytes();
            tree.insert(entry, entry);
        }

        // Iterator<Entry<ReusableBuffer, ReusableBuffer>> it =
        // tree.prefixLookup(null);
        // while (it.hasNext())
        // System.out.println(new String(it.next().getKey().array()));
        //
        System.out.println("performing " + lookups + " random lookups ...");

        // look up each element
        int hits = 0;
        long t0 = System.currentTimeMillis();
        for (int i = 0; i < lookups; i++) {

            byte[] key = createRandomString(minChar, maxChar, minStrLen, maxStrLen).getBytes();
            byte[] result = tree.lookup(key);
            if (result != null)
                hits++;

            if (i % 100000 == 0)
                System.out.println(i);
        }

        long time = System.currentTimeMillis() - t0;

        System.out.println(time + " ms");
        System.out.println((long) lookups * 1000 / time + " lookups/s");
        System.out.println("hits: " + hits + " / " + lookups);
    }

    private static String createNextString(String st, int minStrLen, int maxStrLen, char minChar, char maxChar) {

        char[] chars = st.toCharArray();

        for (;;) {

            double rnd = Math.random();

            if (rnd < .1f + .8f / chars.length && chars.length < maxStrLen) {

                // append character
                char[] chars2 = new char[chars.length + 1];
                System.arraycopy(chars, 0, chars2, 0, chars.length);
                chars2[chars2.length - 1] = createRandomChar(minChar, maxChar);
                return new String(chars2);

            } else if (rnd > .95f + .05f / chars.length && chars.length > minStrLen) {

                int i = chars.length - 2;
                for (; i >= 0; i--)
                    if (chars[i] < maxChar)
                        break;

                if (i == -1)
                    continue;

                // increment character and truncate
                char[] chars2 = new char[i + 1];
                System.arraycopy(chars, 0, chars2, 0, chars2.length);
                chars2[chars2.length - 1]++;
                return new String(chars2);

            } else if (chars[chars.length - 1] < maxChar) {

                // increment last character
                chars[chars.length - 1]++;
                return new String(chars);
            }
        }
    }

    private static String createRandomString(char minChar, char maxChar, int minLength, int maxLength) {

        char[] chars = new char[(int) (Math.random() * (maxLength + 1)) + minLength];
        for (int i = 0; i < chars.length; i++)
            chars[i] = createRandomChar(minChar, maxChar);

        return new String(chars);
    }

    private static char createRandomChar(char minChar, char maxChar) {
        return (char) (Math.random() * (maxChar - minChar + 1) + minChar);
    }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.9.1"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>libfly: std::hash< fly::Json > Struct Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="doxygen-awesome.css" rel="stylesheet" type="text/css"/>

libfly
    6.2.2

C++20 utility library for Linux, macOS, and Windows

Public Member Functions |
List of all members

std::hash< fly::Json > Struct Reference

Public Member Functions

std::size_t 	operator() (const fly::Json &json) const

Member Function Documentation

◆ operator()()

          std::size_t std::hash< fly::Json >::operator()
          (
          const fly::Json &
          json	)
           const

inline

Hash a JSON value using std::hash specializations for the underlying JSON types.

Parameters

json	The JSON value to hash.

Returns

The hashed JSON value.

The documentation for this struct was generated from the following file:

fly/types/json/json.hpp

std

hash< fly::Json >

Generated by  1.9.1


text:
package com.emc.vipr.model.keystore;

import javax.xml.bind.annotation.*;
import java.util.List;

@XmlRootElement(name = "rotate_keycertchain")
@XmlAccessorType(XmlAccessType.PROPERTY)
public class ObjectSvcRotateKeyAndCertParam {
    private List<String> ipList;
    private Boolean systemSelfSigned;
    private KeyAndCertificateChain keyCertChain;

    @XmlElementWrapper(name = "ip_addresses")
    @XmlElement(name = "ip_address")
    public List<String> getIpAddresses() {
        return ipList;
    }

    public void setIpAddresses(List<String> ipAddresses) {
        this.ipList = ipAddresses;
    }

    @XmlElement(name = "system_selfsigned")
    public Boolean getSystemSelfSigned() {
        return systemSelfSigned;
    }

    public void setSystemSelfSigned(Boolean systemSelfSigned) {
        this.systemSelfSigned = systemSelfSigned;
    }

    @XmlElement(name = "key_and_certificate")
    public KeyAndCertificateChain getKeyCertChain() {
        return keyCertChain;
    }

    public void setKeyCertChain(KeyAndCertificateChain keyCertChain) {
        this.keyCertChain = keyCertChain;
    }
}


text:
//
//  GKConstants.h
//  CHGank
//
//  Created by ChiHo on 6/2/16.
//  Copyright © 2016 ChiHo. All rights reserved.
//

#ifndef GKConstants_h
#define GKConstants_h

static const NSInteger kNetworkServerErrorCode = 2727;
#ifdef DEBUG
static NSString *const kAppDomain = @"http://gank.io/api";
static const NSInteger kNetworkRetryTimes = 2;
static const NSTimeInterval kNetworkTimeoutInterval = 4;
#else
static NSString *const kAppDomain = @"http://gank.io/api";
static const NSInteger kNetworkRetryTimes = 2;
static const NSTimeInterval kNetworkTimeoutInterval = 4;
#endif

#define color_d3ccc6 RGB(0xd3, 0xcc, 0xc6)
#define color_fffcf2 RGB(0xff, 0xfc, 0xf2)
#define color_fffdf8 RGB(0xff, 0xfd, 0xf8)
#define color_4f331a RGB(0x4f, 0x33, 0x1a)
#define color_c4bbb2 RGB(0xc4, 0xbb, 0xb2)
#define color_7a8b9f RGB(0x7a, 0x8b, 0x9f)
#define color_ebe8d8 RGB(0xeb, 0xe8, 0xd8)
#define color_b5bbc4 RGB(0xb5, 0xbb, 0xc4)

#endif /* GKConstants_h */


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Ann. Rep. Reg. St. N. Y. 23: 122 (1872)

#### Original name
Cantharellus minor Peck, 1872

### Remarks
null


text:
cask 'packages' do
  version '1.2.3'
  sha256 '77e88cf1b02cee232ece0c24c61e30da20274f3c0e1a6107d06030dd126d677c'

  url 'http://s.sudre.free.fr/Software/files/Packages.dmg'
  appcast 'http://s.sudre.free.fr/Software/documentation/RemoteVersion.plist'
  name 'Packages'
  homepage 'http://s.sudre.free.fr/Software/Packages/about.html'

  pkg 'packages/Packages.pkg'

  uninstall script: 'Extras/uninstall.sh'
end


text:
package de.kaiserpfalzedv.office.contacts.api.addresses;

import de.kaiserpfalzedv.office.contacts.api.city.City;

/**
 * @author klenkes {@literal <rlichti@kaiserpfalz-edv.de>}
 * @version 1.0.0
 * @since 2017-08-08
 */
public interface PostalAddress extends Address {
    City getCity();
}


text:
Fuzz testing for `parse` using [go-fuzz](https://github.com/dvyukov/go-fuzz). Pull requests to add more corpora or testers are appreciated.

To run the tests, install `go-fuzz`:

```
go get -u github.com/dvyukov/go-fuzz/go-fuzz github.com/dvyukov/go-fuzz/go-fuzz-build

cd $GOPATH/github.com/tdewolff/parse/tests/number

go-fuzz-build
go-fuzz -bin fuzz-fuzz.zip
```

If restarts is not close to `1/10000`, something is probably wrong. If not finding new corpus for a while, restart the fuzzer.


text:
<!DOCTYPE html>

<title>How do I override a course grade in Gradebook Classic?</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta content="sakai.gradebook.tool" name="description">
<meta content="manual grade change" name="search">
<link href="/library/skin/tool_base.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">
<link href="/library/skin/morpheus-default/tool.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">
<link href="/library/skin/morpheus-default/help.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">
<link href="/library/js/jquery/featherlight/0.4.0/featherlight.min.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">

How do I override a course grade in Gradebook Classic?

Note: When manually entering a course grade, you must use the appropriate grade type for the gradebook in which you are working. For example, if the course is graded on a simple letter grade scale, you will only be able to enter the letters A, B, C, D, or F. If the course is graded on a standard letter grade scale, you will also be able to add  +  (plus sign) or  -  (minus sign) to the letter grade. If the course is graded on a Pass/Not pass scale, you will only be able to enter the letters P or N.

Go to Gradebook Classic.

Select the Gradebook Classic tool from the Tool Menu of your site.

Click Course Grades.

              Zoom

Enter override score.

              Zoom

You will see a list of enrolled students and their calculated course grades. In the "Grade Override" column.

Enter the new course grade(s) to replace the autocalculated grade(s)

Click Save Changes.

Note: Once you save the grade override, a log icon will appear next to each modified grade which displays the time, date, grade information, and name of the person who changed the grade manually.


text:
package com.ait.lienzo.client.core.shape.toolbox.items;

public abstract class AbstractDecoratorItem<T extends AbstractDecoratorItem>
        extends AbstractPrimitiveItem<T>
        implements DecoratorItem<T> {

    protected abstract void doShow();

    protected abstract void doHide();

    public abstract T copy();

    @Override
    public final T show() {
        doShow();
        return batch();
    }

    @Override
    public final T hide() {
        doHide();
        return batch();
    }

    @Override
    public void destroy() {
        asPrimitive().removeFromParent();
    }

    @SuppressWarnings("unchecked")
    private T batch() {
        if (null != asPrimitive().getLayer()) {
            asPrimitive().getLayer().batch();
        }
        return (T) this;
    }
}


text:
//
// Created by Aidan Campbell on 3/15/15.
//
#ifndef _MAINH_
#define _MAINH_

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <sys/types.h>

#define NONE 0
#define LEFTTORIGHT 1
#define RIGHTTOLEFT 2
#define NUM_SEMS 3
#define WAIT -1
#define SIGNAL 1
#define MUTEX 0
#define LEFTBOUND 1
#define RIGHTBOUND 2

struct common {
    int crossing;//number of cars crossing
    int crossed;//number of cars that have crossed in this current direction iteration
    int leftToRightWaiting;//number of rightbound cars waiting
    int rightToLeftWaiting;//number of leftbound cars waiting
    int direction;//enumerated direction as NONE, LEFTTORIGHT, or RIGHTTOLEFT
    int semkey;
    int shmkey;
};

union semun {
    int              val;    /* Value for SETVAL */
    struct semid_ds *buf;    /* Buffer for IPC_STAT, IPC_SET */
    unsigned short  *array;  /* Array for GETALL, SETALL */
    struct seminfo  *__buf;  /* Buffer for IPC_INFO
                                (Linux-specific) */
};

int safesemget();
int safeshmget();
int main();
void makeLeftToRight(struct common*);
void makeRightToLeft(struct common*);
struct common * initializeSharedMemory(int, int);
#endif


text:
// @ts-check
const axios = require('axios').default;
const cheerio = require('cheerio');

/**
 * @typedef {Object} IndexData
 * @property {number} page
 * @property {number} pagePrev
 * @property {number} pageMax
 * @property {Release} latestTranslation
 *
 * @typedef {Object} Release
 * @property {string} title
 * @property {ReleaseRow[]} data
 *
 * @typedef {Object} ReleaseRow
 * @property {TitleRow} title
 * @property {GroupRow} group
 * @property {ChapterRow} chapter
 *
 * @typedef {Object} TitleRow
 * @property {string} title
 * @property {string} url
 *
 * @typedef {Object} GroupRow
 * @property {string} group
 * @property {string} url
 *
 * @typedef {Object} ChapterRow
 * @property {string} chapter
 * @property {string} url
 */

/**
 * @param {number} page
 * @returns {Promise<IndexData>}
 */
const getIndexData = (page = 1) => getPageWithData(page).then($ => extractData($))

/**
 *
 * @param {CheerioStatic} $
 * @returns {IndexData}
 */
const extractData = ($) => ({
    page: getReleasePage($) || 1,
    pagePrev: getReleasePage($) - 1 || 1,
    pageMax: getReleasePageMax($) || 1,
    latestTranslation: getRelease($)
});

/**
 * @param {CheerioStatic} $
 * @returns {number}
 */
const getReleasePage = $ => parseInt($('.digg_pagination').find('em').text().trim());

/**
 * @param {CheerioStatic} $
 * @returns {number}
 */
const getReleasePageMax = ($) => {
    let last = $('.digg_pagination').children().last();

    if (last.hasClass('current')) {
        return parseInt(last.text().trim());
    } else {
        return parseInt(last.prev().text().trim());
    }
};

/**
 * @param {CheerioStatic} $
 * @returns {Release}
 */
const getRelease = ($) => {
    return $('#myTable').map((i, el) => {
        el = $(el);
        return {
            title: el.prev().text(),
            data: el.find('tr').map((i2, el2) => {
                el2 = $(el2);
                if (el2.find('a').first().text()) {
                    return {
                        title: {
                            title: el2.find('a').first().attr('title'),
                            url: el2.find('a').first().attr('href')
                        },
                        group: {
                            group: el2.find('a').last().text().trim(),
                            url: el2.find('a').last().attr('href')
                        },
                        chapter: {
                            chapter: el2.find('.chp-release').first().text(),
                            url: el2.find('.chp-release').first().attr('href')
                        }
                    };
                }
            }).get()
        };
    }).get();
};

/**
 * @param {number} page
 * @returns {Promise<CheerioStatic>}
 */
const getPageWithData = async (page = 1) => {
    const response = await axios(`https://www.novelupdates.com/?pg=${page}`)
    if (response.status >= 400) {
        throw new Error("Bad response from server");
    }

    return cheerio.load(response.data)
};

module.exports = getIndexData;


text:
package com.svbio.cloudkeeper.model.beans.element.module;

import com.svbio.cloudkeeper.model.bare.element.module.BareCompositeModuleDeclaration;
import com.svbio.cloudkeeper.model.bare.element.module.BareModuleDeclarationVisitor;
import com.svbio.cloudkeeper.model.beans.CopyOption;

import javax.annotation.Nullable;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.Objects;

@XmlRootElement(name = "composite-module-declaration")
public final class MutableCompositeModuleDeclaration
        extends MutableModuleDeclaration<MutableCompositeModuleDeclaration>
        implements BareCompositeModuleDeclaration {
    private static final long serialVersionUID = -2930636903424679052L;

    @Nullable
    private MutableCompositeModule template;

    public MutableCompositeModuleDeclaration() { }

    private MutableCompositeModuleDeclaration(BareCompositeModuleDeclaration original, CopyOption[] copyOptions) {
        super(original, copyOptions);
        template = MutableCompositeModule.copyOfCompositeModule(original.getTemplate(), copyOptions);
    }

    @Nullable
    public static MutableCompositeModuleDeclaration copyOfCompositeModuleDeclaration(
            @Nullable BareCompositeModuleDeclaration original, CopyOption... copyOptions) {
        return original == null
            ? null
            : new MutableCompositeModuleDeclaration(original, copyOptions);
    }

    @Override
    public boolean equals(@Nullable Object otherObject) {
        if (this == otherObject) {
            return true;
        } else if (!super.equals(otherObject)) {
            return false;
        }
        return Objects.equals(template, ((MutableCompositeModuleDeclaration) otherObject).template);
    }

    @Override
    public int hashCode() {
        return 31 * super.hashCode() + Objects.hashCode(template);
    }

    @Override
    public String toString() {
        return BareCompositeModuleDeclaration.Default.toString(this);
    }

    @Override
    protected MutableCompositeModuleDeclaration self() {
        return this;
    }

    @Override
    @Nullable
    public <T, P> T accept(BareModuleDeclarationVisitor<T, P> visitor, @Nullable P parameter) {
        return visitor.visit(this, parameter);
    }

    @XmlElement
    @Override
    @Nullable
    public MutableCompositeModule getTemplate() {
        return template;
    }

    public MutableCompositeModuleDeclaration setTemplate(@Nullable MutableCompositeModule template) {
        this.template = template;
        return this;
    }
}


text:
export function clone(obj: any): any {
    let copy: any;

    // Handle the 3 simple types (boolean, number, string), and null or undefined
    if (null == obj || "object" != typeof obj) return obj;

    // Handle Date
    if (obj instanceof Date) {
        copy = new Date();
        copy.setTime(obj.getTime());
        return copy;
    }

    // Handle Array
    if (obj instanceof Array) {
        copy = [];
        for (let i = 0, len = obj.length; i < len; i++) {
            copy[i] = clone(obj[i]);
        }
        return copy;
    }

    // Handle Object
    if (obj instanceof Object) {
        copy = {};
        for (let attr in obj) {
            if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
        }
        return copy;
    }

    throw new Error("Unable to copy obj! Its type isn't supported.");
}


text:
%close all;
%clear classes;

defaultIntegrationDuration  = 100;
% use raw data (no additional pre-processing)
dataTypes                   = WideField.CONSTANTS.ORIGINAL;
% don't care (gaussian spread will be used)
gaussSigma          = 1;
% band-pass filter parameters
load('./Data/OrientationColumnFilterParams.mat','meanBandPassParams');

for i = 1:length(dataTypes)
    [~, uniformBlocks_200ms,naturalBlocks_200ms] = ...
        getNeuralPerformance_200ms_stimulus(dataTypes(i), ...
            defaultIntegrationDuration, ...
            meanBandPassParams, ...
            gaussSigma);
end

numSampleCrit       = 0;
validThreshLimit    = 1;
decoderList         = [1,2];
decoderDesc{1} = 'RETINOTOPY (whitened)';
decoderDesc{2} = 'COLUMNS (separate block)';
plotPerformances_200ms_stimulus(dataTypes, decoderList, decoderDesc, numSampleCrit, validThreshLimit);


text:
<?php

namespace Warden;

/**
 * Events class to keep track of the various event stages
 *
 * @package Warden
 * @author Dan Cox
 */
final class WardenEvents
{
    /**
     * The event name for when warden starts
     *
     * @var String
     */
    const WARDEN_START = 'warden.start';

    /**
     * The event name for when warden ends
     *
     * @var String
     */
    const WARDEN_END = 'warden.end';

    /**
     * The event name for when a governor method is called
     *
     * @var String
     */
    const BEFORE_METHOD = 'before.method';

    /**
     * The event name for after governor method execution
     *
     * @var String
     */
    const AFTER_METHOD = 'after.method';

} // END class WardenEvents


text:
"""Google Cloud Speech-to-Text sample application using gRPC for async
batch processing.
"""

# [START speech_transcribe_async]
def transcribe_file(speech_file):
    """Transcribe the given audio file asynchronously."""
    from google.cloud import speech

    client = speech.SpeechClient()

    # [START speech_python_migration_async_request]
    with open(speech_file, "rb") as audio_file:
        content = audio_file.read()

    """
     Note that transcription is limited to a 60 seconds audio file.
     Use a GCS file for audio longer than 1 minute.
    """
    audio = speech.RecognitionAudio(content=content)

    config = speech.RecognitionConfig(
        encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
        sample_rate_hertz=16000,
        language_code="en-US",
    )

    # [START speech_python_migration_async_response]

    operation = client.long_running_recognize(config=config, audio=audio)
    # [END speech_python_migration_async_request]

    print("Waiting for operation to complete...")
    response = operation.result(timeout=90)

    # Each result is for a consecutive portion of the audio. Iterate through
    # them to get the transcripts for the entire audio file.
    for result in response.results:
        # The first alternative is the most likely one for this portion.
        print(u"Transcript: {}".format(result.alternatives[0].transcript))
        print("Confidence: {}".format(result.alternatives[0].confidence))
    # [END speech_python_migration_async_response]

# [END speech_transcribe_async]


text:
module Azure::EventGrid::Mgmt::V2020_04_01_preview
  module Models
    #
    # Defines values for EventChannelProvisioningState
    #
    module EventChannelProvisioningState
      Creating = "Creating"
      Updating = "Updating"
      Deleting = "Deleting"
      Succeeded = "Succeeded"
      Canceled = "Canceled"
      Failed = "Failed"
    end
  end
end


text:
using System.Reflection;

[assembly: AssemblyCopyright("Copyright © Wojciech Kotlarski 2013")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]


text:
"""Test jarvis.websearch module."""

###############################################################################
# Module Imports
###############################################################################

from jarvis import lex
from jarvis.tests.utils import run

###############################################################################

def test_wikipedia_simple():
    assert run('.w music') == lex.wikipedia.result(title='Music')

def test_wikipedia_ambiguous():
    assert run('.w mercury') == lex.unclear

def test_wikipedia_not_found():
    assert run('.w sdfgdhfghe') == lex.wikipedia.not_found

def test_wikipedia_bracket_escaping():
    assert str(run('.w probability field'))

###############################################################################

def test_youtube_search_simple():
    assert run('.y I like trains') == lex.youtube.result(
        video_id='hHkKJfcBXcw')

def test_youtube_mssing_likes():
    assert (
        run('https://www.youtube.com/watch?v=llIAae61QHk') ==
        lex.youtube.result(title='Защитники - Официальный тизер!'))

def test_youtube_curly_braces():
    assert str(run('https://www.youtube.com/watch?v=DNNOeEDB19E'))

def test_youtube_whatever():
    assert str(run('https://www.youtube.com/watch?v=T1Hklvc-vx0'))

###############################################################################

def test_translate_simple():
    assert (
        run('.trans en-ru teapot') == lex.translate.result(text=['чайничек']))

def test_translate_detect_language():
    assert run('.trans en белочки') == lex.translate.result(text=['squirrels'])

def test_translate_garbage_text():
    assert run('.trans en-ru gsjdhfgsjld') == lex.translate.result

def test_translate_garbage_lang():
    assert run('.trans 1011-en text in robot language') == lex.translate.error

###############################################################################

def test_duckduckgo_simpe():
    assert run('.ddg scp wiki') == lex.duckduckgo.result(index=1)

def test_duckduckgo_index():
    assert run('.ddg scp-wiki -i 5') == lex.duckduckgo.result(index=5)

def test_duckduckgo_index_error():
    assert run('.ddg scp-wiki -i 100') == lex.generics.index_error

def test_duckduckgo_showmore():
    run('.ddg scp-wiki')
    assert run('.sm 8') == lex.duckduckgo.result(index=8)

###############################################################################

def test_steam_lookup_simple():
    assert (
        run('http://store.steampowered.com/app/418150') ==
        lex.steam.result(name='The Madness of Little Emma'))

def test_steam_lookup_not_found():
    assert (
        run('http://store.steampowered.com/app/999999999999') ==
        lex.steam.not_found)

def test_steam_simple():
    assert run('.steam terraria') == lex.steam.result(name='Terraria')

def test_steam_no_price():
    assert str(run('.steam little emma demo'))

def test_steam_no_genre():
    assert str(run('.steam magic the gathering'))

def test_steam_superhot():
    # this weird bug happens in cycles, every 3rd or so result is correct
    # so we'll check the output 3 times to make sure
    url = 'http://store.steampowered.com/app/322500'
    for _ in range(3):
        assert url in str(run('.steam superhot'))

###############################################################################

def test_twitter_lookup_simple():
    assert (
        run('https://twitter.com/scpwiki/status/859196218618064896') ==
        lex.twitter_lookup(
            text='The 3000s are open!  Welcome to the show. - EC'))

def test_twitter_lookup_linebreaks():
    assert (
        run('https://twitter.com/TwitterForNews/status/311909802462822400') ==
        lex.twitter_lookup(text='L I N E  B R E A K S  #newattwitter'))

###############################################################################
#
###############################################################################

def test_kaktuskast_default():
    assert run('.kk') == [
        lex.kaktuskast.short, lex.kaktuskast.short, lex.kaktuskast.short]

def test_kaktuskast_index():
    assert run('.kk 25') == [
        lex.kaktuskast.short(title='The KaktusKast Ep. 25 - 3000Kast'),
        lex.kaktuskast.text]

def test_kaktuskast_index_error():
    assert run('.kk 4002') == lex.kaktuskast.index_error

def test_kaktuskast_podcast_not_found():
    assert run('.kk blahblah') == lex.kaktuskast.podcast_not_found

def test_kaktuskast_podcast():
    assert run('.kk crit 1') == [
        lex.kaktuskast.short(date='2017-07-25'), lex.kaktuskast.text]

def test_kaktuskast_foundation():
    assert run('.kk foundation 1')

def test_kaktuskast_ttrimmd():
    assert run('.kk trim 10') == [
        lex.kaktuskast.short(date='2017-07-22'), lex.kaktuskast.text]

def test_kaktuskast_title():
    assert run('.kk thing 5') == [lex.kaktuskast.short, lex.kaktuskast.text]

def test_kaktuskast_sm():
    run('.kk')
    assert run('.sm 1') == lex.kaktuskast.long


text:
import neo4j
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web

from handlers.base import BaseHandler, NodeNotFoundError

import logging
logger = logging.getLogger('trinity.' + __name__)

class NodeHandler(BaseHandler):
    @neo4j.transactional(BaseHandler.graph)
    def post(self):
        node_id = unicode(self.get_json_argument('id')).lower()
        params = self.get_json_argument('node', {})

        try:
            node = self.find_node(node_id)
        except NodeNotFoundError:
            node = self.graph.node(**params)
            self.index[node_id] = node
            logger.debug("Created node %s with 'ID' %s and data %s"
                    % (node, node_id, params))
        else:
            logger.debug("Found existing node %s with ID %s -- "
                    "not creating another" % (node, node_id))
        self.write({'id': node_id, 'node': params})


text:
require File.dirname(__FILE__) + '/../../spec_helper'

describe "Kernel#instance_of?" do
  it "needs to be reviewed for spec completeness" do
  end
end


text:
#![cfg_attr(doc_cfg, feature(doc_cfg))]
#![allow(
    clippy::needless_doctest_main,
    clippy::new_ret_no_self,
    clippy::wrong_self_convention
)]
use core::fmt::Display;

use std::error::Error as StdError;

use once_cell::sync::OnceCell;

#[allow(unreachable_pub)]
pub use into_diagnostic::*;
#[doc(hidden)]
#[allow(unreachable_pub)]
pub use Report as ErrReport;
/// Compatibility re-export of `Report` for interop with `anyhow`
#[allow(unreachable_pub)]
pub use Report as Error;
#[doc(hidden)]
#[allow(unreachable_pub)]
pub use ReportHandler as EyreContext;
/// Compatibility re-export of `WrapErr` for interop with `anyhow`
#[allow(unreachable_pub)]
pub use WrapErr as Context;

#[cfg(not(feature = "fancy-no-backtrace"))]
use crate::DebugReportHandler;
use crate::Diagnostic;
#[cfg(feature = "fancy-no-backtrace")]
use crate::MietteHandler;

use error::ErrorImpl;

use self::ptr::Own;

mod context;
mod error;
mod fmt;
mod into_diagnostic;
mod kind;
mod macros;
mod ptr;
mod wrapper;

/**
Core Diagnostic wrapper type.

## `eyre` Users

You can just replace `use`s of `eyre::Report` with `miette::Report`.
*/
pub struct Report {
    inner: Own<ErrorImpl<()>>,
}

unsafe impl Sync for Report {}
unsafe impl Send for Report {}

///
pub type ErrorHook =
    Box<dyn Fn(&(dyn Diagnostic + 'static)) -> Box<dyn ReportHandler> + Sync + Send + 'static>;

static HOOK: OnceCell<ErrorHook> = OnceCell::new();

/// Error indicating that [`set_hook()`] was unable to install the provided
/// [`ErrorHook`].
#[derive(Debug)]
pub struct InstallError;

impl core::fmt::Display for InstallError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str("cannot install provided ErrorHook, a hook has already been installed")
    }
}

impl StdError for InstallError {}
impl Diagnostic for InstallError {}

/**
Set the error hook.
*/
pub fn set_hook(hook: ErrorHook) -> Result<(), InstallError> {
    HOOK.set(hook).map_err(|_| InstallError)
}

#[cfg_attr(track_caller, track_caller)]
#[cfg_attr(not(track_caller), allow(unused_mut))]
fn capture_handler(error: &(dyn Diagnostic + 'static)) -> Box<dyn ReportHandler> {
    let hook = HOOK.get_or_init(|| Box::new(get_default_printer)).as_ref();

    #[cfg(track_caller)]
    {
        let mut handler = hook(error);
        handler.track_caller(std::panic::Location::caller());
        handler
    }
    #[cfg(not(track_caller))]
    {
        hook(error)
    }
}

fn get_default_printer(_err: &(dyn Diagnostic + 'static)) -> Box<dyn ReportHandler + 'static> {
    #[cfg(feature = "fancy-no-backtrace")]
    return Box::new(MietteHandler::new());
    #[cfg(not(feature = "fancy-no-backtrace"))]
    return Box::new(DebugReportHandler::new());
}

impl dyn ReportHandler {
    ///
    pub fn is<T: ReportHandler>(&self) -> bool {
        // Get `TypeId` of the type this function is instantiated with.
        let t = core::any::TypeId::of::<T>();

        // Get `TypeId` of the type in the trait object (`self`).
        let concrete = self.type_id();

        // Compare both `TypeId`s on equality.
        t == concrete
    }

    ///
    pub fn downcast_ref<T: ReportHandler>(&self) -> Option<&T> {
        if self.is::<T>() {
            unsafe { Some(&*(self as *const dyn ReportHandler as *const T)) }
        } else {
            None
        }
    }

    ///
    pub fn downcast_mut<T: ReportHandler>(&mut self) -> Option<&mut T> {
        if self.is::<T>() {
            unsafe { Some(&mut *(self as *mut dyn ReportHandler as *mut T)) }
        } else {
            None
        }
    }
}

/// Error Report Handler trait for customizing `miette::Report`
pub trait ReportHandler: core::any::Any + Send + Sync {
    /// Define the report format
    ///
    /// Used to override the report format of `miette::Report`
    ///
    /// # Example
    ///
    /// ```rust
    /// use indenter::indented;
    /// use miette::{Diagnostic, ReportHandler};
    ///
    /// pub struct Handler;
    ///
    /// impl ReportHandler for Handler {
    ///     fn debug(
    ///         &self,
    ///         error: &dyn Diagnostic,
    ///         f: &mut core::fmt::Formatter<'_>,
    ///     ) -> core::fmt::Result {
    ///         use core::fmt::Write as _;
    ///
    ///         if f.alternate() {
    ///             return core::fmt::Debug::fmt(error, f);
    ///         }
    ///
    ///         write!(f, "{}", error)?;
    ///
    ///         Ok(())
    ///     }
    /// }
    /// ```
    fn debug(
        &self,
        error: &(dyn Diagnostic),
        f: &mut core::fmt::Formatter<'_>,
    ) -> core::fmt::Result;

    /// Override for the `Display` format
    fn display(
        &self,
        error: &(dyn StdError + 'static),
        f: &mut core::fmt::Formatter<'_>,
    ) -> core::fmt::Result {
        write!(f, "{}", error)?;

        if f.alternate() {
            for cause in crate::chain::Chain::new(error).skip(1) {
                write!(f, ": {}", cause)?;
            }
        }

        Ok(())
    }

    /// Store the location of the caller who constructed this error report
    #[allow(unused_variables)]
    fn track_caller(&mut self, location: &'static std::panic::Location<'static>) {}
}

/// type alias for `Result<T, Report>`
///
/// This is a reasonable return type to use throughout your application but also
/// for `main()`. If you do, failures will be printed along with a backtrace if
/// one was captured.
///
/// `miette::Result` may be used with one *or* two type parameters.
///
/// ```rust
/// use miette::Result;
///
/// # const IGNORE: &str = stringify! {
/// fn demo1() -> Result<T> {...}
///            // ^ equivalent to std::result::Result<T, miette::Error>
///
/// fn demo2() -> Result<T, OtherError> {...}
///            // ^ equivalent to std::result::Result<T, OtherError>
/// # };
/// ```
///
/// # Example
///
/// ```
/// # pub trait Deserialize {}
/// #
/// # mod serde_json {
/// #     use super::Deserialize;
/// #     use std::io;
/// #
/// #     pub fn from_str<T: Deserialize>(json: &str) -> io::Result<T> {
/// #         unimplemented!()
/// #     }
/// # }
/// #
/// # #[derive(Debug)]
/// # struct ClusterMap;
/// #
/// # impl Deserialize for ClusterMap {}
/// #
/// use miette::{IntoDiagnostic, Result};
///
/// fn main() -> Result<()> {
///     # return Ok(());
///     let config = std::fs::read_to_string("cluster.json").into_diagnostic()?;
///     let map: ClusterMap = serde_json::from_str(&config).into_diagnostic()?;
///     println!("cluster info: {:#?}", map);
///     Ok(())
/// }
/// ```
///
/// ## `anyhow`/`eyre` Users
///
/// You can just replace `use`s of `anyhow::Result`/`eyre::Result` with
/// `miette::Result`.
pub type Result<T, E = Report> = core::result::Result<T, E>;

/// Provides the [`wrap_err()`](WrapErr::wrap_err) method for [`Result`].
///
/// This trait is sealed and cannot be implemented for types outside of
/// `miette`.
///
/// # Example
///
/// ```
/// use miette::{WrapErr, IntoDiagnostic, Result};
/// use std::{fs, path::PathBuf};
///
/// pub struct ImportantThing {
///     path: PathBuf,
/// }
///
/// impl ImportantThing {
///     # const IGNORE: &'static str = stringify! {
///     pub fn detach(&mut self) -> Result<()> {...}
///     # };
///     # fn detach(&mut self) -> Result<()> {
///     #     unimplemented!()
///     # }
/// }
///
/// pub fn do_it(mut it: ImportantThing) -> Result<Vec<u8>> {
///     it.detach().wrap_err("Failed to detach the important thing")?;
///
///     let path = &it.path;
///     let content = fs::read(path)
///         .into_diagnostic()
///         .wrap_err_with(|| format!(
///             "Failed to read instrs from {}",
///             path.display())
///         )?;
///
///     Ok(content)
/// }
/// ```
///
/// When printed, the outermost error would be printed first and the lower
/// level underlying causes would be enumerated below.
///
/// ```console
/// Error: Failed to read instrs from ./path/to/instrs.json
///
/// Caused by:
///     No such file or directory (os error 2)
/// ```
///
/// # Wrapping Types That Do Not Implement `Error`
///
/// For example `&str` and `Box<dyn Error>`.
///
/// Due to restrictions for coherence `Report` cannot implement `From` for types
/// that don't implement `Error`. Attempts to do so will give `"this type might
/// implement Error in the future"` as an error. As such, `wrap_err()`, which
/// uses `From` under the hood, cannot be used to wrap these types. Instead we
/// encourage you to use the combinators provided for `Result` in `std`/`core`.
///
/// For example, instead of this:
///
/// ```rust,compile_fail
/// use std::error::Error;
/// use miette::{WrapErr, Report};
///
/// fn wrap_example(err: Result<(), Box<dyn Error + Send + Sync + 'static>>)
///     -> Result<(), Report>
/// {
///     err.wrap_err("saw a downstream error")
/// }
/// ```
///
/// We encourage you to write this:
///
/// ```rust
/// use miette::{miette, Report, WrapErr};
/// use std::error::Error;
///
/// fn wrap_example(err: Result<(), Box<dyn Error + Send + Sync + 'static>>) -> Result<(), Report> {
///     err.map_err(|e| miette!(e))
///         .wrap_err("saw a downstream error")
/// }
/// ```
///
/// # Effect on Downcasting
///
/// After attaching a message of type `D` onto an error of type `E`, the
/// resulting `miette::Error` may be downcast to `D` **or** to `E`.
///
/// That is, in codebases that rely on downcasting, `miette`'s `wrap_err()`
/// supports both of the following use cases:
///
///   - **Attaching messages whose type is insignificant onto errors whose type
///     is used in downcasts.**
///
///     In other error libraries whose `wrap_err()` is not designed this way, it
///     can be risky to introduce messages to existing code because new message
///     might break existing working downcasts. In miette, any downcast that
///     worked before adding the message will continue to work after you add a
///     message, so you should freely wrap errors wherever it would be helpful.
///
///     ```
///     # use miette::bail;
///     # use thiserror::Error;
///     #
///     # #[derive(Error, Debug)]
///     # #[error("???")]
///     # struct SuspiciousError;
///     #
///     # fn helper() -> Result<()> {
///     #     bail!(SuspiciousError);
///     # }
///     #
///     use miette::{WrapErr, Result};
///
///     fn do_it() -> Result<()> {
///         helper().wrap_err("Failed to complete the work")?;
///         # const IGNORE: &str = stringify! {
///         ...
///         # };
///         # unreachable!()
///     }
///
///     fn main() {
///         let err = do_it().unwrap_err();
///         if let Some(e) = err.downcast_ref::<SuspiciousError>() {
///             // If helper() returned SuspiciousError, this downcast will
///             // correctly succeed even with the message in between.
///             # return;
///         }
///         # panic!("expected downcast to succeed");
///     }
///     ```
///
///   - **Attaching message whose type is used in downcasts onto errors whose
///     type is insignificant.**
///
///     Some codebases prefer to use machine-readable messages to categorize
///     lower level errors in a way that will be actionable to higher levels of
///     the application.
///
///     ```
///     # use miette::bail;
///     # use thiserror::Error;
///     #
///     # #[derive(Error, Debug)]
///     # #[error("???")]
///     # struct HelperFailed;
///     #
///     # fn helper() -> Result<()> {
///     #     bail!("no such file or directory");
///     # }
///     #
///     use miette::{WrapErr, Result};
///
///     fn do_it() -> Result<()> {
///         helper().wrap_err(HelperFailed)?;
///         # const IGNORE: &str = stringify! {
///         ...
///         # };
///         # unreachable!()
///     }
///
///     fn main() {
///         let err = do_it().unwrap_err();
///         if let Some(e) = err.downcast_ref::<HelperFailed>() {
///             // If helper failed, this downcast will succeed because
///             // HelperFailed is the message that has been attached to
///             // that error.
///             # return;
///         }
///         # panic!("expected downcast to succeed");
///     }
///     ```
pub trait WrapErr<T, E>: context::private::Sealed {
    /// Wrap the error value with a new adhoc error
    #[cfg_attr(track_caller, track_caller)]
    fn wrap_err<D>(self, msg: D) -> Result<T, Report>
    where
        D: Display + Send + Sync + 'static;

    /// Wrap the error value with a new adhoc error that is evaluated lazily
    /// only once an error does occur.
    #[cfg_attr(track_caller, track_caller)]
    fn wrap_err_with<D, F>(self, f: F) -> Result<T, Report>
    where
        D: Display + Send + Sync + 'static,
        F: FnOnce() -> D;

    /// Compatibility re-export of `wrap_err()` for interop with `anyhow`
    #[cfg_attr(track_caller, track_caller)]
    fn context<D>(self, msg: D) -> Result<T, Report>
    where
        D: Display + Send + Sync + 'static;

    /// Compatibility re-export of `wrap_err_with()` for interop with `anyhow`
    #[cfg_attr(track_caller, track_caller)]
    fn with_context<D, F>(self, f: F) -> Result<T, Report>
    where
        D: Display + Send + Sync + 'static,
        F: FnOnce() -> D;
}

// Private API. Referenced by macro-generated code.
#[doc(hidden)]
pub mod private {
    use super::Report;
    use core::fmt::{Debug, Display};

    pub use core::result::Result::Err;

    #[doc(hidden)]
    pub mod kind {
        pub use super::super::kind::{AdhocKind, TraitKind};

        pub use super::super::kind::BoxedKind;
    }

    #[cfg_attr(track_caller, track_caller)]
    pub fn new_adhoc<M>(message: M) -> Report
    where
        M: Display + Debug + Send + Sync + 'static,
    {
        Report::from_adhoc(message)
    }
}


text:
using namespace RISE;
using namespace RISE::Implementation;

#define ENABLE_MAX_RECURSION

GlobalPelPhotonTracer::GlobalPelPhotonTracer(
	const unsigned int maxR,
	const Scalar ext,
	const bool branch,
	const bool dononmeshlights,					///< Should we trace non-mesh lights?
	const bool useiorstack,						///< [in] Should we use an ior stack ?
	const Scalar powerscale,
	const unsigned int temporal_samples,
	const bool regenerate
	) :
  PhotonTracer<GlobalPelPhotonMap>( dononmeshlights, useiorstack, powerscale, temporal_samples, regenerate ),
  nMaxRecursions( maxR ),
  dExtinction( ext ),
  bBranch( branch )
{
}

GlobalPelPhotonTracer::~GlobalPelPhotonTracer( )
{
}

void GlobalPelPhotonTracer::TracePhoton(
	const Ray& ray,
	const RISEPel& power,
	GlobalPelPhotonMap& pPhotonMap,
	const bool bStorePhoton,
	const IORStack* const ior_stack								///< [in/out] Index of refraction stack
	) const
{
	static unsigned int		numRecursions = 0;

#ifdef ENABLE_MAX_RECURSION
	if( numRecursions > nMaxRecursions )
	{
#ifdef ENABLE_TERMINATION_MESSAGES
		GlobalLog()->PrintEasyInfo( "FORCED RECURSION TERMINATION" );
#endif
		return;
	}
#endif

	if( ColorMath::MaxValue(power) < dExtinction )
	{
#ifdef ENABLE_TERMINATION_MESSAGES
		GlobalLog()->PrintEasyInfo( "PHOTON BECAME EXTINCT :(" );
#endif
		return;
	}

	numRecursions++;

	// Cast the ray into the scene
	RayIntersection	ri( ray, nullRasterizerState );
	Vector3Ops::NormalizeMag(ri.geometric.ray.dir);
	pScene->GetObjects()->IntersectRay( ri, true, true, false );

	if( ri.geometric.bHit )
	{
		// If there is an intersection modifier, then get it to modify
		// the intersection information
		if( ri.pModifier ) {
			ri.pModifier->Modify( ri.geometric );
		}

		// Set the current object on the IOR stack
		if( ior_stack ) {
			ior_stack->SetCurrentObject( ri.pObject );
		}

		ISPF* pSPF = ri.pMaterial->GetSPF();

		if( pSPF )
		{
			// Get information from the material as to what to do
			ScatteredRayContainer		scattered;

			pSPF->Scatter( ri.geometric, random, scattered, ior_stack );

			bool bDiffuseComponentAvailable = false;
			for( unsigned int i=0; i<scattered.Count(); i++ ) {
				ScatteredRay& scat = scattered[i];
				if( scat.type==ScatteredRay::eRayDiffuse ) {
					bDiffuseComponentAvailable = true;
					break;
				}
			}

			if( bDiffuseComponentAvailable && bStorePhoton ) {
				pPhotonMap.Store( power, ri.geometric.ptIntersection, ri.geometric.vNormal, -ray.dir );
			}

			if( bBranch ) {
				for( unsigned int i=0; i<scattered.Count(); i++ ) {
					ScatteredRay& scat = scattered[i];
					scat.ray.Advance( 1e-8 );
					TracePhoton( scat.ray, power*scat.kray, pPhotonMap, scat.type==ScatteredRay::eRayDiffuse, scat.ior_stack?scat.ior_stack:ior_stack );
				}
			} else {
				ScatteredRay* pScat = scattered.RandomlySelect( random.CanonicalRandom(), false );
				if( pScat ) {
					pScat->ray.Advance( 1e-8 );
					TracePhoton( pScat->ray, power*pScat->kray, pPhotonMap, pScat->type==ScatteredRay::eRayDiffuse, pScat->ior_stack?pScat->ior_stack:ior_stack );
				}
			}
		}
	}

	// If there was no hit then the photon just got ejected into space!

	numRecursions--;
}