text:
import {Observable} from '../../observable';
import {Services} from '../../services';
import {ViewportBindingDef} from './viewport-binding-def';
import {computedStyle, px, setImportantStyles} from '../../style';
import {dev} from '../../log';
import {isExperimentOn} from '../../experiments';
import {layoutRectLtwh} from '../../layout-rect';

const TAG_ = 'Viewport';

/**
 * Implementation of ViewportBindingDef based on the native window. It assumes
 * that the native window is sized properly and events represent the actual
 * scroll/resize events. This mode is applicable to a standalone document
 * display or when an iframe has a fixed size.
 *
 * Visible for testing.
 *
 * @implements {ViewportBindingDef}
 */
export class ViewportBindingNatural_ {

  /**
   * @param {!../ampdoc-impl.AmpDoc} ampdoc
   */
  constructor(ampdoc) {
    /** @const {!../ampdoc-impl.AmpDoc} */
    this.ampdoc = ampdoc;

    /** @const {!Window} */
    this.win = ampdoc.win;

    /** @const {!../../service/platform-impl.Platform} */
    this.platform_ = Services.platformFor(this.win);

    /** @private @const {!Observable} */
    this.scrollObservable_ = new Observable();

    /** @private @const {!Observable} */
    this.resizeObservable_ = new Observable();

    /** @const {function()} */
    this.boundScrollEventListener_ = () => {
      this.scrollObservable_.fire();
    };

    /** @const {function()} */
    this.boundResizeEventListener_ = () => this.resizeObservable_.fire();

    /** @private @const {boolean} */
    this.useLayers_ = isExperimentOn(this.win, 'layers');

    dev().fine(TAG_, 'initialized natural viewport');
  }

  /** @override */
  connect() {
    this.win.addEventListener('scroll', this.boundScrollEventListener_);
    this.win.addEventListener('resize', this.boundResizeEventListener_);
  }

  /** @override */
  disconnect() {
    this.win.removeEventListener('scroll', this.boundScrollEventListener_);
    this.win.removeEventListener('resize', this.boundResizeEventListener_);
  }

  /** @override */
  ensureReadyForElements() {
    // Nothing.
  }

  /** @override */
  getBorderTop() {
    return 0;
  }

  /** @override */
  requiresFixedLayerTransfer() {
    return false;
  }

  /** @override */
  supportsPositionFixed() {
    return true;
  }

  /** @override */
  onScroll(callback) {
    this.scrollObservable_.add(callback);
  }

  /** @override */
  onResize(callback) {
    this.resizeObservable_.add(callback);
  }

  /** @override */
  updatePaddingTop(paddingTop) {
    setImportantStyles(this.win.document.documentElement, {
      'padding-top': px(paddingTop),
    });
  }

  /** @override */
  hideViewerHeader(transient, unusedLastPaddingTop) {
    if (!transient) {
      this.updatePaddingTop(0);
    }
  }

  /** @override */
  showViewerHeader(transient, paddingTop) {
    if (!transient) {
      this.updatePaddingTop(paddingTop);
    }
  }

  /** @override */
  disableScroll() {
    // TODO(jridgewell): Recursively disable scroll
    this.win.document.documentElement.classList.add(
        'i-amphtml-scroll-disabled');
  }

  /** @override */
  resetScroll() {
    // TODO(jridgewell): Recursively disable scroll
    this.win.document.documentElement.classList.remove(
        'i-amphtml-scroll-disabled');
  }

  /** @override */
  updateLightboxMode(unusedLightboxMode) {
    // The layout is always accurate.
    return Promise.resolve();
  }

  /** @override */
  getSize() {
    // Prefer window innerWidth/innerHeight but fall back to
    // documentElement clientWidth/clientHeight.
    // documentElement./*OK*/clientHeight is buggy on iOS Safari
    // and thus cannot be used.
    const winWidth = this.win./*OK*/innerWidth;
    const winHeight = this.win./*OK*/innerHeight;
    if (winWidth && winHeight) {
      return {width: winWidth, height: winHeight};
    }
    const el = this.win.document.documentElement;
    return {width: el./*OK*/clientWidth, height: el./*OK*/clientHeight};
  }

  /** @override */
  getScrollTop() {
    const pageScrollTop = this.getScrollingElement()./*OK*/scrollTop ||
        this.win./*OK*/pageYOffset;
    const {host} = this.ampdoc.getRootNode();
    return (host ? pageScrollTop - host./*OK*/offsetTop : pageScrollTop);
  }

  /** @override */
  getScrollLeft() {
    // The html is set to overflow-x: hidden so the document cannot be
    // scrolled horizontally. The scrollLeft will always be 0.
    return 0;
  }

  /** @override */
  getScrollWidth() {
    return this.getScrollingElement()./*OK*/scrollWidth;
  }

  /** @override */
  getScrollHeight() {
    return this.getScrollingElement()./*OK*/scrollHeight;
  }

  /** @override */
  getContentHeight() {
    // Don't use scrollHeight, since it returns `MAX(viewport_height,
    // document_height)` (we only want the latter), and it doesn't account
    // for margins. Also, don't use documentElement's rect height because
    // there's no workable analog for either ios-embed-* modes.
    const scrollingElement = this.getScrollingElement();
    const rect = scrollingElement./*OK*/getBoundingClientRect();
    const style = computedStyle(this.win, scrollingElement);
    // The Y-position of any element can be offset by the vertical margin
    // of its first child, and this is _not_ accounted for in `rect.height`.
    // This "top gap" causes smaller than expected contentHeight, so calculate
    // and add it manually. Note that the "top gap" includes any padding-top
    // on ancestor elements, and the "bottom gap" remains unaddressed.
    const topGapPlusPadding = rect.top + this.getScrollTop();
    return rect.height
        + topGapPlusPadding
        + parseInt(style.marginTop, 10)
        + parseInt(style.marginBottom, 10);
  }

  /** @override */
  contentHeightChanged() {
    // Nothing to do here.
  }

  /** @override */
  getLayoutRect(el, opt_scrollLeft, opt_scrollTop) {
    const b = el./*OK*/getBoundingClientRect();
    if (this.useLayers_) {
      return layoutRectLtwh(b.left, b.top, b.width, b.height);
    }

    const scrollTop = opt_scrollTop != undefined
      ? opt_scrollTop
      : this.getScrollTop();
    const scrollLeft = opt_scrollLeft != undefined
      ? opt_scrollLeft
      : this.getScrollLeft();
    return layoutRectLtwh(Math.round(b.left + scrollLeft),
        Math.round(b.top + scrollTop),
        Math.round(b.width),
        Math.round(b.height));
  }

  /** @override */
  getRootClientRectAsync() {
    return Promise.resolve(null);
  }

  /** @override */
  setScrollTop(scrollTop) {
    this.getScrollingElement()./*OK*/scrollTop = scrollTop;
  }

  /** @override */
  getScrollingElement() {
    const doc = this.win.document;
    if (doc./*OK*/scrollingElement) {
      return doc./*OK*/scrollingElement;
    }
    if (doc.body
        // Due to https://bugs.webkit.org/show_bug.cgi?id=106133, WebKit
        // browsers have to use `body` and NOT `documentElement` for
        // scrolling purposes. This has mostly being resolved via
        // `scrollingElement` property, but this branch is still necessary
        // for backward compatibility purposes.
        && this.platform_.isWebKit()) {
      return doc.body;
    }
    return doc.documentElement;
  }

  /** @override */
  getScrollingElementScrollsLikeViewport() {
    return true;
  }
}


text:
package org.onosproject.d.config.sync.operation;

import static com.google.common.base.Preconditions.checkNotNull;

import java.util.Collection;
import java.util.Objects;

import org.apache.commons.lang3.tuple.Pair;
import org.onosproject.d.config.sync.operation.SetRequest.Change.Operation;
import org.onosproject.yang.model.ResourceId;

import com.google.common.annotations.Beta;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableList;

@Beta
public final class SetResponse {

    // partially borrowed from io.grpc.Status.Code,
    // might want to borrow all of them
    public enum Code {
        OK,
        CANCELLED,

        UNKNOWN,

        INVALID_ARGUMENT,

        NOT_FOUND,
        ALREADY_EXISTS,

        FAILED_PRECONDITION,
        ABORTED,
        UNAVAILABLE,
    }

    private final Collection<Pair<Operation, ResourceId>> subjects;

    private final SetResponse.Code code;

    // human readable error message for logging purpose
    private final String message;

    SetResponse(Collection<Pair<Operation, ResourceId>> subjects,
                SetResponse.Code code,
                String message) {
        this.subjects = ImmutableList.copyOf(subjects);
        this.code = checkNotNull(code);
        this.message = checkNotNull(message);
    }

    public Collection<Pair<Operation, ResourceId>> subjects() {
        return subjects;
    }

    public Code code() {
        return code;
    }

    public String message() {
        return message;
    }

    /**
     * Creates SetResponse instance from request.
     *
     * @param request original request this response corresponds to
     * @param code response status code
     * @param message human readable error message for logging purpose.
     *        can be left empty string on OK response.
     * @return SetResponse instance
     */
    public static SetResponse response(SetRequest request,
                                       Code code,
                                       String message) {
        return new SetResponse(request.subjects(), code, checkNotNull(message));
    }

    /**
     * Creates successful SetResponce instance from request.
     *
     * @param request original request this response corresponds to
     * @return SetResponse instance
     */
    public static SetResponse ok(SetRequest request) {
        return new SetResponse(request.subjects(), Code.OK, "");
    }

    @Override
    public int hashCode() {
        return Objects.hash(subjects, code, message);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj instanceof SetResponse) {
            SetResponse that = (SetResponse) obj;
            return Objects.equals(this.subjects, that.subjects) &&
                    Objects.equals(this.code, that.code) &&
                    Objects.equals(this.message, that.message);
        }
        return false;
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(getClass())
                .add("code", code)
                .add("subjects", subjects)
                .add("message", message)
                .toString();
    }

}

redpajama_set_name: RedPajamaGithub


text:
// external
import { DatabaseLib } from 'ords-db';

// internal
import { IConformance, IRestResource } from './lib/schemas/conformance';

/**
 * String index of resources
 */
interface IImplemented {
    [key: string]: {
        restConformance: IRestResource
        resource: DatabaseLib.DatabaseResource;
    };
}

/**
 * Manage all valueset and resources including structure definitions that an implementation conforms too
 */
export class Conformance {
    /**
     * The raw content of the conformance
     */
    public conformance: IConformance;
    /**
     * General rest conformance for all resources
     */
    public generalResourceConformance: IRestResource;
    /**
     * General rest conformance for all resources
     */
    public generalRestConformance: any;    //DO SOMETHING ELSE HERE WITH MODEL
    /**
     * Avalable resources and constom conformance for these
     */
    private implemented: IImplemented = {};
    /**
     * Create empty conformance component
     */
    constructor() {

        // standard values for the conformance for all resources
        this.generalResourceConformance = {
            type: '*'
        };

        // set general rest conformance
        this.generalRestConformance = {};

        // standard value for conformance
        this.conformance = {
            acceptUnknown: 'no',
            contact: [],
            format: ['json'],
            profile: [],
            rest: [this.generalRestConformance]
        };
    }
    /**
     * Adds a resource to the stack of resources in an implementation
     * @param   {string}       Resource             the resource itself being added
     * @returns {void}
     */
    public addResource(resource: DatabaseLib.DatabaseResource, conformance: IRestResource): void {

        // init new holder for implemented resource and save reference to it
        this.implemented[resource.name] = {
            resource: resource,
            restConformance: conformance
        };
    }
    /**
     * Grap all known information about a resource type
     * @param   {string}       type     type of the resource
     */
    public getResource(type: string): DatabaseLib.DatabaseResource {

        // return content if it exists
        if (this.implemented[type] === undefined) {
            return undefined;
        } else {
            return this.implemented[type].resource;
        }
    }
    /**
     * Calculate the content of the conformance and return it back
     * @returns {IConformance}
     */
    public getConformance(): IConformance {

        // reset calculated rest
        this.conformance.rest = [];

        // MERGE GENERAL WITH SPECIFIC KEYS FOR RESOURCES

        // for all resources
        for (let type in this.implemented) {

            // check that it is not inherited
            if (this.implemented.hasOwnProperty(type)) {

                // push conformance into rest
                this.conformance.rest.push(this.implemented[type].restConformance);
            }
        }

        // Todo: Create an instance of the conformance resource and check if it fails.
        // implement general conformance too

        return this.conformance;
    }
}


text:
package us.kbase.auth2.lib;

/** Wrapper around credentials for a user, consisting of a hashed password and a salt used to
 * hash that password.
 *
 * Note that the password and salt are not copied in the constructor and therefore changes to the
 * input arrays will be reflected in the class. For this reason equals() and hashCode() are not
 * implemented.
 * @author gaprice@lbl.gov
 *
 */
public class PasswordHashAndSalt {

	final byte[] passwordHash;
	final byte[] salt;

	/** Create user credentials. Note this class can be mutated by manipulating the input arrays.
	 * @param passwordHash the hash of the a user's password.
	 * @param salt the salt used when hashing the password.
	 */
	public PasswordHashAndSalt(byte[] passwordHash, byte[] salt) {
		// what's the right # here? Have to rely on user to some extent
		if (passwordHash == null || passwordHash.length < 10) {
			throw new IllegalArgumentException("passwordHash missing or too small");
		}
		if (salt == null || salt.length < 2) {
			throw new IllegalArgumentException("salt missing or too small");
		}
		this.passwordHash = passwordHash;
		this.salt = salt;
	}

	/** Get the password hash. Note that mutating the returned array will mutate this class.
	 * @return the password hash.
	 */
	public byte[] getPasswordHash() {
		return passwordHash;
	}

	/** Get the salt. Note that mutating the returned array will mutate this class.
	 * @return the salt.
	 */
	public byte[] getSalt() {
		return salt;
	}

	/** Zero the contents of the hash and salt arrays. */
	public void clear() {
		Utils.clear(passwordHash);
		Utils.clear(salt);
	}

}


text:
Copyright, Michael P. Soulier, 2010-2021.

Note: ChangeLog produced with python's git-changelog

About Release 0.8.2:
====================

Bugfix release:

- / hardcoded making problems for windows users

About Release 0.8.1:
====================

Bugfix release:

- replace deprecated log.warn( with log.warning(
- fixing a security issue in breaking out of the tftproot
- setup with setuptools instead of distutils.
- allow overriding select timeout in listen
- fixing reading binary data from stdin on multiple platforms
- defaulting Makefile to python3 interpreter

About Release 0.8.0:
====================
This version introduces Python 3.X support.
And there was much rejoicing.

About Release 0.7.0:
====================
Various bugfixes and refactoring for improved logging.
Now requiring python 2.7+ and tightening syntax in
preparation for supporting python 3.

About Release 0.6.2:
====================
Maintenance release to fix a couple of reported issues.

About Release 0.6.1:
====================
Maintenance release to fix several reported problems, including a rollover
at 2^16 blocks, and some contributed work on dynamic file objects.

About Release 0.6.0:
====================
Maintenance update to fix several reported issues, including proper
retransmits on timeouts, and further expansion of unit tests.

About Release 0.5.1:
====================
Maintenance update to fix a bug in the server, overhaul the documentation for
the website, fix a typo in the unit tests, fix a failure to set default
blocksize, and a divide by zero error in speed calculations for very short
transfers.

Also, this release adds support for input/output in client as stdin/stdout

About Release 0.5.0:
====================
Complete rewrite of the state machine.
Now fully implements downloading and uploading.

About Release 0.4.6:
====================
Feature release to add the tsize option.
Thanks to Kuba Kończyk for the patch.

About Release 0.4.5:
====================
Bugfix release for compatibility issues on Win32, among other small issues.

About Release 0.4.4:
====================
Bugfix release for poor tolerance of unsupported options in the server.

About Release 0.4.3:
====================
Bugfix release for an issue with the server's detection of the end of the file
during a download.

About Release 0.4.2:
====================
Bugfix release for some small installation issues with earlier Python
releases.

About Release 0.4.1:
====================
Bugfix release to fix the installation path, with some restructuring into a
tftpy package from the single module used previously.

About Release 0.4:
==================
This release adds a TftpServer class with a sample implementation in bin.
The server uses a single thread with multiple handlers and a select() loop to
handle multiple clients simultaneously.

Only downloads are supported at this time.

About Release 0.3:
==================
This release fixes a major RFC 1350 compliance problem with the remote TID.

About Release 0.2:
==================
This release adds variable block sizes, and general option support,
implementing RFCs 2347 and 2348. This is accessible in the TftpClient class
via the options dict, or in the sample client via the --blocksize option.

About Release 0.1:
==================

This is an initial release in the spirit of "release early, release often".
Currently the sample client works, supporting RFC 1350. The server is not yet
implemented, and RFC 2347 and 2348 support (variable block sizes) is underway,
planned for 0.2.

About Tftpy:
============

Purpose:
--------
Tftpy is a TFTP library for the Python programming language. It includes
client and server classes, with sample implementations. Hooks are included for
easy inclusion in a UI for populating progress indicators. It supports RFCs
1350, 2347, 2348 and the tsize option from RFC 2349.

Dependencies:
-------------
Python 2.7+, hopefully. Let me know if it fails to work.

Trifles:
--------
Home page: http://tftpy.sf.net/
Project page: http://sourceforge.net/projects/tftpy/

License is the MIT License

See COPYING in this distribution.

Limitations:
------------
- Only 'octet' mode is supported.
- The only options supported are blksize and tsize.

Author:
=======
Michael P. Soulier <msoulier@digitaltorque.ca>


text:
'use strict';

const models = require('./index');

/**
 * HyperV replica Azure input to update replication protected item.
 *
 * @extends models['UpdateReplicationProtectedItemProviderInput']
 */
class HyperVReplicaAzureUpdateReplicationProtectedItemInput extends models['UpdateReplicationProtectedItemProviderInput'] {
  /**
   * Create a HyperVReplicaAzureUpdateReplicationProtectedItemInput.
   * @member {string} [recoveryAzureV1ResourceGroupId] The recovery Azure
   * resource group Id for classic deployment.
   * @member {string} [recoveryAzureV2ResourceGroupId] The recovery Azure
   * resource group Id for resource manager deployment.
   * @member {string} [useManagedDisks] A value indicating whether managed
   * disks should be used during failover.
   */
  constructor() {
    super();
  }

  /**
   * Defines the metadata of HyperVReplicaAzureUpdateReplicationProtectedItemInput
   *
   * @returns {object} metadata of HyperVReplicaAzureUpdateReplicationProtectedItemInput
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'HyperVReplicaAzure',
      type: {
        name: 'Composite',
        className: 'HyperVReplicaAzureUpdateReplicationProtectedItemInput',
        modelProperties: {
          instanceType: {
            required: true,
            serializedName: 'instanceType',
            type: {
              name: 'String'
            }
          },
          recoveryAzureV1ResourceGroupId: {
            required: false,
            serializedName: 'recoveryAzureV1ResourceGroupId',
            type: {
              name: 'String'
            }
          },
          recoveryAzureV2ResourceGroupId: {
            required: false,
            serializedName: 'recoveryAzureV2ResourceGroupId',
            type: {
              name: 'String'
            }
          },
          useManagedDisks: {
            required: false,
            serializedName: 'useManagedDisks',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = HyperVReplicaAzureUpdateReplicationProtectedItemInput;


text:
// Generated by Haxe 3.3.0
#ifndef INCLUDED_flixel_input_IFlxInput
#define INCLUDED_flixel_input_IFlxInput

#ifndef HXCPP_H
#include <hxcpp.h>
#endif

HX_DECLARE_CLASS2(flixel,input,IFlxInput)

namespace flixel{
namespace input{

class HXCPP_CLASS_ATTRIBUTES IFlxInput_obj {
	public:
		typedef hx::Object super;
		HX_DO_INTERFACE_RTTI;

		Bool (hx::Object :: *_hx_get_justReleased)();
		static inline Bool get_justReleased( ::Dynamic _hx_) {
			return (_hx_.mPtr->*( static_cast< ::flixel::input::IFlxInput_obj *>(_hx_.mPtr->_hx_getInterface(0x52baf533)))->_hx_get_justReleased)();
		}
		Bool (hx::Object :: *_hx_get_released)();
		static inline Bool get_released( ::Dynamic _hx_) {
			return (_hx_.mPtr->*( static_cast< ::flixel::input::IFlxInput_obj *>(_hx_.mPtr->_hx_getInterface(0x52baf533)))->_hx_get_released)();
		}
		Bool (hx::Object :: *_hx_get_pressed)();
		static inline Bool get_pressed( ::Dynamic _hx_) {
			return (_hx_.mPtr->*( static_cast< ::flixel::input::IFlxInput_obj *>(_hx_.mPtr->_hx_getInterface(0x52baf533)))->_hx_get_pressed)();
		}
		Bool (hx::Object :: *_hx_get_justPressed)();
		static inline Bool get_justPressed( ::Dynamic _hx_) {
			return (_hx_.mPtr->*( static_cast< ::flixel::input::IFlxInput_obj *>(_hx_.mPtr->_hx_getInterface(0x52baf533)))->_hx_get_justPressed)();
		}
};

} // end namespace flixel
} // end namespace input

#endif /* INCLUDED_flixel_input_IFlxInput */


text:
namespace Microsoft.Azure.Management.ServiceBus
{
    using System;
    using System.Collections.Generic;
    using System.Net.Http;
    using System.Threading;
    using System.Threading.Tasks;
    using Newtonsoft.Json;
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Models;

    /// <summary>
    /// Azure Service Bus client
    /// </summary>
    public partial interface IServiceBusManagementClient : IDisposable
    {
        /// <summary>
        /// The base URI of the service.
        /// </summary>
        Uri BaseUri { get; set; }

        /// <summary>
        /// Gets or sets json serialization settings.
        /// </summary>
        JsonSerializerSettings SerializationSettings { get; }

        /// <summary>
        /// Gets or sets json deserialization settings.
        /// </summary>
        JsonSerializerSettings DeserializationSettings { get; }

        /// <summary>
        /// Gets Azure subscription credentials.
        /// </summary>
        ServiceClientCredentials Credentials { get; }

        /// <summary>
        /// Subscription credentials which uniquely identify Microsoft Azure
        /// subscription. The subscription ID forms part of the URI for every
        /// service call.
        /// </summary>
        string SubscriptionId { get; set; }

        /// <summary>
        /// Client Api Version.
        /// </summary>
        string ApiVersion { get; }

        /// <summary>
        /// Gets or sets the preferred language for the response.
        /// </summary>
        string AcceptLanguage { get; set; }

        /// <summary>
        /// Gets or sets the retry timeout in seconds for Long Running
        /// Operations. Default value is 30.
        /// </summary>
        int? LongRunningOperationRetryTimeout { get; set; }

        /// <summary>
        /// When set to true a unique x-ms-client-request-id value is
        /// generated and included in each request. Default is true.
        /// </summary>
        bool? GenerateClientRequestId { get; set; }

        /// <summary>
        /// Gets the INamespacesOperations.
        /// </summary>
        INamespacesOperations Namespaces { get; }

        /// <summary>
        /// Gets the IQueuesOperations.
        /// </summary>
        IQueuesOperations Queues { get; }

        /// <summary>
        /// Gets the ITopicsOperations.
        /// </summary>
        ITopicsOperations Topics { get; }

        /// <summary>
        /// Gets the ISubscriptionsOperations.
        /// </summary>
        ISubscriptionsOperations Subscriptions { get; }

    }
}


text:
const canvas    = document.body.appendChild(document.createElement('canvas'))
const camera    = require('canvas-orbit-camera')(canvas)
const gl        = require('gl-context')(canvas, render)
const quat      = require('gl-matrix').quat
const Particles = require('gl-particles')
const Geom      = require('gl-geometry')
const eyevec    = require('eye-vector')
const icosphere = require('icosphere')
const Shader    = require('gl-shader')
const mat4      = require('gl-mat4')
const glslify   = require('glslify')

const start    = Date.now()
const registry = Geom(gl)
  .attr('position', icosphere(3))

const shaders = {
  registry: Shader(gl
    , glslify('./shaders/registry.vert')
    , glslify('./shaders/registry.frag')
  )
}

const particles = Particles(gl, {
  shape: [128, 256],
  logic: glslify('./shaders/particles.glsl'),
  vert: glslify('./shaders/particles.vert'),
  frag: glslify('./shaders/particles.frag')
})

particles.populate(function(u, v, data) {
  data[0] = (Math.random() - 0.5) * 0.1
  data[1] = (Math.random() - 0.5) * 0.1
  data[2] = (Math.random() - 0.5) * 0.1
  data[3] = 0
})

const model = new Float32Array(16)
const view  = new Float32Array(16)
const proj  = new Float32Array(16)
const eye   = new Float32Array(3)

camera.distance = 1.05

var regScale = 1

function render() {
  const width  = gl.drawingBufferWidth
  const height = gl.drawingBufferHeight

  mat4.identity(model)
  mat4.scale(model, model, [regScale, regScale, regScale])
  mat4.perspective(proj, Math.PI / 4, width / height, 0.01, 100)
  camera.view(view)
  camera.tick()
  eyevec(view, eye)

  camera.distance += (12 - camera.distance) * 0.005
  regScale = Math.max(0.05, regScale * 0.9955)
  quat.rotateZ(camera.rotation, camera.rotation, 0.001)
  quat.rotateY(camera.rotation, camera.rotation, 0.0025)

  gl.disable(gl.BLEND)
  gl.disable(gl.DEPTH_TEST)
  gl.disable(gl.CULL_FACE)
  particles.step(function(uniforms) {
    uniforms.time = (Date.now() - start) / 1000
  })

  gl.viewport(0, 0, width, height)
  gl.enable(gl.DEPTH_TEST)
  gl.enable(gl.CULL_FACE)
  gl.clearColor(0.135, 0.1, 0.2125, 1)
  gl.clear(gl.COLOR_BUFFER_BIT)

  drawRegistry()
  drawParticles()
}

window.addEventListener('resize'
  , require('canvas-fit')(canvas)
  , false
)

function drawRegistry() {
  registry.bind(shaders.registry)
  shaders.registry.uniforms.model = model
  shaders.registry.uniforms.view  = view
  shaders.registry.uniforms.proj  = proj
  shaders.registry.uniforms.eye   = eye
  registry.draw()
}

function drawParticles() {
  gl.depthMask(false)
  gl.enable(gl.DEPTH_TEST)
  gl.enable(gl.BLEND)
  gl.blendFunc(gl.ONE, gl.ONE)

  particles.draw(function(uniforms) {
    uniforms.proj = proj
    uniforms.view = view
    uniforms.eye  = eye
  })

  gl.depthMask(true)
  gl.disable(gl.BLEND)
}


text:
<?php
namespace Veles\Tests\View;

class View extends \Veles\View\View
{
	public static function unsetAdapter()
	{
		self::$adapter = null;
	}
}


text:
import { AsyncQueue, TimerId } from '../util/async_queue';
import * as log from '../util/log';
import { CancelablePromise } from '../util/promise';
const LOG_TAG = 'ExponentialBackoff';

/**
 * A helper for running delayed tasks following an exponential backoff curve
 * between attempts.
 *
 * Each delay is made up of a "base" delay which follows the exponential
 * backoff curve, and a +/- 50% "jitter" that is calculated and added to the
 * base delay. This prevents clients from accidentally synchronizing their
 * delays causing spikes of load to the backend.
 */
export class ExponentialBackoff {
  private currentBaseMs: number;
  private timerPromise: CancelablePromise<void> | null = null;
  /** The last backoff attempt, as epoch milliseconds. */
  private lastAttemptTime = Date.now();

  constructor(
    /**
     * The AsyncQueue to run backoff operations on.
     */
    private readonly queue: AsyncQueue,
    /**
     * The ID to use when scheduling backoff operations on the AsyncQueue.
     */
    private readonly timerId: TimerId,
    /**
     * The initial delay (used as the base delay on the first retry attempt).
     * Note that jitter will still be applied, so the actual delay could be as
     * little as 0.5*initialDelayMs.
     */
    private readonly initialDelayMs: number,
    /**
     * The multiplier to use to determine the extended base delay after each
     * attempt.
     */
    private readonly backoffFactor: number,
    /**
     * The maximum base delay after which no further backoff is performed.
     * Note that jitter will still be applied, so the actual delay could be as
     * much as 1.5*maxDelayMs.
     */
    private readonly maxDelayMs: number
  ) {
    this.reset();
  }

  /**
   * Resets the backoff delay.
   *
   * The very next backoffAndWait() will have no delay. If it is called again
   * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and
   * subsequent ones will increase according to the backoffFactor.
   */
  reset(): void {
    this.currentBaseMs = 0;
  }

  /**
   * Resets the backoff delay to the maximum delay (e.g. for use after a
   * RESOURCE_EXHAUSTED error).
   */
  resetToMax(): void {
    this.currentBaseMs = this.maxDelayMs;
  }

  /**
   * Returns a promise that resolves after currentDelayMs, and increases the
   * delay for any subsequent attempts. If there was a pending backoff operation
   * already, it will be canceled.
   */
  backoffAndRun(op: () => Promise<void>): void {
    // Cancel any pending backoff operation.
    this.cancel();

    // First schedule using the current base (which may be 0 and should be
    // honored as such).
    const desiredDelayWithJitterMs = Math.floor(
      this.currentBaseMs + this.jitterDelayMs()
    );

    // Guard against lastAttemptTime being in the future due to a clock change.
    const delaySoFarMs = Math.max(0, Date.now() - this.lastAttemptTime);

    // Guard against the backoff delay already being past.
    const remainingDelayMs = Math.max(
      0,
      desiredDelayWithJitterMs - delaySoFarMs
    );

    if (this.currentBaseMs > 0) {
      log.debug(
        LOG_TAG,
        `Backing off for ${remainingDelayMs} ms ` +
          `(base delay: ${this.currentBaseMs} ms, ` +
          `delay with jitter: ${desiredDelayWithJitterMs} ms, ` +
          `last attempt: ${delaySoFarMs} ms ago)`
      );
    }

    this.timerPromise = this.queue.enqueueAfterDelay(
      this.timerId,
      remainingDelayMs,
      () => {
        this.lastAttemptTime = Date.now();
        return op();
      }
    );

    // Apply backoff factor to determine next delay and ensure it is within
    // bounds.
    this.currentBaseMs *= this.backoffFactor;
    if (this.currentBaseMs < this.initialDelayMs) {
      this.currentBaseMs = this.initialDelayMs;
    }
    if (this.currentBaseMs > this.maxDelayMs) {
      this.currentBaseMs = this.maxDelayMs;
    }
  }

  cancel(): void {
    if (this.timerPromise !== null) {
      this.timerPromise.cancel();
      this.timerPromise = null;
    }
  }

  /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */
  private jitterDelayMs(): number {
    return (Math.random() - 0.5) * this.currentBaseMs;
  }
}


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>React Redux React-Router with Webpack Boilerplate</title>
    <meta name="description" content="React Redux React-Router with Webpack Boilerplate">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">


text:
"""
This module tests the code listings used in the documentation.
"""

import sys

from twisted.python.filepath import FilePath
from twisted.trial.unittest import SkipTest, TestCase

from nevow._widget_plugin import ElementRenderingLivePage
from nevow.testutil import renderLivePage, JavaScriptTestCase
from nevow.athena import jsDeps, expose

from nevow import plugins

class ExampleTestBase(object):
    """
    This is a mixin which adds an example to the path, tests it, and then
    removes it from the path and unimports the modules which the test loaded.
    Test cases which test example code and documentation listings should use
    this.

    This is done this way so that examples can live in isolated path entries,
    next to the documentation, replete with their own plugin packages and
    whatever other metadata they need.  Also, example code is a rare instance
    of it being valid to have multiple versions of the same code in the
    repository at once, rather than relying on version control, because
    documentation will often show the progression of a single piece of code as
    features are added to it, and we want to test each one.
    """

    examplePath = None

    def setUp(self):
        """
        Add our example directory to the path and record which modules are
        currently loaded.
        """
        self.originalPath = sys.path[:]
        self.originalModules = sys.modules.copy()
        here = FilePath(__file__).parent().parent().parent()
        for childName in self.examplePath:
            here = here.child(childName)
        if not here.exists():
            raise SkipTest("Examples (%s) not found - cannot test" % (here.path,))
        sys.path.append(here.path)
        # This stuff is pretty horrible; we need to turn off JS caching for the
        # duration of this test (this flag will be set back to True by the
        # plugin-loading itself, so no need to clean it up) because the
        # previously-loaded list of plugins is going to be invalid.
        jsDeps._loadPlugins = True
        # Even more horrible!  nevow.plugins.__path__ needs to be recomputed
        # each time for the new value of sys.path.
        reload(plugins)

    def tearDown(self):
        """
        Remove the example directory from the path and remove all modules loaded by
        the test from sys.modules.
        """
        sys.modules.clear()
        sys.modules.update(self.originalModules)
        sys.path[:] = self.originalPath
        reload(plugins)

class ExampleJavaScriptTestCase(JavaScriptTestCase):
    """
    Since JavaScriptTestCase does not use setUp and tearDown, we can't use
    simple inheritance to invoke the functionality in ExampleTestBase; so,
    instead, this class composes JavaScriptTestCase with a ExampleTestBase.
    """
    def run(self, result):
        """
        Wrap L{JavaScriptTestCase.run} to change and restore the plugin environment
        on each test run.
        """
        base = ExampleTestBase()
        base.examplePath = self.examplePath
        try:
            base.setUp()
        except SkipTest, e:
            result.startTest(self)
            result.addSkip(self, str(e))
            result.stopTest(self)
        else:
            try:
                return JavaScriptTestCase.run(self, result)
            finally:
                base.tearDown()

def chatListing(partname):
    """
    Return a list of strings that represents a path from the root of the Nevow
    source package which contains a potential PYTHONPATH entry with some
    listing code in it, based on which part of the chat tutorial it came from.
    """
    return ['doc', 'howto', 'chattutorial', 'part'+partname, 'listings']

class Part00Tests(ExampleJavaScriptTestCase):
    """
    Refer to JavaScript unit tests for section 01 of the tutorial.
    """

    examplePath = chatListing('00')

    def test_part00(self):
        """
        Test method pointing to part 00 of the tutorial.
        """
        return 'Nevow.Test.TestHowtoListing00'

class Echo00(ExampleTestBase, TestCase):
    """
    These tests will make sure that the very basic 'echobox' portion of the
    tutorial works.
    """
    examplePath = chatListing('00')

    def test_renderEcho(self):
        """
        Rendering the echo example element should produce a very simple text area.
        """
        from echothing.echobox import EchoElement
        TEXT = 'Echo Element'
        eb = EchoElement()
        erlp = ElementRenderingLivePage(eb)
        def checkContent(result):
            # The "liveElement" renderer inserts this, let's look for it to
            # make sure it rendered live:
            self.assertIn('id="athena:'+str(eb._athenaID)+'"', result)
            self.assertIn('athena:class="EchoThing.EchoWidget"', result)
            self.assertIn(TEXT, result)
        return renderLivePage(erlp).addCallback(checkContent)

    def test_echoTellsClient(self):
        """
        When 'hear' is called on a ChatterElement, it should inform its client of what
        was said and by whom.
        """
        from echothing.echobox import EchoElement
        eb = EchoElement()
        echoed = []
        eb.callRemote = lambda method, message: echoed.append((method, message))
        eb.say(u'HELLO... Hello... hello...')
        self.assertEquals(echoed, [('addText', u'HELLO... Hello... hello...')])

class Part01Tests(ExampleJavaScriptTestCase):
    """
    Refer to JavaScript unit tests for section 01 of the tutorial.
    """

    examplePath = chatListing('01')

    def test_part01(self):
        """
        Test method pointing to part 01 of the tutorial.
        """
        return 'Nevow.Test.TestHowtoListing01'

class RenderAndChat01(ExampleTestBase, TestCase):
    """
    These tests make sure that the listing for part 01 of the chatterbox
    tutorial will import, render, and allow users to chat with each other.
    """

    examplePath = chatListing('01')

    def test_basicRendering(self):
        """
        Rendering the example element should produce a chat area.
        """
        from chatthing.chatterbox import ChatterElement, ChatRoom
        PROMPT = 'Choose your username: '
        cb = ChatterElement(ChatRoom())
        erlp = ElementRenderingLivePage(cb)
        def checkContent(result):
            # The "liveElement" renderer inserts this, let's look for it to
            # make sure it rendered live:
            self.assertIn('id="athena:'+str(cb._athenaID)+'"', result)
            self.assertIn('athena:class="ChatThing.ChatterWidget"', result)
            self.assertIn(PROMPT, result)
        return renderLivePage(erlp).addCallback(checkContent)

    def test_username(self):
        """
        When a user sets their username in the chat room, it should set an
        attribute on their ChatterElement instance.
        """
        from chatthing.chatterbox import ChatterElement, ChatRoom
        cb = ChatterElement(ChatRoom())
        setUsername = expose.get(cb, 'setUsername')
        setUsername(u'jethro')
        self.assertIdentical(u'jethro', cb.username)

    def test_loginThenWall(self):
        """
        When a user logs in the 'wall' method on their ChatterElement gets called,
        notifiying everyone in the room that they have entered.
        """
        from chatthing.chatterbox import ChatRoom
        jethroHeard = []
        cletusHeard = []
        cr = ChatRoom()
        user1 = cr.makeChatter()
        user1.wall = lambda msg: jethroHeard.append(msg)
        user1.setUsername(u'jethro')
        user2 = cr.makeChatter()
        user2.wall = lambda msg: cletusHeard.append(msg)
        user2.setUsername(u'cletus')
        self.assertEquals(jethroHeard,
                          [u' * user jethro has joined the room',
                           u' * user cletus has joined the room'])
        self.assertEquals(cletusHeard, [u' * user cletus has joined the room'])

    def test_sayThenHear(self):
        """
        When a user calls the 'say' method on their ChatterElement, everyone (including
        them) should 'hear' it.
        """
        from chatthing.chatterbox import ChatRoom
        cr = ChatRoom()
        user1 = cr.makeChatter()
        user1.wall = lambda msg: msg
        user1.setUsername(u'jethro')
        user2 = cr.makeChatter()
        user2.wall = lambda msg: msg
        user2.setUsername(u'cletus')
        jethroHeard = []
        cletusHeard = []
        user1.hear = lambda who, what: jethroHeard.append((who,what))
        user2.hear = lambda who, what: cletusHeard.append((who,what))
        say = expose.get(user1, 'say')
        say(u'Hey, Cletus!')
        self.assertEquals(jethroHeard, cletusHeard)
        self.assertEquals(cletusHeard, [(u'jethro', u'Hey, Cletus!')])

    def test_wallTellsClient(self):
        """
        When 'wall' is called on a ChatterElement, it should inform its client of
        the message.
        """
        from chatthing.chatterbox import ChatRoom
        cb = ChatRoom().makeChatter()
        heard = []
        cb.callRemote = lambda method, msg: heard.append((method, msg))
        cb.wall(u'Message for everyone...')
        self.assertEquals(heard, [('displayMessage', u'Message for everyone...')])

    def test_hearTellsClient(self):
        """
        When 'hear' is called on a ChatterElement, it should inform its client of what
        was said and by whom.
        """
        from chatthing.chatterbox import ChatRoom
        cb = ChatRoom().makeChatter()
        heard = []
        cb.callRemote = lambda method, who, what: heard.append((method, who, what))
        cb.hear(u'Hello', u'Chat')
        self.assertEquals(heard, [('displayUserMessage', u'Hello', u'Chat')])


text:
layout: post
title: Created our site with Dr. Jekyll and Mr. Hyde
date: 2015-11-28 22:07:37
categories: jekyll update
---

Strange case of Dr. [Jekyll]({% post_url 2012-02-06-whats-jekyll %}) and Mr. [Hyde]({% post_url 2013-12-28-introducing-hyde %}).

[https://github.com/hiqdev/hiqdev.github.io](https://github.com/hiqdev/hiqdev.github.io)

Check out the [Jekyll docs][jekyll] for more info on how to get the most out of Jekyll. File all bugs/feature requests at [Jekyll's GitHub repo][jekyll-gh]. If you have questions, you can ask them on [Jekyll's dedicated Help repository][jekyll-help].

[jekyll]:      http://jekyllrb.com
[jekyll-gh]:   https://github.com/jekyll/jekyll
[jekyll-help]: https://github.com/jekyll/jekyll-help


text:
namespace ApplicationGateway.Models
{
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// Troubleshooting information gained from specified resource.
    /// </summary>
    public partial class TroubleshootingResult
    {
        /// <summary>
        /// Initializes a new instance of the TroubleshootingResult class.
        /// </summary>
        public TroubleshootingResult()
        {
          CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the TroubleshootingResult class.
        /// </summary>
        /// <param name="startTime">The start time of the
        /// troubleshooting.</param>
        /// <param name="endTime">The end time of the troubleshooting.</param>
        /// <param name="code">The result code of the troubleshooting.</param>
        /// <param name="results">Information from troubleshooting.</param>
        public TroubleshootingResult(System.DateTime? startTime = default(System.DateTime?), System.DateTime? endTime = default(System.DateTime?), string code = default(string), IList<TroubleshootingDetails> results = default(IList<TroubleshootingDetails>))
        {
            StartTime = startTime;
            EndTime = endTime;
            Code = code;
            Results = results;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets the start time of the troubleshooting.
        /// </summary>
        [JsonProperty(PropertyName = "startTime")]
        public System.DateTime? StartTime { get; set; }

        /// <summary>
        /// Gets or sets the end time of the troubleshooting.
        /// </summary>
        [JsonProperty(PropertyName = "endTime")]
        public System.DateTime? EndTime { get; set; }

        /// <summary>
        /// Gets or sets the result code of the troubleshooting.
        /// </summary>
        [JsonProperty(PropertyName = "code")]
        public string Code { get; set; }

        /// <summary>
        /// Gets or sets information from troubleshooting.
        /// </summary>
        [JsonProperty(PropertyName = "results")]
        public IList<TroubleshootingDetails> Results { get; set; }

    }
}