text:
using System;
using System.Collections.Generic;
using System.Reflection;

using OpenSim.Framework;

using OpenSim.Services.Interfaces;

using OpenMetaverse;
using log4net;

namespace OpenSim.Region.CoreModules.Framework.Library
{
    public class LocalInventoryService : IInventoryService
    {
        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        private InventoryFolderImpl m_Library;

        public LocalInventoryService(InventoryFolderImpl lib)
        {
            m_Library = lib;
        }

        /// <summary>
        /// Retrieve the root inventory folder for the given user.
        /// </summary>
        /// <param name="userID"></param>
        /// <returns>null if no root folder was found</returns>
        public InventoryFolderBase GetRootFolder(UUID userID) { return m_Library; }

        /// <summary>
        /// Gets everything (folders and items) inside a folder
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="folderID"></param>
        /// <returns></returns>
        public InventoryCollection GetFolderContent(UUID userID, UUID folderID)
        {
            InventoryFolderImpl folder = null;
            InventoryCollection inv = new InventoryCollection();
            inv.OwnerID = m_Library.Owner;

            if (folderID != m_Library.ID)
            {
                folder = m_Library.FindFolder(folderID);
                if (folder == null)
                {
                    inv.Folders = new List<InventoryFolderBase>();
                    inv.Items = new List<InventoryItemBase>();
                    return inv;
                }
            }
            else
                folder = m_Library;

            inv.Folders = folder.RequestListOfFolders();
            inv.Items = folder.RequestListOfItems();

            m_log.DebugFormat("[LIBRARY MODULE]: Got content for folder {0}", folder.Name);
            return inv;
        }

        public virtual InventoryCollection[] GetMultipleFoldersContent(UUID principalID, UUID[] folderIDs)
        {
            InventoryCollection[] invColl = new InventoryCollection[folderIDs.Length];
            int i = 0;
            foreach (UUID fid in folderIDs)
            {
                invColl[i++] = GetFolderContent(principalID, fid);
            }

            return invColl;
        }

        public virtual InventoryItemBase[] GetMultipleItems(UUID principalID, UUID[] itemIDs)
        {
            InventoryItemBase[] itemColl = new InventoryItemBase[itemIDs.Length];
            int i = 0;
            foreach (UUID fid in itemIDs)
                itemColl[i++] = GetItem(principalID, fid);

            return itemColl;
        }

        /// <summary>
        /// Add a new folder to the user's inventory
        /// </summary>
        /// <param name="folder"></param>
        /// <returns>true if the folder was successfully added</returns>
        public bool AddFolder(InventoryFolderBase folder)
        {
            //m_log.DebugFormat("[LIBRARY MODULE]: Adding folder {0} ({1}) to {2}", folder.Name, folder.ID, folder.ParentID);
            InventoryFolderImpl parent = m_Library;
            if (m_Library.ID != folder.ParentID)
                parent = m_Library.FindFolder(folder.ParentID);

            if (parent == null)
            {
                m_log.DebugFormat("[LIBRARY MODULE]: could not add folder {0} because parent folder {1} not found", folder.Name, folder.ParentID);
                return false;
            }

            parent.CreateChildFolder(folder.ID, folder.Name, (ushort)folder.Type);

            return true;
        }

        /// <summary>
        /// Add a new item to the user's inventory
        /// </summary>
        /// <param name="item"></param>
        /// <returns>true if the item was successfully added</returns>
        public bool AddItem(InventoryItemBase item)
        {
            //m_log.DebugFormat("[LIBRARY MODULE]: Adding item {0} to {1}", item.Name, item.Folder);
            InventoryFolderImpl folder = m_Library;
            if (m_Library.ID != item.Folder)
                folder = m_Library.FindFolder(item.Folder);

            if (folder == null)
            {
                m_log.DebugFormat("[LIBRARY MODULE]: could not add item {0} because folder {1} not found", item.Name, item.Folder);
                return false;
            }

            folder.Items.Add(item.ID, item);
            return true;
        }

        public bool CreateUserInventory(UUID user) { return false; }

        /// <summary>
        /// Gets the skeleton of the inventory -- folders only
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public List<InventoryFolderBase> GetInventorySkeleton(UUID userId) { return null; }

        /// <summary>
        /// Gets the user folder for the given folder-type
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public InventoryFolderBase GetFolderForType(UUID userID, FolderType type) { return null; }

        /// <summary>
        /// Gets the items inside a folder
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="folderID"></param>
        /// <returns></returns>
        public List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID) { return null; }

        /// <summary>
        /// Update a folder in the user's inventory
        /// </summary>
        /// <param name="folder"></param>
        /// <returns>true if the folder was successfully updated</returns>
        public bool UpdateFolder(InventoryFolderBase folder) { return false; }

        /// <summary>
        /// Move an inventory folder to a new location
        /// </summary>
        /// <param name="folder">A folder containing the details of the new location</param>
        /// <returns>true if the folder was successfully moved</returns>
        public bool MoveFolder(InventoryFolderBase folder) { return false; }

        /// <summary>
        /// Delete an item from the user's inventory
        /// </summary>
        /// <param name="item"></param>
        /// <returns>true if the item was successfully deleted</returns>
        //bool DeleteItem(InventoryItemBase item);
        public bool DeleteFolders(UUID userID, List<UUID> folderIDs) { return false; }

        /// <summary>
        /// Purge an inventory folder of all its items and subfolders.
        /// </summary>
        /// <param name="folder"></param>
        /// <returns>true if the folder was successfully purged</returns>
        public bool PurgeFolder(InventoryFolderBase folder) { return false; }

        /// <summary>
        /// Update an item in the user's inventory
        /// </summary>
        /// <param name="item"></param>
        /// <returns>true if the item was successfully updated</returns>
        public bool UpdateItem(InventoryItemBase item) { return false; }

        public bool MoveItems(UUID ownerID, List<InventoryItemBase> items) { return false; }

        /// <summary>
        /// Delete an item from the user's inventory
        /// </summary>
        /// <param name="item"></param>
        /// <returns>true if the item was successfully deleted</returns>
        //bool DeleteItem(InventoryItemBase item);
        public bool DeleteItems(UUID userID, List<UUID> itemIDs) { return false; }

        /// <summary>
        /// Get an item, given by its UUID
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public InventoryItemBase GetItem(UUID principalID, UUID itemID) { return null; }

        /// <summary>
        /// Get a folder, given by its UUID
        /// </summary>
        /// <param name="folder"></param>
        /// <returns></returns>
        public InventoryFolderBase GetFolder(UUID principalID, UUID folderID) { return null; }

        /// <summary>
        /// Does the given user have an inventory structure?
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public bool HasInventoryForUser(UUID userID) { return false; }

        /// <summary>
        /// Get the active gestures of the agent.
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public List<InventoryItemBase> GetActiveGestures(UUID userId) { return null; }

        /// <summary>
        /// Get the union of permissions of all inventory items
        /// that hold the given assetID.
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="assetID"></param>
        /// <returns>The permissions or 0 if no such asset is found in
        /// the user's inventory</returns>
        public int GetAssetPermissions(UUID userID, UUID assetID) { return 0; }
    }
}


text:
package org.elasticsearch.index.engine;

import org.elasticsearch.common.util.concurrent.ConcurrentCollections;
import org.elasticsearch.index.seqno.LocalCheckpointTracker;
import org.elasticsearch.index.seqno.SequenceNumbers;

import java.io.IOException;
import java.util.Map;
import java.util.function.BiFunction;

/**
 * An alternative of {@link InternalEngine} that allows tweaking internals to reduce noise in engine tests.
 */
class InternalTestEngine extends InternalEngine {
    private final Map<String, Long> idToMaxSeqNo = ConcurrentCollections.newConcurrentMap();

    InternalTestEngine(EngineConfig engineConfig) {
        super(engineConfig);
    }

    InternalTestEngine(EngineConfig engineConfig, int maxDocs,
                       BiFunction<Long, Long, LocalCheckpointTracker> localCheckpointTrackerSupplier) {
        super(engineConfig, maxDocs, localCheckpointTrackerSupplier);
    }

    @Override
    public IndexResult index(Index index) throws IOException {
        if (index.seqNo() != SequenceNumbers.UNASSIGNED_SEQ_NO) {
            idToMaxSeqNo.compute(index.id(), (id, existing) -> {
                if (existing == null) {
                    return index.seqNo();
                } else {
                    long maxSeqNo = Math.max(index.seqNo(), existing);
                    advanceMaxSeqNoOfUpdatesOrDeletes(maxSeqNo);
                    return maxSeqNo;
                }
            });
        }
        return super.index(index);
    }

    @Override
    public DeleteResult delete(Delete delete) throws IOException {
        if (delete.seqNo() != SequenceNumbers.UNASSIGNED_SEQ_NO) {
            final long maxSeqNo = idToMaxSeqNo.compute(delete.id(), (id, existing) -> {
                if (existing == null) {
                    return delete.seqNo();
                } else {
                    return Math.max(delete.seqNo(), existing);
                }
            });
            advanceMaxSeqNoOfUpdatesOrDeletes(maxSeqNo);
        }
        return super.delete(delete);
    }
}

redpajama_set_name: RedPajamaGithub


text:
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2020 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0

/**
 * @license
 * @fileoverview Helper block definitions. These are created based on the
 *     component database, and are meant to be connected to component
 *     method/setter inputs to make coding faster for users.
 */

'use strict';

goog.provide('Blockly.Blocks.helpers');

goog.require('Blockly.Blocks.Utilities');

Blockly.COLOUR_HELPERS = "#BF4343";

Blockly.Blocks['helpers_dropdown'] = {
  init: function() {
    /**
     * The key to the OptionList associated with this block.
     * @private
     */
    this.key_ = "";
    this.setColour(Blockly.COLOUR_HELPERS);
    // Everything else gets handled by domToMutaiton.
  },

  mutationToDom: function() {
    var mutation = document.createElement('mutation');
    mutation.setAttribute('key', this.key_);
    return mutation;
  },

  domToMutation: function(xml) {
    this.key_ = xml.getAttribute('key');

    var db = this.getTopWorkspace().getComponentDatabase();
    var optionList = db.getOptionList(this.key_);
    var tag = db.getInternationalizedOptionListTag(optionList.tag);
    var dropdown = new Blockly.FieldInvalidDropdown(
        this.getValidOptions(), this.getInvalidOptions());

    // Setting the output check to be the OptionList type only allows this block
    // to connect to inputs which expect its specific type of enum. Currently
    // this is only used for Blockly connection checks, as no output types are
    // encoded in Yail.
    this.setOutput(true, this.getOutputType());
    this.appendDummyInput()
        .appendField(tag)
        .appendField(dropdown, 'OPTION');

    var value = xml.getAttribute('value') || optionList.defaultOpt;
    this.setFieldValue(value, 'OPTION');
  },

  getOutputType: function() {
    var check = [];
    var blocklyType = Blockly.Blocks.Utilities.YailTypeToBlocklyType(
        'enum', Blockly.Blocks.Utilities.OUTPUT);
    if (blocklyType) {
      if (Array.isArray(blocklyType)) {
        // Clone array.
        check = blocklyType.slice();
      } else {
        check.push(blocklyType);
      }
    }

    var helperType = Blockly.Blocks.Utilities.helperKeyToBlocklyType(
      { type: 'OPTION_LIST', key: this.key_ }, this);
    if (helperType && helperType != blocklyType) {
      check.push(helperType);
    }

    return !check.length ? null : check;
  },

  /**
   * Returns a list of tuples defining the valid dropdown values. The first
   * element in the tuple is the human readable name. The second element is the
   * language neutral value.
   */
  getValidOptions: function() {
    var db = this.getTopWorkspace().getComponentDatabase();
    var optionList = db.getOptionList(this.key_);
    var options = [];
    for (var i = 0, option; option = optionList.options[i]; i++) {
      var key = optionList.tag + option.name;
      var i18nName = db.getInternationalizedOptionName(key, option.name);
      if (!option.deprecated) {
        options.push([i18nName, option.name]);
      }
    }
    return options;
  },

  /**
   * Returns a list of tuples defining the /invalid/ dropdown values. The first
   * element in the tuple is the human readable name. The second element is the
   * language neutral value.
   */
  getInvalidOptions: function() {
    var db = this.getTopWorkspace().getComponentDatabase();
    var optionList = db.getOptionList(this.key_);
    var options = [];
    for (var i = 0, option; option = optionList.options[i]; i++) {
      var key = optionList.tag + option.name;
      var i18nName = db.getInternationalizedOptionName(key, option.name);
      if (option.deprecated) {
        options.push([i18nName, option.name]);
      }
    }
    return options;
  },

  typeblock: function() {
    var db = Blockly.mainWorkspace.getComponentDatabase();
    var tb = [];

    db.forEachOptionList(function(optionList) {
      for (var i = 0, option; option = optionList.options[i]; i++) {
        var tag = db.getInternationalizedOptionListTag(optionList.tag);
        var key = optionList.tag + option.name;
        var i18nName = db.getInternationalizedOptionName(key, option.name);
        tb.push({
          // TODO: This doesn't handle rtl langs, anyway to fix that?
          translatedName: tag + i18nName,
          mutatorAttributes: {
            key: optionList.tag,
            value: option.name
          }
        });
      }
    });

    return tb;
  }
}

Blockly.Blocks['helpers_screen_names'] = {
  init: function() {
    var utils = Blockly.Blocks.Utilities;
    var dropdown = new Blockly.FieldInvalidDropdown(
        this.generateOptions.bind(this));

    this.setColour(Blockly.COLOUR_HELPERS);

    this.setOutput(true, utils.YailTypeToBlocklyType('text', utils.OUTPUT));
    this.appendDummyInput()
        .appendField(dropdown, 'SCREEN');
  },

  onchange: function(e) {
    if (e.type == AI.Events.SCREEN_SWITCH) {
      this.setFieldValue(this.getFieldValue('SCREEN'), 'SCREEN');
    }
  },

  domToMutation: function(xml) {
    var value = xml.getAttribute('value');
    this.setFieldValue(value, 'SCREEN');
  },

  getScreens: function() {
    return this.workspace.getScreenList();
  },

  generateOptions: function() {
    if (!this.workspace) {
      return [['', '']]
    }
    var screens = this.getScreens();
    if (!screens.length) {
      return [['', '']]
    }
    return screens.map(function (elem) {
      return [elem, elem];
    });
  },

  typeblock: function() {
    var tb = [];

    var screens = Blockly.mainWorkspace.getScreenList();
    for (var i = 0, screen; (screen = screens[i]); i++) {
      tb.push({
        translatedName: Blockly.Msg.LANG_SCREENS_TITLE + screen,
        mutatorAttributes: {
          value: screen
        }
      })
    }

    return tb;
  }
}

Blockly.Blocks['helpers_assets'] = {
  init: function() {
    var utils = Blockly.Blocks.Utilities;

    this.setColour(Blockly.COLOUR_HELPERS);

    this.setOutput(true, utils.YailTypeToBlocklyType('text', utils.OUTPUT));
    this.appendDummyInput('INPUT')

    this.addField();
  },

  onchange: function(e) {
    if (e.type != AI.Events.SCREEN_SWITCH &&
        !(e.type == Blockly.Events.MOVE)) {
      return;
    }

    if (this.addField()) {
      var value = this.getFieldValue('ASSET');
      var options = this.generateOptions();
      if (this.isInFlyout && options.length) {
        value = options[0][1];
      }
      this.setFieldValue(value, 'ASSET');
    }
  },

  domToMutation: function(xml) {
    var field = this.getField('ASSET');
    if (!field) {
      return;
    }
    var value = xml.getAttribute('value');
    field.setValue(value);
  },

  addField: function() {
    if (!this.workspace) {  // Disposed.
      return;
    }
    var input = this.getInput('INPUT');
    var assets = this.workspace.getAssetList();

    if (assets.length) { // We should have an asset dropdown.
      if (!this.getField('ASSET')) {
        var dropdown = new Blockly.FieldInvalidDropdown(
            this.generateOptions.bind(this));
        input.appendField(dropdown, 'ASSET');
      }
      if (this.getField('TEXT')) {
        input.removeField('TEXT');
      }
    } else {
      if (!this.getField('TEXT')) {
        var label = new Blockly.FieldLabel(Blockly.Msg.LANG_NO_ASSETS);
        input.appendField(label, 'TEXT');
      }
      if (this.getField('ASSET')) {
        input.removeField('ASSET');
      }
    }

    return assets.length;
  },

  generateOptions: function() {
    if (!this.workspace) {
      return [['', '']];
    }

    // Must include the '' so .some returns true if no restrictions.
    var restrictedFormats = [''];
    var types = this.outputConnection.targetConnection &&
        this.outputConnection.targetConnection.check_;
    if (types) {
      for (var i = 0, type; type = types[i]; i++) {
        if (Array.isArray(type)) {
          // Not actually a type check. An array in the type check array is used
          // to restrict formats.
          restrictedFormats = type;
        }
      }
    }

    var assets = this.workspace.getAssetList();
    if (assets.length) {
      var values = assets.map(function (elem) {
        var assetValid = restrictedFormats.some(function(fileType) {
          return elem.includes(fileType);
        })
        if (assetValid) {
          return [elem, elem];
        }
        return undefined;  // Not necessary just more explicit.
      });
      values = values.filter(function(elem) {
        return elem !== undefined;
      })
      if (values.length) {
        return values;
      }
    }

    return [['', '']]
  },

  typeblock: function() {
    tb = [];
    var assets = Blockly.mainWorkspace.getAssetList();
    for (var i = 0, asset; (asset = assets[i]); i++) {
      tb.push({
        translatedName: asset,
        mutatorAttributes: {
          value: asset
        }
      })
    }
    return tb;
  }
}


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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.binaryauthorization.v1.model;

/**
 * An admission rule specifies either that all container images used in a pod creation request must
 * be attested to by one or more attestors, that all pod creations will be allowed, or that all pod
 * creations will be denied.
 *
 * Images matching an admission whitelist pattern are exempted from admission rules and will never
 * block a pod creation.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Binary Authorization API. For a detailed explanation
 * see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class AdmissionRule extends com.google.api.client.json.GenericJson {

  /**
   * Required. The action when a pod creation is denied by the admission rule.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String enforcementMode;

  /**
   * Required. How this admission rule will be evaluated.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String evaluationMode;

  /**
   * Optional. The resource names of the attestors that must attest to a container image, in the
   * format `projects/attestors`. Each attestor must exist before a policy can reference it.  To add
   * an attestor to a policy the principal issuing the policy change request must be able to read
   * the attestor resource.
   *
   * Note: this field must be non-empty when the evaluation_mode field specifies
   * REQUIRE_ATTESTATION, otherwise it must be empty.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<java.lang.String> requireAttestationsBy;

  /**
   * Required. The action when a pod creation is denied by the admission rule.
   * @return value or {@code null} for none
   */
  public java.lang.String getEnforcementMode() {
    return enforcementMode;
  }

  /**
   * Required. The action when a pod creation is denied by the admission rule.
   * @param enforcementMode enforcementMode or {@code null} for none
   */
  public AdmissionRule setEnforcementMode(java.lang.String enforcementMode) {
    this.enforcementMode = enforcementMode;
    return this;
  }

  /**
   * Required. How this admission rule will be evaluated.
   * @return value or {@code null} for none
   */
  public java.lang.String getEvaluationMode() {
    return evaluationMode;
  }

  /**
   * Required. How this admission rule will be evaluated.
   * @param evaluationMode evaluationMode or {@code null} for none
   */
  public AdmissionRule setEvaluationMode(java.lang.String evaluationMode) {
    this.evaluationMode = evaluationMode;
    return this;
  }

  /**
   * Optional. The resource names of the attestors that must attest to a container image, in the
   * format `projects/attestors`. Each attestor must exist before a policy can reference it.  To add
   * an attestor to a policy the principal issuing the policy change request must be able to read
   * the attestor resource.
   *
   * Note: this field must be non-empty when the evaluation_mode field specifies
   * REQUIRE_ATTESTATION, otherwise it must be empty.
   * @return value or {@code null} for none
   */
  public java.util.List<java.lang.String> getRequireAttestationsBy() {
    return requireAttestationsBy;
  }

  /**
   * Optional. The resource names of the attestors that must attest to a container image, in the
   * format `projects/attestors`. Each attestor must exist before a policy can reference it.  To add
   * an attestor to a policy the principal issuing the policy change request must be able to read
   * the attestor resource.
   *
   * Note: this field must be non-empty when the evaluation_mode field specifies
   * REQUIRE_ATTESTATION, otherwise it must be empty.
   * @param requireAttestationsBy requireAttestationsBy or {@code null} for none
   */
  public AdmissionRule setRequireAttestationsBy(java.util.List<java.lang.String> requireAttestationsBy) {
    this.requireAttestationsBy = requireAttestationsBy;
    return this;
  }

  @Override
  public AdmissionRule set(String fieldName, Object value) {
    return (AdmissionRule) super.set(fieldName, value);
  }

  @Override
  public AdmissionRule clone() {
    return (AdmissionRule) super.clone();
  }

}


text:
#if (defined(GOOGLE_CUDA) && GOOGLE_CUDA) || \
    (defined(TENSORFLOW_USE_ROCM) && TENSORFLOW_USE_ROCM)

#define EIGEN_USE_GPU

#include "tensorflow/core/kernels/xent_op.h"

#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/platform/types.h"

namespace tensorflow {

typedef Eigen::GpuDevice GPUDevice;

// Partial specialization for a GPUDevice, that uses the Eigen implementation
// from XentEigenImpl.
namespace functor {
template <typename T>
struct XentFunctor<GPUDevice, T> {
  void operator()(const GPUDevice &d,
                  const Eigen::DSizes<Eigen::DenseIndex, 2> &shape,
                  const Eigen::array<Eigen::DenseIndex, 2> &logits_bcast,
                  const Eigen::array<Eigen::DenseIndex, 2> &labels_bcast,
                  typename TTypes<T>::ConstMatrix logits,
                  typename TTypes<T>::ConstMatrix labels,
                  typename TTypes<T>::Matrix scratch,
                  typename TTypes<T>::Vec loss,
                  typename TTypes<T>::Matrix backprop) {
    XentEigenImpl<GPUDevice, T>::Compute(d, shape, logits_bcast, labels_bcast,
                                         logits, labels, scratch, loss,
                                         backprop);
  }
};
}  // end namespace functor

// Instantiate the GPU implementation for half, float and double.
template struct functor::XentFunctor<GPUDevice, Eigen::half>;
template struct functor::XentFunctor<GPUDevice, float>;
template struct functor::XentFunctor<GPUDevice, double>;

}  // end namespace tensorflow

#endif  // GOOGLE_CUDA || TENSORFLOW_USE_ROCM


text:
This gallery plugin allows you to create a Flickr photostream-like gallery for your application
while still using Flickr to host your image files. The plugin uses the Flickr API to gather a list
of recently added public photos for a particular user and displays them in a justified gallery
using ["Justified Gallery"](http://miromannino.com/projects/justified-gallery/) from Miro Mannino.

## Installation

```bash
bower install kladd/flickr-justified-gallery
```

## Usage

Follow the directions on Miro Mannino's project page
[here](http://miromannino.com/projects/justified-gallery/).

Then replace

```javascript
$("#mygallery").justifiedGallery();
```

with

```javascript
$("#mygallery").flickrJustifiedGallery({
	flickrApiKey: "YOUR_API_KEY",
	flickrUserID: "YOUR_FLICKR_USER_ID",
	flickrPerPage: 12
});
```

Additional settings can be set through the `justifiedGallerySettings` parameter.

Here's an example:

```javascript
$("#mygallery").flickrJustifiedGallery({
	flickrApiKey: "YOUR_API_KEY",
	flickrUserID: "YOUR_FLICKR_USER_ID",
	flickrPerPage: 12,

	justifiedGallerySettings: {
		rowHeight: 212,
		maxRowHeight: 312,
		target: "_blank",
		lastRow: "hide"
	}
});
```

## License

Flickr Justified Gallery is open-sourced software licensed under the
[MIT license](https://raw.github.com/kladd/flickr-justified-gallery/master/LICENSE)


text:
namespace base {
class SingleThreadTaskRunner;
}

namespace blink {

class CachedMetadata;
class ScriptResource;
class ScriptCacheConsumerClient;

// A V8 code cache consumer for a script's code cache, which consumes the code
// cache off-thread and notifies a given ScriptCacheConsumerClient once it has
// completed.
//
// ScriptCacheConsumer works on unchecked CachedMetadata speculatively, before
// the source is available. If SingleCachedMetadataHandler::Check() fails later,
// the CachedMetadata on the CachedMetadataHandler will be cleared, and the
// result of this ScriptCacheConsumer will be dropped on TakeV8ConsumeTask() due
// to a CachedMetadata mismatch.
//
// The state of the ScriptCacheConsumer state is associated with a single
// CachedMetadata, but it is independent of the state of the corresponding
// ScriptResource or its CachedMetadataHandler. Thus, it's fine that one
// ClassicPendingScript for the ScriptResource can get a non-null
// ConsumeCodeCacheTask from TakeV8ConsumeTask(), while others with the same
// ScriptResource don't use ScriptCacheConsumer. It's fine even if a
// ClassicPendingScript is notified finished (with or without
// ScriptCacheConsumer), and executes a script for a ScriptResource while
// another ClassicPendingScript for the same ScriptResource with the same
// CachedMetadata is still waiting for ScriptCacheConsumer completion.
class CORE_EXPORT ScriptCacheConsumer final
    : public GarbageCollected<ScriptCacheConsumer> {
 public:
  // Construct a cache consumer for the given CachedMetadata, corresponding to
  // the given URL and resource ID.
  //
  // The CachedMetadata should contain a V8 code cache. An off-thread cache
  // consumption task is posted immediately when this object is constructed.
  ScriptCacheConsumer(scoped_refptr<CachedMetadata> cached_metadata,
                      const String& script_url_string,
                      uint64_t script_resource_identifier);

  // Notify this cache consumer that the corresponding resource has completed.
  //
  // If the resource calls this, it expects this consumer to call
  // ScriptCacheConsumerClient::NotifyCacheConsumeFinished once the consumption
  // task completes. There are two possibilities:
  //
  //   1) If the task has already completed, it calls NotifyCacheConsumeFinished
  //      immediately and synchronously.
  //   2) Otherwise, it updates the state and returns, Then, when the off-thread
  //      cache consume task completes, it will post a task that calls
  //      NotifyCacheConsumeFinished using the given task runner.
  void NotifyClientWaiting(
      ScriptCacheConsumerClient* client,
      scoped_refptr<base::SingleThreadTaskRunner> task_runner);

  // Take ownership of the consume task, clearing it from the consumer so that
  // no one can attempt to use it twice.
  //
  // Pass in the CachedMetadata which should match the one the consume task was
  // created with -- if there is a mismatch (e.g. because the metadata was later
  // cleared), drop the consume task and return nullptr.
  //
  // Also, may return nullptr if no consume task was ever created.
  v8::ScriptCompiler::ConsumeCodeCacheTask* TakeV8ConsumeTask(
      CachedMetadata* cached_metadata) {
    CHECK_EQ(state_, kFinishedAndReady);
    if (cached_metadata != cached_metadata_) {
      consume_task_.reset();
      return nullptr;
    }
    return consume_task_.release();
  }

  void Trace(Visitor* visitor) const;

 private:
  // Valid state transitions:
  //
  //                           kRunning
  //                              |
  //        RunTaskOffThread()    |     NotifyClientWaiting()
  //                     .--------'---------.
  //                     v                  v
  //             kConsumeFinished      kClientReady
  //                     |                  |
  //                     '--------.---------'
  //     NotifyClientWaiting()    |     RunTaskOffThread()
  //                              v
  //                        kBothFinished
  //
  // These states are represented as a bit field.
  enum State {
    kRunning = 0,
    kConsumeFinished = 0b10,
    kClientReady = 0b01,
    kFinishedAndReady = 0b11
  };
  static_assert(
      (kConsumeFinished & kClientReady) == 0,
      "kConsumeFinished and kClientReady have to be independent bits");
  static_assert(
      (kConsumeFinished | kClientReady) == kFinishedAndReady,
      "kFinishedAndReady has to mean kConsumeFinished and kClientReady");

  // Advance the state with either the kConsumeFinished or the kClientReady
  // bit. Returns the new state, which is either the given state or
  // kFinishedAndReady.
  State AdvanceState(State new_state_bit);

  // Helper methods for running the consume task off-thread and posting back
  // from it.
  void RunTaskOffThread();
  void CallFinishCallback(const char* trace_name);

  // The cached metadata storing the code cache. This is held by the consumer
  // to keep the cached data alive even if it is cleared on the script resource.
  scoped_refptr<CachedMetadata> cached_metadata_;

  // The V8 task which consumes the code cache in the cached metadata. This is
  // expected to be run on a worker thread, and then to be passed back into V8
  // to be used.
  std::unique_ptr<v8::ScriptCompiler::ConsumeCodeCacheTask> consume_task_;

  // The client which should be notified when the consume task completes.
  WeakMember<ScriptCacheConsumerClient> finish_callback_client_;

  // The task runner on which the finish callback should be run.
  scoped_refptr<base::SingleThreadTaskRunner> finish_callback_task_runner_;

  // Keep the script URL string for event tracing. This is owned by the main
  // thread, and should be copied when used off-thread.
  const String script_url_string_;

  // Keep the script resource dentifier for event tracing.
  const uint64_t script_resource_identifier_;

  // The state of this ScriptCacheConsumer, advanced atomically when this
  // consume task completes, and when the resource completes.
  std::atomic<State> state_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_SCRIPT_CACHE_CONSUMER_H_


text:
"""
XML test data builders for [Content_Types].xml elements
"""

from __future__ import absolute_import, print_function, unicode_literals

from pptx.opc.oxml import nsmap

from ...unitdata import BaseBuilder

class CT_DefaultBuilder(BaseBuilder):
    __tag__ = 'Default'
    __nspfxs__ = ('ct',)
    __attrs__ = ('Extension', 'ContentType')

class CT_OverrideBuilder(BaseBuilder):
    __tag__ = 'Override'
    __nspfxs__ = ('ct',)
    __attrs__ = ('PartName', 'ContentType')

class CT_TypesBuilder(BaseBuilder):
    __tag__ = 'Types'
    __nspfxs__ = ('ct',)
    __attrs__ = ()

    def with_nsdecls(self, *nspfxs):
        self._nsdecls = ' xmlns="%s"' % nsmap['ct']
        return self

def a_Default():
    return CT_DefaultBuilder()

def a_Types():
    return CT_TypesBuilder()

def an_Override():
    return CT_OverrideBuilder()


text:
/* */
"format cjs";
describe('L.mapbox.infoControl', function() {
    'use strict';
    it('constructor', function() {
        var info = L.mapbox.infoControl();
        expect(info).to.be.ok();
    });

    describe('#addInfo', function() {
        it('returns the info object', function() {
            var info = L.mapbox.infoControl();
            expect(info.addInfo('foo')).to.eql(info);
            expect(info instanceof L.mapbox.InfoControl).to.eql(true);
        });

        it('adds a map info element to its container', function() {
            var elem = document.createElement('div');
            var map = L.mapbox.map(elem);
            var info = L.mapbox.infoControl();
            info.addTo(map);
            expect(info.addInfo('foo')).to.eql(info);
            expect(info._content.innerHTML).to.eql('foo');
        });

        it('handles multiple infos', function() {
            var elem = document.createElement('div');
            var map = L.mapbox.map(elem);
            var info = L.mapbox.infoControl();
            expect(info.addTo(map)).to.eql(info);
            expect(info.addInfo('foo')).to.eql(info);
            expect(info.addInfo('bar')).to.eql(info);
            expect(info._content.innerHTML).to.eql('foo | bar');
        });
    });

    describe('#removeInfo', function() {
        it('returns the info object', function() {
            var info = L.mapbox.infoControl();
            expect(info.addInfo('foo')).to.eql(info);
            expect(info.removeInfo('foo')).to.eql(info);
            expect(info.removeInfo()).to.eql(info);
        });

        it('adds and removes dom elements', function() {
            var elem = document.createElement('div');
            var map = L.mapbox.map(elem);
            var info = L.mapbox.infoControl();
            info.addTo(map);
            expect(info.addInfo('foo')).to.eql(info);
            expect(info.addInfo('bar')).to.eql(info);
            expect(info._content.innerHTML).to.eql('foo | bar');
            expect(info.removeInfo('bar')).to.eql(info);
            expect(info._content.innerHTML).to.eql('foo');
        });
    });

    it('sanitizes its content', function() {
        var map = L.map(document.createElement('div'));
        var info = L.mapbox.infoControl().addTo(map);

        info.addInfo('<script></script>');

        expect(info._content.innerHTML).to.eql('');
    });

    it('supports a custom sanitizer', function() {
        var map = L.map(document.createElement('div'));
        var info = L.mapbox.infoControl({
            sanitizer: function(_) { return _; }
        }).addTo(map);

        info.addInfo('<script></script>');

        expect(info._content.innerHTML).to.eql('<script></script>');
    });

    it('receives attribution from a layer', function(done) {
        var server = sinon.fakeServer.create();
        var element = document.createElement('div');
        var map = L.mapbox.map(element, 'mapbox.map-0l53fhk2', {
            infoControl: true
        });

        map.on('ready', function() {
            expect(map.infoControl._content.innerHTML).to.eql('Data provided by NatureServe in collaboration with Robert Ridgely');
            map.removeLayer(map.tileLayer);
            expect(map.infoControl._content.innerHTML).to.eql('');
            done();
        });

        server.respondWith("GET", internals.url.tileJSON("mapbox.map-0l53fhk2"),
            [200, { "Content-Type": "application/json" }, JSON.stringify(helpers.tileJSON)]);
        server.respond();
    });
});


text:
package org.apache.shiro.guice.web;

import com.google.inject.spi.InjectionPoint;
import org.apache.shiro.web.env.EnvironmentLoaderListener;
import org.apache.shiro.web.filter.mgt.FilterChainResolver;
import org.apache.shiro.web.mgt.WebSecurityManager;
import org.easymock.Capture;
import org.junit.Test;

import javax.servlet.ServletContext;

import static org.easymock.EasyMock.*;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;

public class WebGuiceEnvironmentTest {

    @Test
    public void ensureInjectable() {
        try {
            InjectionPoint ip = InjectionPoint.forConstructorOf(WebGuiceEnvironment.class);
        } catch (Exception e) {
            fail("Could not create constructor injection point.");
        }
    }

    @Test
    public void testConstructor() {
        WebSecurityManager securityManager = createMock(WebSecurityManager.class);
        FilterChainResolver filterChainResolver = createMock(FilterChainResolver.class);
        ServletContext servletContext = createMock(ServletContext.class);

        Capture<WebGuiceEnvironment> capture = new Capture<WebGuiceEnvironment>();
        servletContext.setAttribute(eq(EnvironmentLoaderListener.ENVIRONMENT_ATTRIBUTE_KEY), and(anyObject(WebGuiceEnvironment.class), capture(capture)));

        replay(servletContext, securityManager, filterChainResolver);

        WebGuiceEnvironment underTest = new WebGuiceEnvironment(filterChainResolver, servletContext, securityManager);

        assertSame(securityManager, underTest.getSecurityManager());
        assertSame(filterChainResolver, underTest.getFilterChainResolver());
        assertSame(securityManager, underTest.getWebSecurityManager());
        assertSame(servletContext, underTest.getServletContext());

        assertSame(underTest, capture.getValue());

        verify(servletContext);
    }
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

        <title>Beers @ Al's</title>
        <meta name="description" content="Providing a mobile-friendly list and Untappd integration to beers on tap at Al's of Hampden / Pizza Boy Brewing Co.!">
        <meta property="og:url" content="https://pizzaboy.taplists.com/">
        <meta property="og:title" content="Beers @ Al's">
        <meta property="og:description" content="Providing a mobile-friendly list and Untappd integration to beers on tap at Al's of Hampden / Pizza Boy Brewing Co.!">
        <meta property="og:image" content="https://pizzaboy.taplists.com/img/android-chrome-192x192.png">
        <meta property="og:image:type" content="image/png">

        <link rel="canonical" href="https://pizzaboy.taplists.com/" />
        <link rel="stylesheet" href="release/css/beersapp.min.css">

        <link rel="apple-touch-icon" sizes="57x57" href="img/apple-touch-icon-57x57.png">
        <link rel="apple-touch-icon" sizes="60x60" href="img/apple-touch-icon-60x60.png">
        <link rel="apple-touch-icon" sizes="72x72" href="img/apple-touch-icon-72x72.png">
        <link rel="apple-touch-icon" sizes="76x76" href="img/apple-touch-icon-76x76.png">
        <link rel="apple-touch-icon" sizes="114x114" href="img/apple-touch-icon-114x114.png">
        <link rel="apple-touch-icon" sizes="120x120" href="img/apple-touch-icon-120x120.png">
        <link rel="apple-touch-icon" sizes="144x144" href="img/apple-touch-icon-144x144.png">
        <link rel="apple-touch-icon" sizes="152x152" href="img/apple-touch-icon-152x152.png">
        <link rel="apple-touch-icon" sizes="180x180" href="img/apple-touch-icon-180x180.png">
        <link rel="icon" type="image/png" href="img/favicon-32x32.png" sizes="32x32">
        <link rel="icon" type="image/png" href="img/android-chrome-192x192.png" sizes="192x192">
        <link rel="icon" type="image/png" href="img/favicon-96x96.png" sizes="96x96">
        <link rel="icon" type="image/png" href="img/favicon-16x16.png" sizes="16x16">
        <link rel="manifest" href="img/android-chrome-manifest.json">
        <link rel="shortcut icon" href="img/favicon.ico">
        <meta name="msapplication-TileColor" content="#2b5797">
        <meta name="msapplication-TileImage" content="img/mstile-144x144.png">
        <meta name="msapplication-config" content="img/browserconfig.xml">
        <meta name="theme-color" content="#ffffff">

Beers @ Al's

            <data-navigation></data-navigation>

                    <data-ng-view></data-ng-view>

        <data-footer-topscroller></data-footer-topscroller>
        <data-ng-include src="'templates/modalHelp.html'"></data-ng-include>
        <data-ng-include src="'templates/modalAbout.html'"></data-ng-include>


text:
module.exports = function(grunt) {
    'use strict';

    grunt.registerTask( 'scandium-clean', 'This executes the `titanium clean` command.', function() {

        // Tell grunt this task is asynchronous.
        var done    = this.async(),
            exec    = require('child_process').exec,
            command = 'titanium clean';

        function puts( error, stdout, stderr ) {
            grunt.log.write( stdout );
            if ( error !== null ) {
                grunt.log.error( error );
                done(false);
            }
            else {
                done(true);
            }
        }

        exec( command, puts );
        grunt.log.write( '`' + command + '` was initiated.' );
    });
};


text:
public class Kata {
    public static int Multiply(int a, int b) {
        return a * b;
    }
}


text:
package com.carrotsearch.junitbenchmarks.h2;

import com.carrotsearch.junitbenchmarks.*;
import org.h2.jdbcx.JdbcDataSource;

import java.io.*;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.carrotsearch.junitbenchmarks.BenchmarkOptionsSystemProperties.*;
import static java.lang.Math.max;
import static org.junit.Assert.fail;

/**
 * {@link IResultsConsumer} that appends records to a H2 database.
 */
public final class H2Consumer extends AutocloseConsumer implements Closeable
{
    /*
     * Column indexes in the prepared insert statement.
     */
    private final static int RUN_ID, CLASSNAME, NAME, BENCHMARK_ROUNDS, WARMUP_ROUNDS,
        ROUND_AVG, ROUND_STDDEV, GC_AVG, GC_STDDEV, GC_INVOCATIONS, GC_TIME,
        TIME_BENCHMARK, TIME_WARMUP, UNITS;

    static
    {
        int column = 1;
        RUN_ID = column++;
        CLASSNAME = column++;
        NAME = column++;
        BENCHMARK_ROUNDS = column++;
        WARMUP_ROUNDS = column++;
        ROUND_AVG = column++;
        ROUND_STDDEV = column++;
        GC_AVG = column++;
        GC_STDDEV = column++;
        GC_INVOCATIONS = column++;
        GC_TIME = column++;
        TIME_BENCHMARK = column++;
        TIME_WARMUP = column++;
        UNITS = column++;
    }

    /* */
    private Connection connection;

    /** Unique primary key for this consumer in the RUNS table. */
    int runId;

    /** Insert statement to the tests table. */
    private PreparedStatement newTest;

    /** Output directory for charts. */
    File chartsDir;

    /**
     * Charting visitors.
     */
    private List<? extends IChartAnnotationVisitor> chartVisitors;

    /*
     *
     */
    public H2Consumer()
    {
        this(getDefaultDbName());
    }

    /*
     *
     */
    public H2Consumer(File dbFileName)
    {
        this(dbFileName, getDefaultChartsDir(), getDefaultCustomKey());
    }

    /*
     *
     */
    public H2Consumer(File dbFileName, File chartsDir, String customKeyValue)
    {
        try
        {
            final JdbcDataSource ds = new org.h2.jdbcx.JdbcDataSource();
            ds.setURL("jdbc:h2:" + dbFileName.getAbsolutePath() + ";DB_CLOSE_ON_EXIT=FALSE");
            ds.setUser("sa");

            this.chartsDir = chartsDir;
            this.chartVisitors = newChartVisitors();

            this.connection = ds.getConnection();
            connection.setAutoCommit(false);
            super.addAutoclose(this);

            checkSchema();

            runId = getRunID(customKeyValue);

            newTest = connection.prepareStatement(getResource("003-new-result.sql"));
            newTest.setInt(RUN_ID, runId);
        }
        catch (SQLException e)
        {
            throw new RuntimeException("Cannot initialize H2 database.", e);
        }
    }

    /*
     *
     */
    private List<? extends IChartAnnotationVisitor> newChartVisitors()
    {
        return Arrays.asList(
            new MethodChartVisitor(),
            new HistoryChartVisitor());
    }

    /**
     * Accept a single benchmark result.
     */
    public void accept(Result result)
    {
        // Visit chart collectors.
        final Class<?> clazz = result.getTestClass();
        final Method method = result.getTestMethod();
        for (IChartAnnotationVisitor v : chartVisitors)
            v.visit(clazz, method, result);

        try
        {
            newTest.setString(CLASSNAME, result.getTestClassName());
            newTest.setString(NAME, result.getTestMethodName());

            newTest.setInt(BENCHMARK_ROUNDS, result.benchmarkRounds);
            newTest.setInt(WARMUP_ROUNDS, result.warmupRounds);

            newTest.setDouble(ROUND_AVG, result.roundAverage.avg);
            newTest.setDouble(ROUND_STDDEV, result.roundAverage.stddev);

            newTest.setDouble(GC_AVG, result.gcAverage.avg);
            newTest.setDouble(GC_STDDEV, result.gcAverage.stddev);

            newTest.setInt(GC_INVOCATIONS, (int) result.gcInfo.accumulatedInvocations());
            newTest.setDouble(GC_TIME, result.gcInfo.accumulatedTime() / 1000.0);

            newTest.setDouble(TIME_WARMUP, result.warmupTime / 1000.0);
            newTest.setDouble(TIME_BENCHMARK, result.benchmarkTime / 1000.0);

            newTest.setLong(UNITS, result.units);

            newTest.executeUpdate();

            assertThatPerformanceDidNotDegrade(result);
        }
        catch (SQLException e)
        {
            throw new RuntimeException(
                "Error while saving the benchmark result to H2.", e);
        }
    }

    /**
     * Close the database connection and finalize transaction.
     */
    public void close()
    {
        try
        {
            if (connection != null)
            {
                if (!connection.isClosed())
                {
                    doClose();
                }
                connection = null;
            }
        }
        catch (Exception e)
        {
            throw new RuntimeException("Failed to close H2 consumer.", e);
        }
    }

    /**
     * Rollback all performed operations on request.
     */
    public void rollback()
    {
        try
        {
            connection.rollback();
            this.chartVisitors = newChartVisitors();
        }
        catch (SQLException e)
        {
            throw new RuntimeException("Could not rollback.", e);
        }
    }

    /**
     * Retrieve DB version.
     */
    DbVersions getDbVersion() throws SQLException
    {
        Statement s = connection.createStatement();
        ResultSet rs = s.executeQuery("SHOW TABLES");
        Set<String> tables = new HashSet<String>();
        while (rs.next())
        {
            tables.add(rs.getString(1));
        }

        if (!tables.contains("DBVERSION"))
        {
            if (tables.contains("RUNS"))
            {
                return DbVersions.VERSION_1;
            }

            return DbVersions.UNINITIALIZED;
        }

        DbVersions version;
        rs = s.executeQuery("SELECT VERSION FROM DBVERSION");
        if (!rs.next())
        {
            throw new RuntimeException("Missing version row in DBVERSION table.");
        }

        version = DbVersions.fromInt(rs.getInt(1));
        if (rs.next()) {
            throw new RuntimeException("More than one row in DBVERSION table.");
        }

        return version;
    }

    /**
     * Read a given resource from classpath and return UTF-8 decoded string.
     */
    static String getResource(String resourceName)
    {
        try
        {
            InputStream is = H2Consumer.class.getResourceAsStream(resourceName);
            if (is == null) throw new IOException();

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final byte [] buffer = new byte [1024];
            int cnt;
            while ((cnt = is.read(buffer)) > 0) {
                baos.write(buffer, 0, cnt);
            }
            is.close();
            baos.close();

            return new String(baos.toByteArray(), "UTF-8");
        }
        catch (IOException e)
        {
            throw new RuntimeException("Required resource missing: "
                + resourceName);
        }
    }

    /**
     * Return the global default DB name.
     */
    private static File getDefaultDbName()
    {
        final String dbPath = System.getProperty(BenchmarkOptionsSystemProperties.DB_FILE_PROPERTY);
        if (dbPath != null && !dbPath.trim().equals(""))
        {
            return new File(dbPath);
        }

        throw new IllegalArgumentException("Missing global property: "
            + BenchmarkOptionsSystemProperties.DB_FILE_PROPERTY);
    }

    private static String getDefaultCustomKey()
    {
        return System.getProperty(BenchmarkOptionsSystemProperties.CUSTOMKEY_PROPERTY);
    }

    private static File getDefaultChartsDir()
    {
        return new File(System.getProperty(BenchmarkOptionsSystemProperties.CHARTS_DIR_PROPERTY, "."));
    }

    /**
     * @return Create a row for this consumer's test run.
     */
    private int getRunID(String customKeyValue) throws SQLException
    {
        PreparedStatement s = connection.prepareStatement(
            getResource("002-new-run.sql"), Statement.RETURN_GENERATED_KEYS);
        s.setString(1, System.getProperty("java.runtime.version", "?"));
        s.setString(2, System.getProperty("os.arch", "?"));
        s.setString(3, customKeyValue);
        s.executeUpdate();

        ResultSet rs = s.getGeneratedKeys();
        if (!rs.next()) throw new SQLException("No autogenerated keys?");
        final int key = rs.getInt(1);
        if (rs.next()) throw new SQLException("More than one autogenerated key?");

        rs.close();
        s.close();

        return key;
    }

    /**
     * Do finalize the consumer; close db connection and emit reports.
     */
    private void doClose() throws Exception
    {
        try
        {
            for (IChartAnnotationVisitor v : chartVisitors)
            {
                v.generate(this);
            }
        }
        finally
        {
            if (!connection.isClosed())
            {
                connection.commit();
                connection.close();
            }
        }
    }

    /**
     * Check database schema and create it if needed.
     */
    private void checkSchema() throws SQLException
    {
        DbVersions dbVersion = getDbVersion();
        Statement s = connection.createStatement();
        switch (dbVersion)
        {
            case UNINITIALIZED:
                s.execute(getResource("000-create-runs.sql"));
                s.execute(getResource("001-create-tests.sql"));
                // fall-through.
            case VERSION_1:
                s.execute(getResource("004-create-dbversion.sql"));
                s.execute(getResource("005-add-custom-key.sql"));
                updateDbVersion(DbVersions.VERSION_2);
                // fall-through
            case VERSION_2:
                break;

            default:
                throw new RuntimeException("Unexpected database version: "
                    + dbVersion);
        }
        connection.commit();
    }

    /**
     * Update database version.
     */
    private void updateDbVersion(DbVersions newVersion) throws SQLException
    {
        Statement s = connection.createStatement();
        s.executeUpdate("DELETE FROM DBVERSION");
        s.executeUpdate("INSERT INTO DBVERSION (VERSION) VALUES (" + newVersion.version + ")");
    }

    /**
     *
     */
    Connection getConnection()
    {
        return connection;
    }

    /**
     * Extension made by peter.romianowski@optivo.de - assert that performance did not degrade.
     */
    void assertThatPerformanceDidNotDegrade(Result result) throws SQLException
    {
        BenchmarkOptions annotation = result.getTestMethod().getAnnotation(BenchmarkOptions.class);
        if (annotation == null) {
            annotation = result.getTestClass().getAnnotation(BenchmarkOptions.class);
        }
        if (runId > 1)
        {

            // This is not the first run ...
            int perfAverageOverRuns = (int) getPerfOption(annotation != null ? annotation.perfAverageOverRuns() : -1, PERF_AVERAGE_OVER_RUNS_PROPERTY);
            int perfIgnoreUpToRun = (int) getPerfOption(annotation != null ? annotation.perfIgnoreUpToRun() : -1, PERF_IGNORE_UP_TO_RUN_PROPERTY);
            double perfDiffToLastRun = getPerfOption(annotation != null ? annotation.perfDiffToLastRun() : -1, PERF_DIFF_TO_LAST_RUN_PROPERTY);
            double perfDiffToAverage = getPerfOption(annotation != null ? annotation.perfDiffToAverage() : -1, PERF_DIFF_TO_AVERAGE_PROPERTY);
            double average = getRoundAverageFor(result, max(perfIgnoreUpToRun, runId - perfAverageOverRuns), runId - 1);
            double last = getRoundAverageFor(result, max(perfIgnoreUpToRun, runId - 1), max(perfIgnoreUpToRun, runId - 1));

            double lastPerformanceDiff = last != 0 ? (result.roundAverage.avg / last) - 1 : 0;
            if (perfDiffToLastRun >= 0 && lastPerformanceDiff > perfDiffToLastRun)
                fail("Performance degraded by " + (int)(lastPerformanceDiff * 10000) / 100f + "% compared to last run: " + result.roundAverage.avg + " vs. " + (int)(last * 1000) / 1000f);

            double averagePerformanceDiff = average != 0 ? (result.roundAverage.avg / average) - 1 : 0;
            if (perfAverageOverRuns > 0 && perfDiffToAverage >= 0 && averagePerformanceDiff > perfDiffToAverage)
                fail("Performance degraded by " + (int)(averagePerformanceDiff * 10000) / 100f + "% compared to average of the last " + perfAverageOverRuns + " runs: " + result.roundAverage.avg + " vs. " + (int)(average * 1000) / 1000f);
        }
    }

    private double getPerfOption(double value, String systemPropertiesKey)
    {
        double result = value;
        if (result < 0) {
            final String s = System.getProperty(systemPropertiesKey);
            if (s != null && s.length() > 0) {
                result = Double.parseDouble(s);
            }
        }
        return result;
    }

    private double getRoundAverageFor(Result result, int minRunId, int maxRunId) throws SQLException
    {
        PreparedStatement s = connection.prepareStatement(
            "SELECT AVG(ROUND_AVG) "
          + "FROM tests t, runs r "
          + "WHERE t.run_id = r.id "
          + "      AND t.classname = ? AND t.name = ? AND t.run_id >= ? AND t.run_id <= ?");
        try
        {
            s.setString(1, result.getTestClassName());
            s.setString(2, result.getTestMethodName());
            s.setInt(3, max(0, minRunId));
            s.setInt(4, max(0, maxRunId));
            final ResultSet resultSet = s.executeQuery();
            double average = 0;
            try
            {
                if (resultSet.next())
                    average = resultSet.getDouble(1);
                return average;
            }
            finally
            {
                resultSet.close();
            }
        }
        finally
        {
            s.close();
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Appy.GitDb.Core.Model;
using Appy.GitDb.Tests.Utils;
using FluentAssertions;
using Xunit;

namespace Appy.GitDb.Tests
{
    public class LogWhenThereAreChanges : WithRepo
    {
        const string BranchA = "master";
        const string TagA = "tagA";
        string _commitA;
        const string BranchB = "branch";
        const string TagB = "tagB";
        string _commitB;

        readonly List<CommitInfo> _commits = new List<CommitInfo>
        {
            new CommitInfo{Author = new Author("auth1", "email"), Message = "msg1"},
            new CommitInfo{Author = new Author("auth2", "email"), Message = "msg2"},
            new CommitInfo{Author = new Author("auth3", "email"), Message = "msg3"},
        };

        protected override async Task Because()
        {
            await Subject.CreateBranch(new Reference{Name = BranchB, Pointer = BranchA});
            _commitA = Repo.Branches[BranchA].Tip.Sha;
            await Subject.Tag(new Reference { Name = TagA, Pointer = BranchA });

            var i = 0;
            foreach (var commitInfo in _commits)
            {
                await Subject.Save(BranchB, commitInfo.Message, new Document {Key = i.ToString(), Value = "value"}, commitInfo.Author);
                i++;
            }
            _commitB = Repo.Branches[BranchB].Tip.Sha;
            await Subject.Tag(new Reference { Name = TagB, Pointer = BranchB });
        }

        [Fact]
        public async Task ShowsLogBetweenBranches() =>
            testLog(await Subject.Log(BranchB, BranchA));

        [Fact]
        public async Task ShowsLogBetweenCommits() =>
            testLog(await Subject.Log(_commitB, _commitA));

        [Fact]
        public async Task ShowsLogBetweenTags() =>
            testLog(await Subject.Log(TagB, TagA));

        void testLog(List<CommitInfo> logs) =>
            logs.ForEach(l =>
            {
                var commit = _commits[logs.IndexOf(l)];
                l.Author.Name.Should().Be(commit.Author.Name);
                l.Author.Email.Should().Be(commit.Author.Email);
                l.Message.Should().Be(commit.Message);
            });
    }

    public class LogWhenThereAreNoChanges : WithRepo
    {
        readonly Document[] _baseDocuments =
        {
            new Document{Key= "a", Value="a"},
            new Document{Key= "b", Value="a"},
            new Document{Key= "c", Value="a"}
        };

        const string BranchA = "master";
        const string BranchB = "branch";

        protected override async Task Because()
        {
            using (var t = await Subject.CreateTransaction(BranchA))
            {
                await t.AddMany(_baseDocuments);
                await t.Commit("base docs", Author);
            }

            await Subject.CreateBranch(new Reference { Name = BranchB, Pointer = BranchA });
        }

        [Fact]
        public async Task ShowsNoLog() =>
            (await Subject.Log(BranchA, BranchB)).Should().BeEmpty();
    }

    public class LogWithAnInvalidReference : WithRepo
    {
        readonly Document[] _baseDocuments =
        {
            new Document{Key= "a", Value="a"},
            new Document{Key= "b", Value="a"},
            new Document{Key= "c", Value="a"}
        };

        const string BranchA = "master";
        const string BranchB = "branch";

        protected override async Task Because()
        {
            using (var t = await Subject.CreateTransaction(BranchA))
            {
                await t.AddMany(_baseDocuments);
                await t.Commit("base docs", Author);
            }

            await Subject.CreateBranch(new Reference { Name = BranchB, Pointer = BranchA });
        }

        [Fact]
        public Task ThrowsAnArgumentException() =>
            Utils.Utils.Catch<ArgumentException>(() => Subject.Log(BranchA, "somebranch"));
    }
}


text:
<project name = "AncestorView" default = "dist" basedir = ".">

	<property name = "src" location = "src/main/java"       />
	<property name = "res" location = "src/main/resources"  />
	<property name = "lib" location = "lib"                 />

	<property name = "out" location = "dist"                />
	<property name = "tmp" location = "tmp.dir"             />

	<basename property = "project.name" file = "${basedir}" />

	<path id = "project.lib">
		<fileset dir = "${lib}">
			<include name = "*.jar" />
		</fileset>
	</path>

	<target name = "clean">
		<delete dir = "${out}" />
		<delete dir = "${tmp}" />
	</target>

	<target name = "dist">
		<!-- Ensure "mct.dir" is set -->
		<fail unless = "mct.dir">
			Please supply the location of MCT's packaging for use in this plugin's classpath.
			Example: ant -Dmct.dir=[location of MCT packaging]
		</fail>

		<!-- Prepare output directories -->
		<mkdir dir  = "${out}" />
		<mkdir dir  = "${tmp}" />

		<!-- Compile sources    -->
	    <javac srcdir  = "${src}"
	           destdir = "${tmp}"
	           target  = "1.6"
	    	   includeantruntime = "false">
	      	<classpath>
	      		<fileset dir = "${mct.dir}">
	      			<include name = "lib/*.jar"          />
	      			<include name = "resources/**/*.jar" />
	      		</fileset>
	      </classpath>
	    </javac>

		<!-- Copy support files -->
		<copy todir = "${tmp}">
			<fileset dir = "${res}">
				<include name = "**/*" />
			</fileset>
		</copy>

		<!-- Package into jar   -->
		<jar destfile = "${out}/${project.name}.jar"
		     manifest = "META-INF/MANIFEST.MF"
		     basedir  = "${tmp}" />

	</target>
</project>


text:
namespace Azure.Communication.Chat
{
    /// <summary> The UpdateChatThreadRequest. </summary>
    internal partial class UpdateChatThreadRequest
    {
        /// <summary> Initializes a new instance of UpdateChatThreadRequest. </summary>
        public UpdateChatThreadRequest()
        {
        }

        /// <summary> Chat thread topic. </summary>
        public string Topic { get; set; }
    }
}


text:
smokeout=`/usr/lib/hive/bin/beeline -u $1 -n fakeuser -p fakepwd -d org.apache.hive.jdbc.HiveDriver -e '!run $2' 2>&1| awk '{print}'|grep Error`

if [ "x$smokeout" == "x" ]; then
  echo "Smoke test of hiveserver2 passed"
  exit 0
else
  echo "Smoke test of hiveserver2 wasnt passed"
  echo $smokeout
  exit 1
fi


text:
#pragma once

#include "pockets/Scene.h"
#include "Treent.h"

class TreentGui : public pk::Scene
{
public:
  TreentGui() = default;
  ~TreentGui() = default;

  void setup() override;
  void connect( ci::app::WindowRef window ) override;
  void update( double dt ) override;
  void draw() override;

  void mouseDown( ci::app::MouseEvent event );
  void mouseDrag( ci::app::MouseEvent event );
  void mouseUp( ci::app::MouseEvent event );

private:
  treent::Treent          _treent;
  treent::RootNodeRef     _treent_root;
  ci::vec2               _mouse_position;
  ci::vec2               _mouse_start;
  ci::vec2               _node_start;
  bool                    _mouse_down = false;
};


text:
layout: index
title: GetRandomDouble
---

    GetRandomDouble ()

Returns a random [double](../types/double.html) value between 0.0 and 1.0.

NOTE: This a [hard-coded function](hardcoded.html).


text:
#define nv04_instmem(p) container_of((p), struct nv04_instmem, base)
#include "priv.h"

#include <core/memory.h>
#include <core/ramht.h>

struct nv04_instmem {
	struct nvkm_instmem base;
	struct nvkm_mm heap;
};

/******************************************************************************
 * instmem object implementation
 *****************************************************************************/
#define nv04_instobj(p) container_of((p), struct nv04_instobj, memory)

struct nv04_instobj {
	struct nvkm_memory memory;
	struct nv04_instmem *imem;
	struct nvkm_mm_node *node;
};

static enum nvkm_memory_target
nv04_instobj_target(struct nvkm_memory *memory)
{
	return NVKM_MEM_TARGET_INST;
}

static u64
nv04_instobj_addr(struct nvkm_memory *memory)
{
	return nv04_instobj(memory)->node->offset;
}

static u64
nv04_instobj_size(struct nvkm_memory *memory)
{
	return nv04_instobj(memory)->node->length;
}

static void __iomem *
nv04_instobj_acquire(struct nvkm_memory *memory)
{
	struct nv04_instobj *iobj = nv04_instobj(memory);
	struct nvkm_device *device = iobj->imem->base.subdev.device;
	return device->pri + 0x700000 + iobj->node->offset;
}

static void
nv04_instobj_release(struct nvkm_memory *memory)
{
}

static u32
nv04_instobj_rd32(struct nvkm_memory *memory, u64 offset)
{
	struct nv04_instobj *iobj = nv04_instobj(memory);
	struct nvkm_device *device = iobj->imem->base.subdev.device;
	return nvkm_rd32(device, 0x700000 + iobj->node->offset + offset);
}

static void
nv04_instobj_wr32(struct nvkm_memory *memory, u64 offset, u32 data)
{
	struct nv04_instobj *iobj = nv04_instobj(memory);
	struct nvkm_device *device = iobj->imem->base.subdev.device;
	nvkm_wr32(device, 0x700000 + iobj->node->offset + offset, data);
}

static void *
nv04_instobj_dtor(struct nvkm_memory *memory)
{
	struct nv04_instobj *iobj = nv04_instobj(memory);
	mutex_lock(&iobj->imem->base.subdev.mutex);
	nvkm_mm_free(&iobj->imem->heap, &iobj->node);
	mutex_unlock(&iobj->imem->base.subdev.mutex);
	return iobj;
}

static const struct nvkm_memory_func
nv04_instobj_func = {
	.dtor = nv04_instobj_dtor,
	.target = nv04_instobj_target,
	.size = nv04_instobj_size,
	.addr = nv04_instobj_addr,
	.acquire = nv04_instobj_acquire,
	.release = nv04_instobj_release,
	.rd32 = nv04_instobj_rd32,
	.wr32 = nv04_instobj_wr32,
};

static int
nv04_instobj_new(struct nvkm_instmem *base, u32 size, u32 align, bool zero,
		 struct nvkm_memory **pmemory)
{
	struct nv04_instmem *imem = nv04_instmem(base);
	struct nv04_instobj *iobj;
	int ret;

	if (!(iobj = kzalloc(sizeof(*iobj), GFP_KERNEL)))
		return -ENOMEM;
	*pmemory = &iobj->memory;

	nvkm_memory_ctor(&nv04_instobj_func, &iobj->memory);
	iobj->imem = imem;

	mutex_lock(&imem->base.subdev.mutex);
	ret = nvkm_mm_head(&imem->heap, 0, 1, size, size,
			   align ? align : 1, &iobj->node);
	mutex_unlock(&imem->base.subdev.mutex);
	return ret;
}

/******************************************************************************
 * instmem subdev implementation
 *****************************************************************************/

static u32
nv04_instmem_rd32(struct nvkm_instmem *imem, u32 addr)
{
	return nvkm_rd32(imem->subdev.device, 0x700000 + addr);
}

static void
nv04_instmem_wr32(struct nvkm_instmem *imem, u32 addr, u32 data)
{
	nvkm_wr32(imem->subdev.device, 0x700000 + addr, data);
}

static int
nv04_instmem_oneinit(struct nvkm_instmem *base)
{
	struct nv04_instmem *imem = nv04_instmem(base);
	struct nvkm_device *device = imem->base.subdev.device;
	int ret;

	/* PRAMIN aperture maps over the end of VRAM, reserve it */
	imem->base.reserved = 512 * 1024;

	ret = nvkm_mm_init(&imem->heap, 0, imem->base.reserved, 1);
	if (ret)
		return ret;

	/* 0x00000-0x10000: reserve for probable vbios image */
	ret = nvkm_memory_new(device, NVKM_MEM_TARGET_INST, 0x10000, 0, false,
			      &imem->base.vbios);
	if (ret)
		return ret;

	/* 0x10000-0x18000: reserve for RAMHT */
	ret = nvkm_ramht_new(device, 0x08000, 0, NULL, &imem->base.ramht);
	if (ret)
		return ret;

	/* 0x18000-0x18800: reserve for RAMFC (enough for 32 nv30 channels) */
	ret = nvkm_memory_new(device, NVKM_MEM_TARGET_INST, 0x00800, 0, true,
			      &imem->base.ramfc);
	if (ret)
		return ret;

	/* 0x18800-0x18a00: reserve for RAMRO */
	ret = nvkm_memory_new(device, NVKM_MEM_TARGET_INST, 0x00200, 0, false,
			      &imem->base.ramro);
	if (ret)
		return ret;

	return 0;
}

static void *
nv04_instmem_dtor(struct nvkm_instmem *base)
{
	struct nv04_instmem *imem = nv04_instmem(base);
	nvkm_memory_del(&imem->base.ramfc);
	nvkm_memory_del(&imem->base.ramro);
	nvkm_ramht_del(&imem->base.ramht);
	nvkm_memory_del(&imem->base.vbios);
	nvkm_mm_fini(&imem->heap);
	return imem;
}

static const struct nvkm_instmem_func
nv04_instmem = {
	.dtor = nv04_instmem_dtor,
	.oneinit = nv04_instmem_oneinit,
	.rd32 = nv04_instmem_rd32,
	.wr32 = nv04_instmem_wr32,
	.memory_new = nv04_instobj_new,
	.persistent = false,
	.zero = false,
};

int
nv04_instmem_new(struct nvkm_device *device, int index,
		 struct nvkm_instmem **pimem)
{
	struct nv04_instmem *imem;

	if (!(imem = kzalloc(sizeof(*imem), GFP_KERNEL)))
		return -ENOMEM;
	nvkm_instmem_ctor(&nv04_instmem, device, index, &imem->base);
	*pimem = &imem->base;
	return 0;
}


text:
namespace installer {
namespace master_preferences {
// All the preferences below are expected to be inside the JSON "distribution"
// block. Some of them also have equivalent command line option. If same option
// is specified in master preference as well as command line, the command line
// value takes precedence.

// Boolean. Use alternate text for the shortcut. Cmd line override present.
extern const char kAltShortcutText[];
// Boolean. Whether to instruct the installer to auto-launch chrome on computer
// startup. The default (if not provided) is |false|.
extern const char kAutoLaunchChrome[];
// Boolean. This is to be a Chrome install. (When using MultiInstall)
extern const char kChrome[];
// Boolean. This is to be a Chrome App Host install.
extern const char kChromeAppHost[];
// Boolean. This is to be a Chrome Frame install.
extern const char kChromeFrame[];
// Boolean. Chrome Frame is to be installed in ready-mode.
extern const char kChromeFrameReadyMode[];
// Integer. Icon index from chrome.exe to use for shortcuts.
extern const char kChromeShortcutIconIndex[];
// Boolean. Create Desktop and QuickLaunch shortcuts. Cmd line override present.
extern const char kCreateAllShortcuts[];
// Boolean pref that disables all logging.
extern const char kDisableLogging[];
// Boolean pref that triggers silent import of the default browser bookmarks.
extern const char kDistroImportBookmarksPref[];
// String pref that triggers silent import of bookmarks from the html file at
// given path.
extern const char kDistroImportBookmarksFromFilePref[];
// Boolean pref that triggers silent import of the default browser history.
extern const char kDistroImportHistoryPref[];
// Boolean pref that triggers silent import of the default browser homepage.
extern const char kDistroImportHomePagePref[];
// Boolean pref that triggers silent import of the default search engine.
extern const char kDistroImportSearchPref[];
// Integer. RLZ ping delay in seconds.
extern const char kDistroPingDelay[];
// Boolean pref that triggers loading the welcome page.
extern const char kDistroShowWelcomePage[];
// Boolean pref that triggers skipping the first run dialogs.
extern const char kDistroSkipFirstRunPref[];
// Boolean. Do not show first run bubble, even if it would otherwise be shown.
extern const char kDistroSuppressFirstRunBubble[];
// Boolean. Do not launch Chrome after first install. Cmd line override present.
extern const char kDoNotLaunchChrome[];
// Boolean. Do not register with Google Update to have Chrome launched after
// install. Cmd line override present.
extern const char kDoNotRegisterForUpdateLaunch[];
// String.  Specifies the file path to write logging info to.
extern const char kLogFile[];
// Boolean. Register Chrome as default browser. Cmd line override present.
extern const char kMakeChromeDefault[];
// Boolean. Register Chrome as default browser for the current user.
extern const char kMakeChromeDefaultForUser[];
// Boolean. Expect to be run by an MSI installer. Cmd line override present.
extern const char kMsi[];
// Boolean. Support installing multiple products at once.
extern const char kMultiInstall[];
// Boolean. Show EULA dialog before install.
extern const char kRequireEula[];
// Boolean. Install Chrome to system wise location. Cmd line override present.
extern const char kSystemLevel[];
// Boolean. Run installer in verbose mode. Cmd line override present.
extern const char kVerboseLogging[];
// Name of the block that contains the extensions on the master preferences.
extern const char kExtensionsBlock[];
}  // namespace master_preferences
}  // namespace installer

#endif  // CHROME_INSTALLER_UTIL_MASTER_PREFERENCES_CONSTANTS_H_


text:
using System;
using System.Web.Http;
using System.Web.Http.ModelBinding;

namespace Climax.Web.Http.Binders
{
    public class SimpleArrayModelBinderProvider : ModelBinderProvider
    {
        public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType)
        {
            if (modelType == null)
            {
                throw new ArgumentNullException();
            }

            if (!modelType.IsArray)
            {
                return null;
            }

            var elementType = modelType.GetElementType();
            if (elementType.IsPrimitive || typeof(string) == elementType)
            {
                return (IModelBinder)Activator.CreateInstance(typeof(SimpleArrayModelBinder<>).MakeGenericType(elementType));
            }

            return null;
        }
    }
}


text:
<?php

namespace Amadeus\Client\Struct\Fop;

/**
 * PassengerAssociation
 *
 * @package Amadeus\Client\Struct\Fop
 * @author Dieter Devlieghere <dermikagh@gmail.com>
 */
class PassengerAssociation
{
    /**
     * @var PassengerReference
     */
    public $passengerReference;

    /**
     * PassengerAssociation constructor.
     *
     * @param string $type
     * @param string|int $value
     */
    public function __construct($type, $value)
    {
        $this->passengerReference = new PassengerReference($type, $value);
    }
}


text:
<?php
/**
 * This file is part of the KrisMvc framework.
 *
 * (c) Kris Erickson
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

/**
 *  @package debug
 */
class DebugRouter extends KrisRouter
{
    /**
     * @param string $controllerPath
     */
    public function Route($controllerPath)
    {

        $this->controllerPath = $controllerPath;

        $route =  RouteRequest::CreateFromUri($this->GetRequestUri(), $this->routeActionOnly);

        if ($route->Controller == 'KrisMVCDebug')
        {
            $this->EmitDebugAssets($route->Action);
        }
        else
        {
            /** @var $log DebugLog */
            $log = AutoLoader::Container()->get('Log');
            $log->Debug('Controller path: '.$controllerPath.' Controller: '.$route->Controller.' Action: '.$route->Action.' Params: ('.implode(',', $route->Params).')');
            $message = '';

            $startTime = microtime(true);
            $startMemoryUsage = memory_get_usage(true);
            ob_start();
            try
            {
                $this->ParseRequest($route->Controller, $route->Action, $route->Params);
            }
            catch (Exception $ex)
            {
                $trace = $ex->getTrace();
                foreach ($trace as $line)
                {
                    $message .= '  '.(isset($line['file']) ? 'file: '.$line['file'].', ' : 'Anonymous: ').(isset($line['line']) ? ' line: '.$line['line'].' : ' : '').
                            (isset($line['class']) ? $line['class'].'->' : '').$line['function'];
                    if (isset($line['args']))
                    {
                        $message .= '('.implode(',', array_map(create_function('$a', 'return gettype($a);'), $line['args'])).')';
                    }
                    $message .= PHP_EOL;
                }
                $message = $ex->getMessage().PHP_EOL.$message;
                $log->Error('Uncaught exception: '.$message);

                if ($this->request->IsJson)
                {
                    $this->request->JsonResponse(array('success' => false, 'message' => $message));
                }
            }
            $endTime = microtime(true);
            $content = ob_get_clean();

            if ($this->request->IsHtml)
            {
                $elapsedTime = ($endTime - $startTime) * 1000;
                if (strpos($content, '') !== false)
                {
                    echo str_replace('', $this->GetWebBar($elapsedTime, $startMemoryUsage, $log) . '', $content);
                }
                else
                {
                    // If there is no message, we probably have BS content...
                    if (strlen($message) > 0)
                    {
                        $content = '';
                    }
                    echo ''.$content.$this->GetWebBar($elapsedTime, $startMemoryUsage, $log).'';
                }
            }
            else
            {
                echo $content;
            }
        }

    }

    /**
     * @param int $elapsedTime
     * @param int $startMemoryUsage
     * @param DebugLog $log
     * @return string
     */
    public function GetWebBar($elapsedTime, $startMemoryUsage, $log)
    {
        $jsVars = '';
        $dbVars = '';

        // Get Database Log
        $db = AutoLoader::Container()->get('PDO');
        /** @var $db DebugPDO */
        $databaseQueryCount = count($db->DatabaseLog);
        $dbTime = 0;
        if ($databaseQueryCount > 0)
        {
            for ($i = 0; $i < $databaseQueryCount; $i++)
            {
                $dbLogItem = $db->DatabaseLog[$i];
                $dbVars .= ($i > 0 ? ','
                        : '') . '{ func: "' . $dbLogItem['function'] . '", query: "' . $dbLogItem['query'] . '", milliseconds: ' . number_format($dbLogItem['microseconds'] * 1000, 2) . '}';
                $dbTime += $dbLogItem['microseconds'];
            }
        }
        $dbTime *= 1000;

        // Get Memory Log
        $peakUsage = memory_get_peak_usage(true);
        $currentUsage = memory_get_usage(true);
        $diffUsage = $currentUsage - $startMemoryUsage;
        $diffMemory = NumberHelpers::BytesToHuman($diffUsage);
        $peakMemory = NumberHelpers::BytesToHuman($peakUsage);
        $currentMemory = NumberHelpers::BytesToHuman($currentUsage);

        $jsVars .= 'dbLog = [' . $this->CleanJSVar($dbVars) . '];' . PHP_EOL;
        $jsVars .= "memoryLog = '
Memory Info
Peak Memory Usage: $peakMemory ($peakUsage Bytes)
" .
                "Current Usage: $currentMemory ($currentUsage Bytes)
" .
                "Amount Used: $diffMemory ($diffUsage Bytes)
';" . PHP_EOL;

        // Get Time Log
        $jsVars .= "timeLog = '
Time Info
Time To Create Page: " . number_format($elapsedTime, 4) . " milliseconds
" .
                "Database Query Time: " . number_format($dbTime, 4) . " milliseconds
" .
                "Processing Time: " . number_format($elapsedTime - $dbTime, 2) . " milliseconds
';" . PHP_EOL;

        $jsVars .= "debugLog = '" . $this->CleanJSVar($log->GetErrorLog()) . "';" . PHP_EOL;

        $debugPrefix = (empty($_SERVER['HTTPS']) ? 'http://' : 'https://').KrisConfig::$SERVER_NAME.KrisConfig::WEB_FOLDER.'/KrisMVCDebug/';

        $webBar = '

' .
                '
show bar
' .
                '

' .
                '
KrisMVC Version: ' . KRIS_MVC_VERSION . '
' .
                '
Config
' .
                '
Logs
' .
                '
Database: ' . $databaseQueryCount . '
' .
                '
Time: ' . (int)($elapsedTime) . 'ms
' .
                '
Memory: ' . $diffMemory . '

' .
                '

' .
                '<link rel="stylesheet" href="' . $debugPrefix . 'debug.css" type="text/css" media="screen" />' .
                '' .
                '';

        return $webBar;
    }

    /**
     * @param string $debugLog
     * @return string
     */
    private function CleanJSVar($debugLog)
    {
        return str_replace(PHP_EOL, '', nl2br(str_replace("'", "\\'", str_replace('\\', '\\\\', $debugLog))));
    }

    /**
     * @param string $asset
     * @return void
     */
    private function EmitDebugAssets($asset)
    {
        switch($asset)
        {
            case 'debug.js':
                header('Content-type: application/javascript');
                readfile(KrisConfig::FRAMEWORK_DIR.'/lib/debug/js/debug.js');
                break;
            case 'debug.css' :
                header('Content-type: text/css');
                readfile(KrisConfig::FRAMEWORK_DIR.'/lib/debug/css/debug.css');
                break;
            default:
                header('Content-type: image/png');
                readfile(KrisConfig::FRAMEWORK_DIR.'/lib/debug/images/'.$asset);

        }
    }

}