text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.

#nullable enable

using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;

using IronPython.Runtime.Exceptions;

namespace IronPython.Runtime {
    ///
    /// Equivalent functionality of CPython's Buffer Protocol.
    ///
    public interface IBufferProtocol {
        IPythonBuffer GetBuffer(BufferFlags flags = BufferFlags.Simple);
    }

    ///
    /// Used to specify what kind of buffer the consumer is prepared to deal with
    /// and therefore what kind of buffer the exporter is allowed to return.
    ///
    /// <seealso href="https://docs.python.org/3/c-api/buffer.html#buffer-request-types"/>
    [Flags]
    public enum BufferFlags {
        ///
        /// The buffer must be writable. The consumer cannot handle read-only buffers.
        ///
        Writable      = 0x0001,

        ///
        /// The consumer expects the item format to be reported and is prepared to deal with items that are more complex than a byte.
        ///
        /// <remarks>
        /// If format is requested, the consumer must also indicate preparedness to handle shape (<see cref="ND"/> flag set).
        /// </remarks>
        Format        = 0x0004,

        ///
        /// An N-dimensional array, 0 <= N <= 64. The dimensions are reported as shape.
        ///
        ND            = 0x0008,

        ///
        /// An N-dimensional array with strides, so data may not be memory contiguous.
        /// However, it will fit in a contiguous memory range.
        ///
        Strides       = 0x0010 | ND,

        ///
        /// An N-dimensional array with strides, so it may not be memory contiguous.
        /// The last dimension is contiguous.
        ///
        CContiguous   = 0x0020 | Strides,

        ///
        /// An N-dimensional array with strides, so it may not be memory contiguous.
        /// The first dimension is contiguous.
        ///
        FContiguous   = 0x0040 | Strides,

        ///
        /// The client is prepared to deal with either <see cref="CContiguous"/> or <see cref="FContiguous"/>.
        ///
        AnyContiguous = 0x0080 | Strides,

        ///
        /// An N-dimensional array that has a complex structure, where higher dimensions
        /// may contains pointers to memory blocks holding lower dimensions.
        ///
        Indirect      = 0x0100 | Strides,

        #region Flag combinations for common requests

        ///
        /// Unformatted (i.e. byte-oriented) read-only blob with no structure.
        ///
        Simple    = 0,

        ///
        /// Contiguous writable buffer of any dimension.
        ///
        Contig    = ND | Writable,

        ///
        /// Contiguous buffer of any dimension.
        ///
        ContigRO  = ND,

        ///
        /// Writable byte buffer of any dimension, possibly non-contiguous, but with no embedded pointers.
        ///
        Strided   = Strides | Writable,

        ///
        /// Byte buffer of any dimension, possibly non-contiguous, but with no embedded pointers.
        ///
        StridedRO = Strides,

        ///
        /// Writable buffer of any dimension, possibly non-contiguous, but with no embedded pointers.
        /// Elements can be any struct type.
        ///
        Records   = Strides | Writable | Format,

        ///
        /// Buffer of any dimension, possibly non-contiguous, but with no embedded pointers.
        /// Elements can be any struct type.
        ///
        RecordsRO = Strides | Format,

        Full      = Indirect | Writable | Format,
        FullRO    = Indirect | Format,

        #endregion
    }

    internal static class BufferProtocolExtensions {
        internal static IPythonBuffer? GetBufferNoThrow(this IBufferProtocol bufferProtocol, BufferFlags flags = BufferFlags.Simple) {
            try {
                return bufferProtocol.GetBuffer(flags);
            } catch (BufferException) {
                return null;
            }
        }
    }

    ///
    /// Provides low-level read-write access to byte data of the underlying object.
    ///
    /// <remarks>
    /// <list type="number">
    /// <item>
    /// The buffer should be disposed after usage. Failing to dispose a buffer
    /// instance will render the underlying object permanently locked in an export state.
    /// </item>
    /// <item>
    /// <see cref="IDisposable.Dispose()"/> can be called multiple times (subsequent calls being no-op).
    /// In multi-thread use scenarios, the client has to ensure that the call to Dispose()
    /// happens only after all calls to other methods are terminated.
    /// </item>
    /// <item>
    /// The buffer provides low-level byte access to the exported data
    /// that may not be synchronized for multiple read-write threads
    /// even if the exporter itself is a synchronized object.
    /// The client can ensure proper synchronization by locking on <see cref="IPythonBuffer.Object"/>.
    /// </item>
    /// <item>
    /// The buffer can be pinned (fixed) by obtaining a memory handle by calling method <see cref="Pin"/>.
    /// The client should make sure that all obtained memory handles are disposed before the buffer itself is disposed.
    /// </item>
    /// </list>
    /// </remarks>
    public interface IPythonBuffer : IDisposable {
        ///
        /// A reference to the exporting object.
        ///
        object Object { get; }

        ///
        /// Indicates whether only read access is permitted.
        /// For writable buffers this is false.
        ///
        bool IsReadOnly { get; }

        ///
        /// Read-only access to binary buffer data. Apart from indirect buffers, all of buffer data lies within the span,
        /// although if strides are used, not all of span data have to be buffer data.
        ///
        ReadOnlySpan<byte> AsReadOnlySpan();

        ///
        /// Writable access to the same data as provided by <see cref="AsReadOnlySpan"/>.
        /// May only be used if <see cref="IsReadOnly"/> is false.
        ///
        /// <exception cref="InvalidOperationException">
        /// Thrown if accessed on a read-only buffer (<see cref="IsReadOnly"/> is true).
        /// </exception>
        Span<byte> AsSpan();

        ///
        /// Creates a handle for the buffer memory exposed through <see cref="AsReadOnlySpan"/>.
        /// If the buffer is backed by managed memory, the garbage collector will not move the memory
        /// until the returned handle is disposed. This enables you to retrieve and use the buffers's address.
        ///
        /// <returns>A handle for the <see cref="IPythonBuffer"/> object.</returns>
        /// <exception cref="BufferException">
        /// Buffers backed by memory on the stack cannot be pinned.
        /// </exception>
        MemoryHandle Pin();

        ///
        /// Offset (in bytes) of the first logical element in the buffer with respect to the beginning of
        /// the byte span. For non-strided buffers it is always 0.
        ///
        int Offset { get; }

        ///
        /// String describing the format of a single element, using element codes as defined in the 'struct' module.
        /// Value null implies unformatted, byte-oriented data access.
        ///
        /// <seealso href="https://docs.python.org/3/c-api/buffer.html#c.Py_buffer.format"/>
        /// <seealso href="https://docs.python.org/3/library/struct.html#format-strings"/>
        string? Format { get; }

        ///
        /// Total number of elements in the buffer.
        /// Equal to a product of all dimension lengths as defined by <see cref="Shape"/>, if Shape is not null.
        ///
        /// <remarks>
        /// Can be used to calculate number of bytes of data in the buffer (len).
        /// (equal to ItemCount * ItemSize).
        /// </remarks>
        /// <seealso href="https://docs.python.org/3/c-api/buffer.html#c.Py_buffer.len"/>
        int ItemCount { get; }

        ///
        /// Size in bytes of one element. It matches the element <see cref="Format"/>.
        /// If Format is null (indicating unformatted access), it matches the original element type.
        ///
        /// <seealso href="https://docs.python.org/3/c-api/buffer.html#c.Py_buffer.itemsize"/>
        int ItemSize { get; }

        ///
        /// Number of dimensions of the buffer (e.g. array rank).
        /// 0 for single values, 1 for simple arrays, 2 and more for ND-arrays.
        /// Maximum number of dimensions is 64.
        ///
        /// <seealso href="https://docs.python.org/3/c-api/buffer.html#c.Py_buffer.ndim"/>
        int NumOfDims { get; }

        ///
        /// A list of number of elements in each dimension.
        /// If null, it implies a scalar or a simple 1-dimensional array.
        ///
        /// <seealso href="https://docs.python.org/3/c-api/buffer.html#c.Py_buffer.shape"/>
        IReadOnlyList<int>? Shape { get; }

        ///
        /// For each dimension, a value indicating how many bytes to skip to get to the next element.
        /// If null, it implies a scalar or a contiguous n-dimensional array.
        ///
        /// <seealso href="https://docs.python.org/3/c-api/buffer.html#c.Py_buffer.strides"/>
        IReadOnlyList<int>? Strides { get; }

        ///
        /// For each dimension, it provides information how to find the start of data in its subdimension.
        /// If null, it implies that all buffer data lies within the span provided by <see cref="AsReadOnlySpan()"/>
        /// and can be accessed by simple offset calculations (no pointer dereferencing).
        ///
        /// <seealso href="https://docs.python.org/3/c-api/buffer.html#c.Py_buffer.suboffsets"/>
        IReadOnlyList<int>? SubOffsets { get; }
    }

    public static class PythonBufferExtensions {
        ///
        /// Number of bytes of data in the buffer (len).
        ///
        /// <seealso href="https://docs.python.org/3/c-api/buffer.html#c.Py_buffer.len"/>
        public static int NumBytes(this IPythonBuffer buffer)
            => buffer.ItemCount * buffer.ItemSize;

        public static BufferBytesEnumerator EnumerateBytes(this IPythonBuffer buffer)
            => new BufferBytesEnumerator(buffer);

        public static BufferEnumerator EnumerateItemData(this IPythonBuffer buffer)
            => new BufferEnumerator(buffer, chunkSize: buffer.ItemSize);

        ///
        /// Checks if the data in buffer uses a contiguous memory block. If the buffer uses more than one dimension,
        /// the data is organized according to the C multi-dimensional array layout.
        ///
        /// <remarks>
        /// This does not directly correspond to the <see cref="BufferFlags.CContiguous"/> flag.
        /// Buffers requested with purely such flag are only guaranteed to have contiguous data in the lowest dimension.
        /// Flag <see cref="BufferFlags.Contig"/>, on the other hand, does guarante a fully C-contiguous data block.
        /// </remarks>
        public static bool IsCContiguous(this IPythonBuffer buffer) {
            Debug.Assert(buffer.Strides != null || buffer.Offset == 0);
            return buffer.Strides == null;
        }

        public static byte[] ToArray(this IPythonBuffer buffer) {
            if (buffer.IsCContiguous()) {
                return buffer.AsReadOnlySpan().ToArray();
            } else {
                var bytes = new byte[buffer.NumBytes()];
                int i = 0;
                foreach (byte b in buffer.EnumerateBytes()) {
                    bytes[i++] = b;
                }
                return bytes;
            }
        }

        public static void CopyTo(this IPythonBuffer buffer, Span<byte> dest) {
            if (buffer.IsCContiguous()) {
                buffer.AsReadOnlySpan().CopyTo(dest);
            } else {
                int i = 0;
                foreach (byte b in buffer.EnumerateBytes()) {
                    dest[i++] = b;
                }
            }
        }

        internal static byte[]? AsUnsafeArray(this IPythonBuffer buffer) {
            if (!buffer.IsCContiguous())
                return null;

            if (buffer.Object is Bytes b)
                return b.UnsafeByteArray;

            if (buffer.Object is Memory<byte> mem) {
                if (MemoryMarshal.TryGetArray(mem, out ArraySegment<byte> seg) && seg.Array != null && seg.Offset == 0 && seg.Count == seg.Array.Length)
                    return seg.Array;
            } else if (buffer.Object is ReadOnlyMemory<byte> rom) {
                if (MemoryMarshal.TryGetArray(rom, out ArraySegment<byte> seg) && seg.Array != null && seg.Offset == 0 && seg.Count == seg.Array.Length)
                    return seg.Array;
            }

            return null;
        }
    }

    public ref struct BufferBytesEnumerator {
        private readonly BufferEnumerator _enumerator;

        public BufferBytesEnumerator(IPythonBuffer buffer)
            => _enumerator = new BufferEnumerator(buffer, chunkSize: 1);

        public byte Current => _enumerator.Current[0];
        public bool MoveNext() => _enumerator.MoveNext();
        public void Dispose() => _enumerator.Dispose();

        public BufferBytesEnumerator GetEnumerator() => this;
    }

    public ref struct BufferEnumerator {
        private readonly int _chunksize;
        private readonly ReadOnlySpan<byte> _span;
        private readonly IEnumerator<int> _offsets;

        public BufferEnumerator(IPythonBuffer buffer, int chunkSize) {
            if (buffer.SubOffsets != null)
                throw new NotImplementedException("buffers with suboffsets are not supported");

            _chunksize = chunkSize;
            _span = buffer.AsReadOnlySpan();
            _offsets = EnumerateDimension(buffer, buffer.Offset, chunkSize, 0).GetEnumerator();
        }

        public ReadOnlySpan<byte> Current => _span.Slice(_offsets.Current, _chunksize);
        public bool MoveNext() => _offsets.MoveNext();
        public void Dispose() => _offsets.Dispose();

        public BufferEnumerator GetEnumerator() => this;

        private static IEnumerable<int> EnumerateDimension(IPythonBuffer buffer, int ofs, int step, int dim) {
            IReadOnlyList<int>? shape = buffer.Shape;
            IReadOnlyList<int>? strides = buffer.Strides;

            if (shape == null || strides == null) {
                // simple C-contiguous case
                Debug.Assert(buffer.Offset == 0);
                int len = buffer.NumBytes();
                for (int i = 0; i < len; i += step) {
                    yield return i;
                }
            } else if (dim >= shape.Count) {
                // iterate individual element (scalar)
                for (int i = 0; i < buffer.ItemSize; i += step) {
                    yield return ofs + i;
                }
            } else {
                for (int i = 0; i < shape[dim]; i++) {
                    // iterate all bytes from a subdimension
                    foreach (int j in EnumerateDimension(buffer, ofs, step, dim + 1)) {
                        yield return j;
                    }
                    ofs += strides[dim];
                }
            }
        }
    }
}


text:
import unittest

from girder.api import rest

class RestUtilTestCase(unittest.TestCase):
    """
    This performs unit-level testing of REST-related utilities.
    """

    def testBoolParam(self):
        resource = rest.Resource()
        expect = {
            'TRUE': True,
            ' true  ': True,
            'Yes': True,
            '1': True,
            'ON': True,
            'false': False,
            'False': False,
            'OFF': False,
            '': False,
            ' ': False,
            False: False,
            True: True
        }

        for input, output in expect.items():
            params = {
                'some_key': input
            }
            self.assertEqual(resource.boolParam('some_key', params), output)

        self.assertEqual(resource.boolParam('some_key', {}, default='x'), 'x')

redpajama_set_name: RedPajamaGithub


text:
var configForAdmin = { database: 'sequelize_test', username: 'readonly', password: 'readonly' };
module.exports = require('../models/index')(configForAdmin);


text:
namespace libwebm {

bool VideoFrame::Buffer::Init(std::size_t new_length) {
  capacity = 0;
  length = 0;
  data.reset(new std::uint8_t[new_length]);

  if (data.get() == nullptr) {
    fprintf(stderr, "VideoFrame: Out of memory.");
    return false;
  }

  capacity = new_length;
  length = 0;
  return true;
}

bool VideoFrame::Init(std::size_t length) { return buffer_.Init(length); }

bool VideoFrame::Init(std::size_t length, std::int64_t nano_pts, Codec codec) {
  nanosecond_pts_ = nano_pts;
  codec_ = codec;
  return Init(length);
}

bool VideoFrame::SetBufferLength(std::size_t length) {
  if (length > buffer_.capacity || buffer_.data.get() == nullptr)
    return false;

  buffer_.length = length;
  return true;
}

}  // namespace libwebm


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

package main

import (
	"os"
	"path/filepath"
	"regexp"
	"strings"
	"sync"
	"time"

	"github.com/minio/mc/pkg/console"
	"github.com/minio/mc/pkg/quick"
	"github.com/minio/minio/pkg/iodine"
)

type sessionV1 struct {
	Version     string          `json:"version"`
	Started     time.Time       `json:"started"`
	CommandType string          `json:"command-type"`
	SessionID   string          `json:"session-id"`
	URLs        []string        `json:"args"`
	Files       map[string]bool `json:"files"`

	Lock *sync.Mutex `json:"-"`
}

func (s sessionV1) String() string {
	message := console.Time("[%s] ", s.Started.Local().Format(printDate))
	message = message + console.SessionID("%s", s.SessionID)
	message = message + console.Command(" [%s %s]", s.CommandType, strings.Join(s.URLs, " "))
	return message
}

// loadSession - reads session file if exists and re-initiates internal variables
func loadSessionV1(sid string) (*sessionV1, error) {
	if !isSessionDirExists() {
		return nil, NewIodine(iodine.New(errInvalidArgument{}, nil))
	}
	sessionFile := getSessionFileV1(sid)

	_, err := os.Stat(sessionFile)
	if err != nil {
		return nil, NewIodine(iodine.New(err, nil))
	}
	s := new(sessionV1)
	s.Version = "1.0.0"
	// map of command and files copied
	s.URLs = nil
	s.Lock = new(sync.Mutex)
	s.Files = make(map[string]bool)
	qs, err := quick.New(s)
	if err != nil {
		return nil, NewIodine(iodine.New(err, nil))
	}
	err = qs.Load(sessionFile)
	if err != nil {
		return nil, NewIodine(iodine.New(err, nil))
	}
	return qs.Data().(*sessionV1), nil
}

func getSessionIDsV1() (sids []string) {
	sessionList, err := filepath.Glob(getSessionDir() + "/*")
	if err != nil {
		console.Fatalf("Unable to list session directory '%s', %s", getSessionDir(), NewIodine(iodine.New(err, nil)))
	}

	for _, path := range sessionList {
		sidReg := regexp.MustCompile("^[a-zA-Z]{8}$")
		sid := filepath.Base(path)
		if sidReg.Match([]byte(sid)) {
			sessionV1, err := loadSessionV1(sid)
			if err != nil {
				console.Fatalf("Unable to load session '%s', %s", sid, NewIodine(iodine.New(err, nil)))
			}
			if sessionV1.Version != "1.0.0" {
				continue
			}
			sids = append(sids, sid)
		}
	}
	return sids
}

func getSessionFileV1(sid string) string {
	return filepath.Join(getSessionDir(), sid)
}


text:
module IsenseColorpicker
  class Engine < ::Rails::Engine
    initializer 'isense_colorpicker.load_static_assets' do |app|
      app.middleware.use ::ActionDispatch::Static, "#{root}/vendor"
    end
  end
end


text:
#pragma once
#include <aws/route53domains/Route53Domains_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace Route53Domains
{
namespace Model
{

  class AWS_ROUTE53DOMAINS_API DomainSuggestion
  {
  public:
    DomainSuggestion();
    DomainSuggestion(const Aws::Utils::Json::JsonValue& jsonValue);
    DomainSuggestion& operator=(const Aws::Utils::Json::JsonValue& jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    inline const Aws::String& GetDomainName() const{ return m_domainName; }

    inline void SetDomainName(const Aws::String& value) { m_domainNameHasBeenSet = true; m_domainName = value; }

    inline void SetDomainName(Aws::String&& value) { m_domainNameHasBeenSet = true; m_domainName = value; }

    inline void SetDomainName(const char* value) { m_domainNameHasBeenSet = true; m_domainName.assign(value); }

    inline DomainSuggestion& WithDomainName(const Aws::String& value) { SetDomainName(value); return *this;}

    inline DomainSuggestion& WithDomainName(Aws::String&& value) { SetDomainName(value); return *this;}

    inline DomainSuggestion& WithDomainName(const char* value) { SetDomainName(value); return *this;}

    inline const Aws::String& GetAvailability() const{ return m_availability; }

    inline void SetAvailability(const Aws::String& value) { m_availabilityHasBeenSet = true; m_availability = value; }

    inline void SetAvailability(Aws::String&& value) { m_availabilityHasBeenSet = true; m_availability = value; }

    inline void SetAvailability(const char* value) { m_availabilityHasBeenSet = true; m_availability.assign(value); }

    inline DomainSuggestion& WithAvailability(const Aws::String& value) { SetAvailability(value); return *this;}

    inline DomainSuggestion& WithAvailability(Aws::String&& value) { SetAvailability(value); return *this;}

    inline DomainSuggestion& WithAvailability(const char* value) { SetAvailability(value); return *this;}

  private:
    Aws::String m_domainName;
    bool m_domainNameHasBeenSet;
    Aws::String m_availability;
    bool m_availabilityHasBeenSet;
  };

} // namespace Model
} // namespace Route53Domains
} // namespace Aws


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>TorrentMetadata</title>
<meta name="date" content="2016-01-25">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

TorrentMetadata

Classes

TorrentFile

TorrentFile.TFile

TorrentFileTest


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

import java.io.Serializable;

/**
 * This class represents tells the fuzzing library that no further values will be requested. After closing a request,
 * no further values can be requested for the closed request.
 *
 * @author Martin Schneider (martin.schneider@fokus.fraunhofer.de)
 *
 */
public interface CloseRequest extends Serializable {

	/**
	 * @return the id of the request to be closed.
	 */
	String getId();

	/**
	 * @param value the id of the request to be closed.
	 */
	void setId(String value);

}


text:
import $ from 'jquery';

/**
 * Linked Tabs
 *
 * Handles persisting and restores the current tab selection and content.
 * Reusable component for static content.
 *
 * ### Example Markup
 *
 *

 *

 *
 *        Tab 1
 *
 *

 *

 *
 *        Tab 2
 *
 *

 *
 *
 *

 *

 *      Tab 1 Content
 *

 *

 *      Tab 2 Content
 *

 *

 *
 *
 * ### How to use
 *
 *  new LinkedTabs({
 *    action: "#{controller.action_name}",
 *    defaultAction: 'tab1',
 *    parentEl: '.tab-links'
 *  });
 */

export default class LinkedTabs {
  /**
   * Binds the events and activates de default tab.
   *
   * @param  {Object} options
   */
  constructor(options = {}) {
    this.options = options;

    this.defaultAction = this.options.defaultAction;
    this.action = this.options.action || this.defaultAction;
    this.hashedTabs = this.options.hashedTabs || false;

    if (this.action === 'show') {
      this.action = this.defaultAction;
    }

    this.currentLocation = window.location;

    if (this.hashedTabs) {
      this.action = this.currentLocation.hash || this.action;
    }

    const tabSelector = `${this.options.parentEl} a[data-toggle="tab"]`;

    // since this is a custom event we need jQuery :(
    $(document)
      .off('shown.bs.tab', tabSelector)
      .on('shown.bs.tab', tabSelector, e => this.tabShown(e));

    this.activateTab(this.action);
  }

  /**
   * Handles the `shown.bs.tab` event to set the currect url action.
   *
   * @param  {type} evt
   * @return {Function}
   */
  tabShown(evt) {
    const source = evt.target.getAttribute('href');

    return this.setCurrentAction(source);
  }

  /**
   * Updates the URL with the path that matched the given action.
   *
   * @param  {String} source
   * @return {String}
   */
  setCurrentAction(source) {
    const copySource = source;

    copySource.replace(/\/+$/, '');

    const newState = this.hashedTabs
      ? copySource
      : `${copySource}${this.currentLocation.search}${this.currentLocation.hash}`;

    window.history.replaceState(
      {
        url: newState,
      },
      document.title,
      newState,
    );
    return newState;
  }

  /**
   * Given the current action activates the correct tab.
   * http://getbootstrap.com/javascript/#tab-show
   * Note: Will trigger `shown.bs.tab`
   */
  activateTab() {
    return $(`${this.options.parentEl} a[data-action='${this.action}']`).tab('show');
  }
}


text:
import { Component, Input, Output, EventEmitter, OnInit, OnChanges, SimpleChange } from '@angular/core';
import { Deck } from '../../shared/models/deck.model';
import { DeckService } from '../../shared/services/deck.service';

@Component({
  moduleId: module.id,
  selector: 'agot-existing-deck-selector',
  templateUrl: 'existing-deck-selector.component.html',
})
export class ExistingDeckSelectorComponent implements OnInit, OnChanges {
  @Input()
  playerId: number;
  @Input()
  existingDeck: Deck;
  @Output()
  selectDeck: EventEmitter<Deck> = new EventEmitter<Deck>();

  myDecks: Deck[];
  allDecks: Deck[];

  isLoadingMyDecks: boolean;
  isLoadingAllDecks: boolean;

  showAllDecks: boolean = false;

  constructor(private deckService: DeckService) {
  }

  setShowAllDecks(state: boolean) {
    this.showAllDecks = state;
  }

  onDeckSelect(deck: Deck) {
    console.log(deck);
    this.selectDeck.emit(deck);
  }

  ngOnInit() {
    this.loadAllDecks();
  }

  ngOnChanges(changes: { [key: string]: SimpleChange }) {
    const change = changes['playerId'];
    if (change && change.previousValue !== change.currentValue) {
      this.loadMyDecks(this.playerId);
    }
  }

  private loadMyDecks(playerId: number) {
    this.isLoadingMyDecks = true;
    if (!playerId) {
      return;
    }
    this.deckService.getDecksFor(+playerId)
      .subscribe(
        (decks: Deck[]) => {
          this.myDecks = decks;
        },
        (error: Error) => {
          console.error(error);
          this.isLoadingMyDecks = false;
        }, () => {
          this.isLoadingMyDecks = false;
        }
      );
  }

  private loadAllDecks() {
    this.isLoadingAllDecks = true;
    return this.deckService.getDecks().subscribe(
      (decksArray: Deck[]) => {
        this.allDecks = decksArray;
      },
      (error: Error) => {
        console.error(error);
        this.isLoadingAllDecks = false;
      }, () => {
        this.isLoadingAllDecks = false;
      }
    );
  }
}


text:
import urllib2
request = urllib2.Request(uri, data=data)
request.get_method = lambda: 'PUT' # or 'DELETE'
response = urllib2.urlopen(request)


text:
<?xml version="1.0" encoding="utf-8"?>
<RadioGroup
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
    <RadioButton android:id="@+id/radio1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/rock" />

    <RadioButton android:id="@+id/radio2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/scissors" />

    <RadioButton android:id="@+id/radio3"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/paper" />
</RadioGroup>


text:
package com.erep.elucs.cmd;

import org.apache.commons.cli.Options;
import org.pircbotx.Channel;
import org.pircbotx.Colors;
import org.pircbotx.PircBotX;
import org.pircbotx.User;
import org.pircbotx.hooks.events.MessageEvent;

import java.util.Set;

/**
 * @author dragos
 */
public class CallCmd extends AbstractCmd {
    public CallCmd(PircBotX botX) {
        super(botX, "call", "<message> Sends a mass message to all users from channel.");
    }

    @Override
    public void doEventLogic(MessageEvent event) {
        String message = event.getMessage();
        if (message.startsWith(getCmdInput())) {
            if (hasAdminRights(event)) {
                int firstSpace = message.indexOf(' ');
                if (firstSpace > 0) {
                    Channel channel = event.getChannel();
                    Set<User> allUsers = channel.getUsers();
                    StringBuilder builder = new StringBuilder();
                    for (User user : allUsers) {
                        builder.append(user.getNick());
                        builder.append(" ");
//                    if (builder.length() > 400) {
//                        sendMessage(channel, builder.toString());
//                        builder = new StringBuilder();
//                    }
                    }
                    sendMessage(event, builder.toString());
                    String actualMessage = message.substring(firstSpace + 1);
                    sendMessage(event, Colors.BOLD + Colors.RED + actualMessage);
                } else {
                    sendUsage(event);
                }
            } else {
                sendError(event, "You don't have access to call this command.");
            }
        }

    }

    private boolean hasAdminRights(MessageEvent event) {
        Channel channel = event.getChannel();
        User user = event.getUser();
        return channel.isOp(user) || channel.isOwner(user) || channel.isSuperOp(user) || channel.isHalfOp(user);
    }

    @Override
    protected Options getCmdOptions() {
        return new Options();
    }
}


text:
require 'cf_spec_helper'

describe 'Rails 5.1 (Webpack/Yarn) App' do
  subject(:app) do
    Machete.deploy_app(app_name)
  end
  let(:browser) { Machete::Browser.new(app) }

  after do
    Machete::CF::DeleteApp.new.execute(app)
  end

  context 'in an online environment' do
    let(:app_name) { 'rails51' }

    specify do
      expect(app).to be_running
      expect(app).to have_logged /Downloaded.*node-6\./

      browser.visit_path('/')
      expect(browser).to have_body('Hello World')
      expect(app).to have_logged /Started GET "\/" for/
    end
  end
end


text:
require 'appsignal'

class AppsignalGenerator < Rails::Generators::Base
  EXCLUDED_ENVIRONMENTS = ['test'].freeze

  source_root File.expand_path('../templates', __FILE__)
  argument :push_api_key, :type => :string
  desc 'Generate a config file for AppSignal'

  def copy_config_file
    template_file = 'appsignal.yml'
    destination_file = File.join('config', template_file)
    if File.exists?(destination_file)
      say_status(:error, 'Looks like you already have a config file', :red)
    else
      template(template_file, destination_file)
      add_appsignal_require_for_capistrano
      check_push_api_key
    end
  end

  protected

  def add_appsignal_require_for_capistrano
    deploy_file = File.expand_path(File.join('config', 'deploy.rb'))
    cap_file = File.expand_path('Capfile')
    if [deploy_file, cap_file].all? { |file| File.exists?(file) }
      file_contents = File.read(deploy_file)
      if (file_contents =~ /require (\'|\").\/appsignal\/capistrano/).nil?
        append_to_file deploy_file, "\nrequire 'appsignal/capistrano'\n"
      end
    else
      say_status :info, "No capistrano setup detected! Did you know you can "\
        "use the AppSignal CLI to notify AppSignal of deployments?", :yellow
      say_status "", "Run the following command for help:"
      say_status "", "appsignal notify_of_deploy -h"
    end
  end

  def config
    Appsignal::Config.new(
      Rails.root,
      'development'
    )
  end

  def check_push_api_key
    auth_check = ::Appsignal::AuthCheck.new(config, Appsignal.logger)
    status, result = auth_check.perform_with_result
    if status == '200'
      say_status :success, result
    else
      say_status :error, result, :red
    end
  end

  private

  def environments
    @environments ||= Dir.glob(
      File.join(%w(. config environments *.rb))
    ).map { |o| File.basename(o, ".rb") }.sort - EXCLUDED_ENVIRONMENTS
  end
end


text:
package org.vertx.scala

/**
 * [[org.vertx.scala.Self]] allows fluent return types pointing to the type of
 * this object.
 *
 * @author Joern Bernhardt
 * @author Galder Zamarreño
 */
private[scala] trait Self {

  /**
   * Helper method wrapping invocations and returning the Scala type, once
   * again to help provide fluent return types
   */
  protected[this] def wrap[X](doStuff: => X): this.type = {
    doStuff
    this
  }

}


text:
package org.apache.jackrabbit.oak.plugins.index.lucene;

import java.util.Collection;
import java.util.function.Predicate;

import org.apache.jackrabbit.oak.plugins.index.search.IndexFormatVersion;
import org.apache.jackrabbit.oak.plugins.index.search.IndexLookup;
import org.apache.jackrabbit.oak.spi.query.Filter;
import org.apache.jackrabbit.oak.spi.state.NodeState;

import static org.apache.jackrabbit.oak.plugins.index.IndexConstants.TYPE_PROPERTY_NAME;
import static org.apache.jackrabbit.oak.plugins.index.lucene.LuceneIndexConstants.TYPE_LUCENE;

class LuceneIndexLookupUtil {
    static final Predicate<NodeState> LUCENE_INDEX_DEFINITION_PREDICATE =
            state -> TYPE_LUCENE.equals(state.getString(TYPE_PROPERTY_NAME));

    private LuceneIndexLookupUtil() {
    }

    /**
     * Returns the path of the first Lucene index node which supports
     * fulltext search
     */
    public static String getOldFullTextIndexPath(NodeState root, Filter filter, IndexTracker tracker) {
        Collection<String> indexPaths = getLuceneIndexLookup(root).collectIndexNodePaths(filter, false);
        LuceneIndexNode indexNode = null;
        for (String path : indexPaths) {
            try {
                indexNode = tracker.acquireIndexNode(path);
                if (indexNode != null
                        && indexNode.getDefinition().isFullTextEnabled()
                        && indexNode.getDefinition().getVersion() == IndexFormatVersion.V1) {
                    return path;
                }
            } finally {
                if (indexNode != null) {
                    indexNode.release();
                }
            }
        }
        return null;
    }

    public static IndexLookup getLuceneIndexLookup(NodeState root) {
        return new IndexLookup(root, LUCENE_INDEX_DEFINITION_PREDICATE);
    }
}


text:
class LxcConfigFileNotComplete(Exception):
    pass

class ContainerNotExists(Exception):
    pass

class ContainerAlreadyExists(Exception):
    pass

class ContainerDoesntExists(Exception):
    pass

class ContainerAlreadyRunning(Exception):
    pass

class ContainerNotRunning(Exception):
    pass

class DirectoryDoesntExists(Exception):
    pass

class NFSDirectoryNotMounted(Exception):
    pass


text:
<?php
/**
 * Author: Xavier
 */

namespace Prunatic\WebBundle\Doctrine\Type;

use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Platforms\AbstractPlatform;

use Prunatic\WebBundle\Entity\Point;

class PointType extends Type
{
    const POINT = 'point';

    public function getName()
    {
        return self::POINT;
    }

    public function getSqlDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {
        return 'POINT';
    }

    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        list($longitude, $latitude) = sscanf($value, 'POINT(%f %f)');

        return new Point($longitude, $latitude);
    }

    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        if ($value instanceof Point) {
            $value = sprintf('POINT(%F %F)', $value->getLongitude(), $value->getLatitude());
        }

        return $value;
    }

    public function canRequireSQLConversion()
    {
        return true;
    }

    /**
     * @see http://en.wikipedia.org/wiki/Well-known_text
     *
     * @param string $sqlExpr
     * @param AbstractPlatform $platform
     * @return string
     */
    public function convertToPHPValueSQL($sqlExpr, $platform)
    {
        return sprintf('AsText(%s)', $sqlExpr);
    }

    /**
     * @see http://dev.mysql.com/doc/refman/5.5/en/creating-spatial-values.html#function_pointfromtext
     *
     * @param string $sqlExpr
     * @param AbstractPlatform $platform
     * @return string
     */
    public function convertToDatabaseValueSQL($sqlExpr, AbstractPlatform $platform)
    {
        return sprintf('PointFromText(%s)', $sqlExpr);
    }
}


text:
package org.apache.commons.compress.archivers.sevenz;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.LinkedList;
import java.util.Map;
import java.util.zip.CRC32;

import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.utils.CountingOutputStream;

/**
 * Writes a 7z file.
 * @since 1.6
 */
public class SevenZOutputFile implements Closeable {
    private final RandomAccessFile file;
    private final List<SevenZArchiveEntry> files = new ArrayList<>();
    private int numNonEmptyStreams = 0;
    private final CRC32 crc32 = new CRC32();
    private final CRC32 compressedCrc32 = new CRC32();
    private long fileBytesWritten = 0;
    private boolean finished = false;
    private CountingOutputStream currentOutputStream;
    private CountingOutputStream[] additionalCountingStreams;
    private Iterable<? extends SevenZMethodConfiguration> contentMethods =
            Collections.singletonList(new SevenZMethodConfiguration(SevenZMethod.LZMA2));
    private final Map<SevenZArchiveEntry, long[]> additionalSizes = new HashMap<>();

    /**
     * Opens file to write a 7z archive to.
     *
     * @param filename name of the file to write to
     * @throws IOException if opening the file fails
     */
    public SevenZOutputFile(final File filename) throws IOException {
        file = new RandomAccessFile(filename, "rw");
        file.seek(SevenZFile.SIGNATURE_HEADER_SIZE);
    }

    /**
     * Sets the default compression method to use for entry contents - the
     * default is LZMA2.
     *
     *
Currently only {@link SevenZMethod#COPY}, {@link
     * SevenZMethod#LZMA2}, {@link SevenZMethod#BZIP2} and {@link
     * SevenZMethod#DEFLATE} are supported.

     *
     *
This is a short form for passing a single-element iterable
     * to {@link #setContentMethods}.

     * @param method the default compression method
     */
    public void setContentCompression(final SevenZMethod method) {
        setContentMethods(Collections.singletonList(new SevenZMethodConfiguration(method)));
    }

    /**
     * Sets the default (compression) methods to use for entry contents - the
     * default is LZMA2.
     *
     *
Currently only {@link SevenZMethod#COPY}, {@link
     * SevenZMethod#LZMA2}, {@link SevenZMethod#BZIP2} and {@link
     * SevenZMethod#DEFLATE} are supported.

     *
     *
The methods will be consulted in iteration order to create
     * the final output.

     *
     * @since 1.8
     * @param methods the default (compression) methods
     */
    public void setContentMethods(final Iterable<? extends SevenZMethodConfiguration> methods) {
        this.contentMethods = reverse(methods);
    }

    /**
     * Closes the archive, calling {@link #finish} if necessary.
     *
     * @throws IOException on error
     */
    @Override
    public void close() throws IOException {
        if (!finished) {
            finish();
        }
        file.close();
    }

    /**
     * Create an archive entry using the inputFile and entryName provided.
     *
     * @param inputFile file to create an entry from
     * @param entryName the name to use
     * @return the ArchiveEntry set up with details from the file
     *
     * @throws IOException on error
     */
    public SevenZArchiveEntry createArchiveEntry(final File inputFile,
            final String entryName) throws IOException {
        final SevenZArchiveEntry entry = new SevenZArchiveEntry();
        entry.setDirectory(inputFile.isDirectory());
        entry.setName(entryName);
        entry.setLastModifiedDate(new Date(inputFile.lastModified()));
        return entry;
    }

    /**
     * Records an archive entry to add.
     *
     * The caller must then write the content to the archive and call
     * {@link #closeArchiveEntry()} to complete the process.
     *
     * @param archiveEntry describes the entry
     * @throws IOException on error
     */
    public void putArchiveEntry(final ArchiveEntry archiveEntry) throws IOException {
        final SevenZArchiveEntry entry = (SevenZArchiveEntry) archiveEntry;
        files.add(entry);
    }

    /**
     * Closes the archive entry.
     * @throws IOException on error
     */
    public void closeArchiveEntry() throws IOException {
        if (currentOutputStream != null) {
            currentOutputStream.flush();
            currentOutputStream.close();
        }

        final SevenZArchiveEntry entry = files.get(files.size() - 1);
        if (fileBytesWritten > 0) {
            entry.setHasStream(true);
            ++numNonEmptyStreams;
            entry.setSize(currentOutputStream.getBytesWritten());
            entry.setCompressedSize(fileBytesWritten);
            entry.setCrcValue(crc32.getValue());
            entry.setCompressedCrcValue(compressedCrc32.getValue());
            entry.setHasCrc(true);
            if (additionalCountingStreams != null) {
                final long[] sizes = new long[additionalCountingStreams.length];
                for (int i = 0; i < additionalCountingStreams.length; i++) {
                    sizes[i] = additionalCountingStreams[i].getBytesWritten();
                }
                additionalSizes.put(entry, sizes);
            }
        } else {
            entry.setHasStream(false);
            entry.setSize(0);
            entry.setCompressedSize(0);
            entry.setHasCrc(false);
        }
        currentOutputStream = null;
        additionalCountingStreams = null;
        crc32.reset();
        compressedCrc32.reset();
        fileBytesWritten = 0;
    }

    /**
     * Writes a byte to the current archive entry.
     * @param b The byte to be written.
     * @throws IOException on error
     */
    public void write(final int b) throws IOException {
        getCurrentOutputStream().write(b);
    }

    /**
     * Writes a byte array to the current archive entry.
     * @param b The byte array to be written.
     * @throws IOException on error
     */
    public void write(final byte[] b) throws IOException {
        write(b, 0, b.length);
    }

    /**
     * Writes part of a byte array to the current archive entry.
     * @param b The byte array to be written.
     * @param off offset into the array to start writing from
     * @param len number of bytes to write
     * @throws IOException on error
     */
    public void write(final byte[] b, final int off, final int len) throws IOException {
        if (len > 0) {
            getCurrentOutputStream().write(b, off, len);
        }
    }

    /**
     * Finishes the addition of entries to this archive, without closing it.
     *
     * @throws IOException if archive is already closed.
     */
    public void finish() throws IOException {
        if (finished) {
            throw new IOException("This archive has already been finished");
        }
        finished = true;

        final long headerPosition = file.getFilePointer();

        final ByteArrayOutputStream headerBaos = new ByteArrayOutputStream();
        final DataOutputStream header = new DataOutputStream(headerBaos);

        writeHeader(header);
        header.flush();
        final byte[] headerBytes = headerBaos.toByteArray();
        file.write(headerBytes);

        final CRC32 crc32 = new CRC32();

        // signature header
        file.seek(0);
        file.write(SevenZFile.sevenZSignature);
        // version
        file.write(0);
        file.write(2);

        // start header
        final ByteArrayOutputStream startHeaderBaos = new ByteArrayOutputStream();
        final DataOutputStream startHeaderStream = new DataOutputStream(startHeaderBaos);
        startHeaderStream.writeLong(Long.reverseBytes(headerPosition - SevenZFile.SIGNATURE_HEADER_SIZE));
        startHeaderStream.writeLong(Long.reverseBytes(0xffffFFFFL & headerBytes.length));
        crc32.reset();
        crc32.update(headerBytes);
        startHeaderStream.writeInt(Integer.reverseBytes((int)crc32.getValue()));
        startHeaderStream.flush();
        final byte[] startHeaderBytes = startHeaderBaos.toByteArray();
        crc32.reset();
        crc32.update(startHeaderBytes);
        file.writeInt(Integer.reverseBytes((int) crc32.getValue()));
        file.write(startHeaderBytes);
    }

    /*
     * Creation of output stream is deferred until data is actually
     * written as some codecs might write header information even for
     * empty streams and directories otherwise.
     */
    private OutputStream getCurrentOutputStream() throws IOException {
        if (currentOutputStream == null) {
            currentOutputStream = setupFileOutputStream();
        }
        return currentOutputStream;
    }

    private CountingOutputStream setupFileOutputStream() throws IOException {
        if (files.isEmpty()) {
            throw new IllegalStateException("No current 7z entry");
        }

        OutputStream out = new OutputStreamWrapper();
        final ArrayList<CountingOutputStream> moreStreams = new ArrayList<>();
        boolean first = true;
        for (final SevenZMethodConfiguration m : getContentMethods(files.get(files.size() - 1))) {
            if (!first) {
                final CountingOutputStream cos = new CountingOutputStream(out);
                moreStreams.add(cos);
                out = cos;
            }
            out = Coders.addEncoder(out, m.getMethod(), m.getOptions());
            first = false;
        }
        if (!moreStreams.isEmpty()) {
            additionalCountingStreams = moreStreams.toArray(new CountingOutputStream[moreStreams.size()]);
        }
        return new CountingOutputStream(out) {
            @Override
            public void write(final int b) throws IOException {
                super.write(b);
                crc32.update(b);
            }

            @Override
            public void write(final byte[] b) throws IOException {
                super.write(b);
                crc32.update(b);
            }

            @Override
            public void write(final byte[] b, final int off, final int len)
                throws IOException {
                super.write(b, off, len);
                crc32.update(b, off, len);
            }
        };
    }

    private Iterable<? extends SevenZMethodConfiguration> getContentMethods(final SevenZArchiveEntry entry) {
        final Iterable<? extends SevenZMethodConfiguration> ms = entry.getContentMethods();
        return ms == null ? contentMethods : ms;
    }

    private void writeHeader(final DataOutput header) throws IOException {
        header.write(NID.kHeader);

        header.write(NID.kMainStreamsInfo);
        writeStreamsInfo(header);
        writeFilesInfo(header);
        header.write(NID.kEnd);
    }

    private void writeStreamsInfo(final DataOutput header) throws IOException {
        if (numNonEmptyStreams > 0) {
            writePackInfo(header);
            writeUnpackInfo(header);
        }

        writeSubStreamsInfo(header);

        header.write(NID.kEnd);
    }

    private void writePackInfo(final DataOutput header) throws IOException {
        header.write(NID.kPackInfo);

        writeUint64(header, 0);
        writeUint64(header, 0xffffFFFFL & numNonEmptyStreams);

        header.write(NID.kSize);
        for (final SevenZArchiveEntry entry : files) {
            if (entry.hasStream()) {
                writeUint64(header, entry.getCompressedSize());
            }
        }

        header.write(NID.kCRC);
        header.write(1); // "allAreDefined" == true
        for (final SevenZArchiveEntry entry : files) {
            if (entry.hasStream()) {
                header.writeInt(Integer.reverseBytes((int) entry.getCompressedCrcValue()));
            }
        }

        header.write(NID.kEnd);
    }

    private void writeUnpackInfo(final DataOutput header) throws IOException {
        header.write(NID.kUnpackInfo);

        header.write(NID.kFolder);
        writeUint64(header, numNonEmptyStreams);
        header.write(0);
        for (final SevenZArchiveEntry entry : files) {
            if (entry.hasStream()) {
                writeFolder(header, entry);
            }
        }

        header.write(NID.kCodersUnpackSize);
        for (final SevenZArchiveEntry entry : files) {
            if (entry.hasStream()) {
                final long[] moreSizes = additionalSizes.get(entry);
                if (moreSizes != null) {
                    for (final long s : moreSizes) {
                        writeUint64(header, s);
                    }
                }
                writeUint64(header, entry.getSize());
            }
        }

        header.write(NID.kCRC);
        header.write(1); // "allAreDefined" == true
        for (final SevenZArchiveEntry entry : files) {
            if (entry.hasStream()) {
                header.writeInt(Integer.reverseBytes((int) entry.getCrcValue()));
            }
        }

        header.write(NID.kEnd);
    }

    private void writeFolder(final DataOutput header, final SevenZArchiveEntry entry) throws IOException {
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int numCoders = 0;
        for (final SevenZMethodConfiguration m : getContentMethods(entry)) {
            numCoders++;
            writeSingleCodec(m, bos);
        }

        writeUint64(header, numCoders);
        header.write(bos.toByteArray());
        for (int i = 0; i < numCoders - 1; i++) {
            writeUint64(header, i + 1);
            writeUint64(header, i);
        }
    }

    private void writeSingleCodec(final SevenZMethodConfiguration m, final OutputStream bos) throws IOException {
        final byte[] id = m.getMethod().getId();
        final byte[] properties = Coders.findByMethod(m.getMethod())
            .getOptionsAsProperties(m.getOptions());

        int codecFlags = id.length;
        if (properties.length > 0) {
            codecFlags |= 0x20;
        }
        bos.write(codecFlags);
        bos.write(id);

        if (properties.length > 0) {
            bos.write(properties.length);
            bos.write(properties);
        }
    }

    private void writeSubStreamsInfo(final DataOutput header) throws IOException {
        header.write(NID.kSubStreamsInfo);
//
//        header.write(NID.kCRC);
//        header.write(1);
//        for (final SevenZArchiveEntry entry : files) {
//            if (entry.getHasCrc()) {
//                header.writeInt(Integer.reverseBytes(entry.getCrc()));
//            }
//        }
//
        header.write(NID.kEnd);
    }

    private void writeFilesInfo(final DataOutput header) throws IOException {
        header.write(NID.kFilesInfo);

        writeUint64(header, files.size());

        writeFileEmptyStreams(header);
        writeFileEmptyFiles(header);
        writeFileAntiItems(header);
        writeFileNames(header);
        writeFileCTimes(header);
        writeFileATimes(header);
        writeFileMTimes(header);
        writeFileWindowsAttributes(header);
        header.write(NID.kEnd);
    }

    private void writeFileEmptyStreams(final DataOutput header) throws IOException {
        boolean hasEmptyStreams = false;
        for (final SevenZArchiveEntry entry : files) {
            if (!entry.hasStream()) {
                hasEmptyStreams = true;
                break;
            }
        }
        if (hasEmptyStreams) {
            header.write(NID.kEmptyStream);
            final BitSet emptyStreams = new BitSet(files.size());
            for (int i = 0; i < files.size(); i++) {
                emptyStreams.set(i, !files.get(i).hasStream());
            }
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final DataOutputStream out = new DataOutputStream(baos);
            writeBits(out, emptyStreams, files.size());
            out.flush();
            final byte[] contents = baos.toByteArray();
            writeUint64(header, contents.length);
            header.write(contents);
        }
    }

    private void writeFileEmptyFiles(final DataOutput header) throws IOException {
        boolean hasEmptyFiles = false;
        int emptyStreamCounter = 0;
        final BitSet emptyFiles = new BitSet(0);
        for (final SevenZArchiveEntry file1 : files) {
            if (!file1.hasStream()) {
                final boolean isDir = file1.isDirectory();
                emptyFiles.set(emptyStreamCounter++, !isDir);
                hasEmptyFiles |= !isDir;
            }
        }
        if (hasEmptyFiles) {
            header.write(NID.kEmptyFile);
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final DataOutputStream out = new DataOutputStream(baos);
            writeBits(out, emptyFiles, emptyStreamCounter);
            out.flush();
            final byte[] contents = baos.toByteArray();
            writeUint64(header, contents.length);
            header.write(contents);
        }
    }

    private void writeFileAntiItems(final DataOutput header) throws IOException {
        boolean hasAntiItems = false;
        final BitSet antiItems = new BitSet(0);
        int antiItemCounter = 0;
        for (final SevenZArchiveEntry file1 : files) {
            if (!file1.hasStream()) {
                final boolean isAnti = file1.isAntiItem();
                antiItems.set(antiItemCounter++, isAnti);
                hasAntiItems |= isAnti;
            }
        }
        if (hasAntiItems) {
            header.write(NID.kAnti);
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final DataOutputStream out = new DataOutputStream(baos);
            writeBits(out, antiItems, antiItemCounter);
            out.flush();
            final byte[] contents = baos.toByteArray();
            writeUint64(header, contents.length);
            header.write(contents);
        }
    }

    private void writeFileNames(final DataOutput header) throws IOException {
        header.write(NID.kName);

        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final DataOutputStream out = new DataOutputStream(baos);
        out.write(0);
        for (final SevenZArchiveEntry entry : files) {
            out.write(entry.getName().getBytes("UTF-16LE"));
            out.writeShort(0);
        }
        out.flush();
        final byte[] contents = baos.toByteArray();
        writeUint64(header, contents.length);
        header.write(contents);
    }

    private void writeFileCTimes(final DataOutput header) throws IOException {
        int numCreationDates = 0;
        for (final SevenZArchiveEntry entry : files) {
            if (entry.getHasCreationDate()) {
                ++numCreationDates;
            }
        }
        if (numCreationDates > 0) {
            header.write(NID.kCTime);

            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final DataOutputStream out = new DataOutputStream(baos);
            if (numCreationDates != files.size()) {
                out.write(0);
                final BitSet cTimes = new BitSet(files.size());
                for (int i = 0; i < files.size(); i++) {
                    cTimes.set(i, files.get(i).getHasCreationDate());
                }
                writeBits(out, cTimes, files.size());
            } else {
                out.write(1); // "allAreDefined" == true
            }
            out.write(0);
            for (final SevenZArchiveEntry entry : files) {
                if (entry.getHasCreationDate()) {
                    out.writeLong(Long.reverseBytes(
                            SevenZArchiveEntry.javaTimeToNtfsTime(entry.getCreationDate())));
                }
            }
            out.flush();
            final byte[] contents = baos.toByteArray();
            writeUint64(header, contents.length);
            header.write(contents);
        }
    }

    private void writeFileATimes(final DataOutput header) throws IOException {
        int numAccessDates = 0;
        for (final SevenZArchiveEntry entry : files) {
            if (entry.getHasAccessDate()) {
                ++numAccessDates;
            }
        }
        if (numAccessDates > 0) {
            header.write(NID.kATime);

            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final DataOutputStream out = new DataOutputStream(baos);
            if (numAccessDates != files.size()) {
                out.write(0);
                final BitSet aTimes = new BitSet(files.size());
                for (int i = 0; i < files.size(); i++) {
                    aTimes.set(i, files.get(i).getHasAccessDate());
                }
                writeBits(out, aTimes, files.size());
            } else {
                out.write(1); // "allAreDefined" == true
            }
            out.write(0);
            for (final SevenZArchiveEntry entry : files) {
                if (entry.getHasAccessDate()) {
                    out.writeLong(Long.reverseBytes(
                            SevenZArchiveEntry.javaTimeToNtfsTime(entry.getAccessDate())));
                }
            }
            out.flush();
            final byte[] contents = baos.toByteArray();
            writeUint64(header, contents.length);
            header.write(contents);
        }
    }

    private void writeFileMTimes(final DataOutput header) throws IOException {
        int numLastModifiedDates = 0;
        for (final SevenZArchiveEntry entry : files) {
            if (entry.getHasLastModifiedDate()) {
                ++numLastModifiedDates;
            }
        }
        if (numLastModifiedDates > 0) {
            header.write(NID.kMTime);

            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final DataOutputStream out = new DataOutputStream(baos);
            if (numLastModifiedDates != files.size()) {
                out.write(0);
                final BitSet mTimes = new BitSet(files.size());
                for (int i = 0; i < files.size(); i++) {
                    mTimes.set(i, files.get(i).getHasLastModifiedDate());
                }
                writeBits(out, mTimes, files.size());
            } else {
                out.write(1); // "allAreDefined" == true
            }
            out.write(0);
            for (final SevenZArchiveEntry entry : files) {
                if (entry.getHasLastModifiedDate()) {
                    out.writeLong(Long.reverseBytes(
                            SevenZArchiveEntry.javaTimeToNtfsTime(entry.getLastModifiedDate())));
                }
            }
            out.flush();
            final byte[] contents = baos.toByteArray();
            writeUint64(header, contents.length);
            header.write(contents);
        }
    }

    private void writeFileWindowsAttributes(final DataOutput header) throws IOException {
        int numWindowsAttributes = 0;
        for (final SevenZArchiveEntry entry : files) {
            if (entry.getHasWindowsAttributes()) {
                ++numWindowsAttributes;
            }
        }
        if (numWindowsAttributes > 0) {
            header.write(NID.kWinAttributes);

            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final DataOutputStream out = new DataOutputStream(baos);
            if (numWindowsAttributes != files.size()) {
                out.write(0);
                final BitSet attributes = new BitSet(files.size());
                for (int i = 0; i < files.size(); i++) {
                    attributes.set(i, files.get(i).getHasWindowsAttributes());
                }
                writeBits(out, attributes, files.size());
            } else {
                out.write(1); // "allAreDefined" == true
            }
            out.write(0);
            for (final SevenZArchiveEntry entry : files) {
                if (entry.getHasWindowsAttributes()) {
                    out.writeInt(Integer.reverseBytes(entry.getWindowsAttributes()));
                }
            }
            out.flush();
            final byte[] contents = baos.toByteArray();
            writeUint64(header, contents.length);
            header.write(contents);
        }
    }

    private void writeUint64(final DataOutput header, long value) throws IOException {
        int firstByte = 0;
        int mask = 0x80;
        int i;
        for (i = 0; i < 8; i++) {
            if (value < ((1L << ( 7  * (i + 1))))) {
                firstByte |= (value >>> (8 * i));
                break;
            }
            firstByte |= mask;
            mask >>>= 1;
        }
        header.write(firstByte);
        for (; i > 0; i--) {
            header.write((int) (0xff & value));
            value >>>= 8;
        }
    }

    private void writeBits(final DataOutput header, final BitSet bits, final int length) throws IOException {
        int cache = 0;
        int shift = 7;
        for (int i = 0; i < length; i++) {
            cache |= ((bits.get(i) ? 1 : 0) << shift);
            if (--shift < 0) {
                header.write(cache);
                shift = 7;
                cache = 0;
            }
        }
        if (shift != 7) {
            header.write(cache);
        }
    }

    private static <T> Iterable<T> reverse(final Iterable<T> i) {
        final LinkedList<T> l = new LinkedList<>();
        for (final T t : i) {
            l.addFirst(t);
        }
        return l;
    }

    private class OutputStreamWrapper extends OutputStream {
        @Override
        public void write(final int b) throws IOException {
            file.write(b);
            compressedCrc32.update(b);
            fileBytesWritten++;
        }

        @Override
        public void write(final byte[] b) throws IOException {
            OutputStreamWrapper.this.write(b, 0, b.length);
        }

        @Override
        public void write(final byte[] b, final int off, final int len)
            throws IOException {
            file.write(b, off, len);
            compressedCrc32.update(b, off, len);
            fileBytesWritten += len;
        }

        @Override
        public void flush() throws IOException {
            // no reason to flush a RandomAccessFile
        }

        @Override
        public void close() throws IOException {
            // the file will be closed by the containing class's close method
        }
    }
}


text:
MdSettingsUI::MdSettingsUI(content::WebUI* web_ui)
    : content::WebUIController(web_ui) {
  // TODO(jlklein): Remove handler logic once settingsPrivate is ready.
#if defined(OS_CHROMEOS)
  core_handler_ = new chromeos::options::CoreChromeOSOptionsHandler();
#else
  core_handler_ = new options::CoreOptionsHandler();
#endif

  core_handler_->set_handlers_host(this);
  scoped_ptr<options::OptionsPageUIHandler> handler(core_handler_);
  if (handler->IsEnabled())
    web_ui->AddMessageHandler(handler.release());

  content::WebUIDataSource* html_source =
      content::WebUIDataSource::Create(chrome::kChromeUIMdSettingsHost);

  // Add all settings resources.
  for (size_t i = 0; i < kSettingsResourcesSize; ++i) {
    html_source->AddResourcePath(kSettingsResources[i].name,
                                 kSettingsResources[i].value);
  }

  settings::AddLocalizedStrings(html_source);
  html_source->AddResourcePath("md_settings.css", IDR_MD_SETTINGS_UI_CSS);
  html_source->SetDefaultResource(IDR_MD_SETTINGS_UI_HTML);

  content::WebUIDataSource::Add(web_ui->GetWebContents()->GetBrowserContext(),
                                html_source);
}

MdSettingsUI::~MdSettingsUI() {
}

void MdSettingsUI::InitializeHandlers() {
  Profile* profile = Profile::FromWebUI(web_ui());
  DCHECK(!profile->IsOffTheRecord() || profile->IsGuestSession());

  core_handler_->InitializeHandler();
  core_handler_->InitializePage();
}


text:
/**
 * Interpreter objects are the one doing the job of taking one command an running the logic on HTMLNode and Storage class.
 *
 * @param storage
 * @constructor
 */
var Interpreter = function(storage)
{
    this.storage = storage || null;
    this.application = null;
};

Interpreter.prototype.interpret = function(command)
{
    throw "Not implemented!";

    return false;
};

/**
 * This method expects to get a path in the form "key.of.my.object.them.path.to.the.property". One part of the path will be resolved through storage and context. But the other part
 * might get resolved in the object itself.
 * @param context A context object
 * @param path The path.to.the.property.
 * @param defaultValue A default value to return in case of not found.
 * @returns {*}
 */
Interpreter.prototype.getValue = function(context, path, defaultValue)
{
    var keyPathComponents = path.split('.');
    var objectPathComponents = [];
    var result = defaultValue;

    // Resolve value from context
    if (keyPathComponents[0] == 'context')
    {
        result = context;
        keyPathComponents.shift();

        while(keyPathComponents.length > 0)
        {
            if((context != null) && (typeof context == 'object') && (keyPathComponents.join('.') in context)) {
                result = context[keyPathComponents.join('.')]
                break;
            }
            objectPathComponents.unshift(keyPathComponents.pop());
        }

        for(var i = 0; i < objectPathComponents.length; ++i)
        {
            if((result == null) || (typeof result != 'object') || !(objectPathComponents[i] in result)) {
                return defaultValue;
            }
            result = result[objectPathComponents[i]];
        }

        return result;
    }

    // Resolve value from storage
    while(keyPathComponents.length > 0)
    {
        if(this.storage.has(keyPathComponents.join('.')))
        {
            result = this.storage.get(keyPathComponents.join('.'));
            break;
        }
        objectPathComponents.unshift(keyPathComponents.pop());
    }

    for(var i = 0; i < objectPathComponents.length; ++i)
    {
        if((result == null) || (typeof result != 'object') || !(objectPathComponents[i] in result)) {
            return defaultValue;
        }

        result = result[objectPathComponents[i]];
    }

    return result;
}

// Exports
module.exports = Interpreter;


text:
Ext.define('Ifresco.model.AutoOCRTransformerSettings', {
    extend: 'Ext.data.Model',
    fields: [
        {name: 'additionalOutputs',  type: 'auto'},
        {name: 'description',  type: 'string'},
        {name: 'engine', type: 'string'},
        {name: 'settingsName',  type: 'string'},
        {name: 'inputFormats', type: 'auto'},
        {name: 'inputFormatsMT', type: 'auto'},
        {name: 'outputFormats', type: 'auto'},
        {name: 'outputFormatsMT', type: 'auto'}
    ]
});


text:
LOGIN_URL = '/students/login/'
STATIC_URL = '/static/'
MEDIA_URL = '/media/'

ROOT_URLCONF = 'urls'


text:
package cogx.runtime.execution

import cogx.parameters.Cog
import cogx.platform.opencl._
import cogx.utilities.AnnotateThread
import com.jogamp.opencl.CLEvent
import cogx.runtime.allocation.AllocateFieldRegisters
import cogx.platform.types.AbstractKernel

import scala.collection.mutable
import cogx.platform.cpumemory.{AbstractFieldMemory, DirectBuffer, PinnedDirectBuffer}
import cogx.runtime.FieldID
import cogx.runtime.resources.GPU

/** Actor which supervises computation of a kernel circuit on a GPU.
  *
  * @param device OpenCL GPU managed by this supervisor.
  * @param gpu An object that allows late binding of the orderedKernels sequence (for multinode)
  * @param profileSize How often to print out profiling statistics (0 == never)
  *
  * @author Greg Snider
  */
private[runtime]
class GPUSupervisor(device: OpenCLDevice, gpu: GPU, profileSize: Int)
{
  // Bring `circuit` and `orderedKernels` into scope. */
  import gpu._

  // The following approach to producing `orderedKernels` resulted in deadlocks
  // in a multi-GPU setting.  The responsibility of determining the order in which
  // kernels are added to the queues must be done by the partitioner unless
  // a smarter (cpu-kernel-driven ?) dynamic scheduler is adopted.  -RJC

  /** Kernels ordered so that they can be executed bottom-up. */
//  private val orderedKernels: Seq[OpenCLAbstractKernel] = Schedule(circuit)

  /** The outputs of the computation. */
  private val rootKernels: Seq[OpenCLAbstractKernel] = {
    val sequence = circuit.roots
    sequence.map(_.asInstanceOf[OpenCLAbstractKernel])
  }

  /** Map of kernel ID to kernel. */
  private val idToKernel = new mutable.HashMap[Integer, AbstractKernel] {
    for (kernel <- orderedKernels)
      this(kernel.id) = kernel
  }

  /** Output events at "roots" that will be triggered when computation is done.*/
  private val rootOutputTriggers = new Array[CLEvent](rootKernels.length)

  /** Should the cpu portion of the buffers (if needed) be allocated in pinned memory. */
  private val bufferType =
    if (Cog.pinnedBuffers)
      PinnedDirectBuffer
    else
      DirectBuffer

  /** Pre start initialization and allocation. */
  def preStart() {

    // Add Cog function to thread name to aide thread probing tools like jconsole
    AnnotateThread(getClass.getSimpleName + "-" + gpu.deviceIndex)

    // Allocate registers for the fields.
    AllocateFieldRegisters(circuit, device, Some(orderedKernels), bufferType)

    // Install the kernels.
    for (kernel <- orderedKernels)
      installKernel(kernel)

    // Instantiate the kernels.
    for (kernel <- orderedKernels) {
      kernel match {
        case k: OpenCLCpuKernel =>
          device.instantiateKernel(k)
        case k: OpenCLDeviceKernel =>
          device.instantiateKernel(k)
        case x =>
          throw new RuntimeException("Illegal AbstractKernel class: " +
                  x.getClass.toString)
      }
    }
  }

  /** Post stop deallocation. */
  def postStop() {
    // TO DO XXX   deallocate field registers, uninstall / deinstantiate kernels
  }

  /** Reset the computation to its initial state. */
  def reset() {
    for (kernel <- orderedKernels)
      kernel.reset()

    // At this point we need to do a single evaluation to "prime" the network
    // for feedback. The problem is that the kernel buffers, other than the
    // inputs, contain garbage at this point, so we need to propagate the
    // inputs to the outputs so that every buffer contains valid data as a
    // result of being reset.
    evaluate()

    // Are we profiling this execution? If so, then reset the stats upon KernelCircuit reset (erases first evaluate)
    if (device.commandQueue.profile)
      for (kernel <- orderedKernels)
        kernel.stats.reset()
  }

  /** Advance the computation by one step. */
//  def evaluate(): Unit = device.lock.synchronized {
  def evaluate() {

    // Clock output registers, mark masters invalid since we're about to
    // overwrite them
    for (kernel <- orderedKernels)
      kernel.phase0Clock()

    // Keep a queue of the last 2 kernels to aide error reporting for launch failures
    var lastKernel: OpenCLAbstractKernel = null
    var nextToLastKernel: OpenCLAbstractKernel = null
    // Clock the circuit bottom-up, being prepared to handle kernel launch failures
    var launchedKernels = 0
    for (kernel <- orderedKernels) {
      try {
        kernel.phase1Clock()
        nextToLastKernel = lastKernel
        lastKernel = kernel
        launchedKernels += 1
        // The ParserSpec test on the HPOmen/IntelIris platform hung after 500 kernel launches without a flush.
        if (launchedKernels % Cog.kernelFlushFrequency == 0)
          device.commandQueue.flush()
      }
      catch {
        case e: Exception =>
          val rethrownMsg = new StringBuilder("\nLaunch of the following GPU kernel generated an exception: " + kernel)
          if (lastKernel != null)
            rethrownMsg append "\nThe kernel launched one before this: " + lastKernel
          if (nextToLastKernel != null)
            "\nThe kernel launched two before this (*** THE KERNEL LIKELY TO HAVE CAUSED A RUNTIME EXCEPTION UNDER NVIDIA OPENCL ***): " + nextToLastKernel
          rethrownMsg append "\nOpenCL exception message: " + e.getMessage()
          rethrownMsg append "\nOpenCL exception stack trace:\n" + e.getStackTrace
          throw new RuntimeException(rethrownMsg.toString)
      }
    }

    ///////////////////////////////////////////////////////////////////////////
    //
    // We now do a "hard" synchronization. This is inappropriate for dynamic
    // pipelining, but is simpler for now. This must be revisited when we
    // implement "running" directly rather than the current "single stepping"
    // and especially when we move dynamic pipelining (where the flush would
    // undesirable). XXX

    // My interpretation of the OpenCL 1.1 spec, Appendix A is this:
    //
    // If you have multiple command queues manipulating the same memory object,
    // event objects should be used to ensure the proper sequencing of reads
    // and writes of the memory object.  Also, when a command in queue "A" is set
    // to wait for a command in queue "B", queue "B" should be flushed to ensure
    // the device driver actually pushs the queue "B" command to the device
    // (instead of using some lazy evaluation technique perhaps).
    //
    // Now earlier the code below did a "clfinish," but I believe only a clflush
    // is required.  Technically, the OpenCLWaitForEvents call does an implicit
    // clflush, so even the clflush is probably not necessary.  However, since
    // the OpenCLWaitForEvents is not associated with a queue directly, I felt
    // is safer to perform the clflush, whose execution time is probably
    // hidden behind the subsequent WaitForEvents.    -RJC

    device.commandQueue.flush()

    // Wait for roots to finish. Actuators run as CPU kernels, so even though
    // all GPU processes have completed at this point, actuators may not have.

    // Now wait for roots/outputs of computation to finish, then return.
    for (r <- 0 until rootKernels.length) {
      rootOutputTriggers(r) = rootKernels(r).done.getEvent(0)
      require(rootOutputTriggers(r) != null)
    }
    device.waitForEvents(rootOutputTriggers)

    // End of hard synchronization
    //
    ///////////////////////////////////////////////////////////////////////////

    // We now have to release all events in all kernels.
    for (kernel <- orderedKernels)
      kernel.phase2Clock()

    // Print out kernel statistics every 'ProfileSize' cycles

    // CommandQueues for this device should already have profiling enabled.

    // When the Profiler uses this class, the CommandQueues will have profiling enabled, but
    // with profileSize == 0 to disable any output from the code below:

    if (profileSize > 0 && orderedKernels.size > 0) {
      val kernelsWithSamples =
        orderedKernels.filter(kernel => kernel.stats.totalSamples > 0 &&
                kernel.stats.totalSamples % profileSize == 0)
      val slowToFastKernels =
        kernelsWithSamples.sortWith(_.stats.avg > _.stats.avg)
      val slowToFastDeviceKernels = slowToFastKernels.filter(_.isInstanceOf[OpenCLDeviceKernel])
      val slowToFastCpuKernels = slowToFastKernels.filter(_.isInstanceOf[OpenCLCpuKernel])
      if (slowToFastKernels.size > 0) {
        println("************ kernel execution times (taken over " +
                profileSize + " steps) ************")
        println()
        val numDeviceKernels = slowToFastDeviceKernels.size
        if (numDeviceKernels > 0) {
          println("Device kernels: ")
          for (kernel <- slowToFastDeviceKernels)
            println("  " + kernel.stats + " | " + kernel)
          println
        }
        if (slowToFastCpuKernels.size > 0) {
          println("CPU kernels: ")
          for (kernel <- slowToFastCpuKernels)
            println("  " + kernel.stats + " | " + kernel)
          println
        }
        val totalAvgDeviceUsecs = slowToFastDeviceKernels.map(_.stats.avg).foldLeft(0.0)(_ + _)
        // Number below is a swag, as it varies depending on OS and kernel DAG structure
        // Value of 15.0 was set to accurately predict the speed of the performance.detection.TrainNetwork app
        // on a Titan Black on linux with no profiling.
        val KernelLaunchOverheadUsecs = 15.0
        val totalAvgDeviceUsecsWithOverhead =
          slowToFastDeviceKernels.map(k => math.max(KernelLaunchOverheadUsecs,k.stats.avg)).foldLeft(0.0)(_ + _)
        val maxAvgCpuUsecs = slowToFastCpuKernels.map(_.stats.avg).foldLeft(0.0)(_ max _)

        if (numDeviceKernels > 0)
          printf("Total avg execution time of %d device kernels = %.1f usec (sim freq = %.1f Hz)\n\n",
            slowToFastKernels.size, totalAvgDeviceUsecs, 1000000.0/totalAvgDeviceUsecs)
        if (slowToFastCpuKernels.size > 0)
          printf("Max Cpu kernel execution time = %.1f usec\n\n", maxAvgCpuUsecs)

        val totalKernelLaunchOverheadUsecs =  totalAvgDeviceUsecsWithOverhead - totalAvgDeviceUsecs
//        val totalKernelLaunchOverheadUsecs =  numDeviceKernels * KernelLaunchOverheadUsecs
//        val deviceCycleTimeWithOverhead = totalAvgDeviceUsecs + totalKernelLaunchOverheadUsecs
        val cycleTimeDictatedByMaxCpuKernel = maxAvgCpuUsecs > totalAvgDeviceUsecsWithOverhead
//        val cycleTimeDictatedByMaxCpuKernel = maxAvgCpuUsecs > deviceCycleTimeWithOverhead
        val cycleTimeEstimateUsecs =
          if (cycleTimeDictatedByMaxCpuKernel) {
            println("Cycle time dictated by longest CPU kernel!")
            maxAvgCpuUsecs
          }
          else
            totalAvgDeviceUsecsWithOverhead
//            deviceCycleTimeWithOverhead

        val cycleTimeEstimateSecs = cycleTimeEstimateUsecs/1000000
        val estimatedSimFreq = 1/cycleTimeEstimateSecs
        printf("Estimated execution time with %.0f usec launch overhead = %.1f usec (sim freq = %.1f Hz)\n\n",
          KernelLaunchOverheadUsecs, cycleTimeEstimateUsecs, estimatedSimFreq)
        if (!cycleTimeDictatedByMaxCpuKernel)
          printf("Estimated kernel launch overhead = %.1f%%\n\n",
            100.0 * totalKernelLaunchOverheadUsecs / cycleTimeEstimateUsecs)

        slowToFastKernels.foreach(_.stats.reset())
      }
    }

  }

  /** Install a kernel so it can be executed. */
  private def installKernel(kernel: AbstractKernel) {
    kernel match {
      case k: OpenCLCpuKernel =>
        device.addKernel(k)
      case k: OpenCLDeviceKernel =>
        device.addKernel(k)
      case x =>
        throw new RuntimeException("Illegal AbstractKernel class: " +
                x.getClass.toString)
    }
  }

  /** Read a field into CPU memory.
    *
    * @param fieldID Unique identifier of the field.
    * @return The field in a CPU memory buffer.
    */
  def readField(fieldID: FieldID): AbstractFieldMemory = {
    val kernel = idToKernel.get(fieldID.kernelID) match {
      case Some(_kernel) => _kernel
      case None => throw new RuntimeException(s"Internal compiler error: read of field $fieldID is not possible.")
    }
    val kernelOutput = fieldID.kernelOutput
    val buffer =
      kernel.asInstanceOf[OpenCLAbstractKernel].outputRegister(kernelOutput).slave
    val memory = device.platform.fieldMemoryAllocator.copy(buffer.read.asInstanceOf[AbstractFieldMemory])
    memory
  }
}


text:
{% extends "hmpo-template.njk" %}
{% set hmpoPageKey = "index" %}


text:
require 'rails_helper'

RSpec.describe PagesController, :type => :controller do

  describe "GET 'landing'" do
    it "returns http success" do
      get 'landing'
      expect(response).to be_success
    end
  end

  describe "GET 'inactive'" do
    it "returns http success" do
      get 'inactive'
      expect(response).to be_success
    end
  end
end


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

package com.cloudera.impala.catalog;

import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.hadoop.hive.metastore.HiveMetaStoreClient;
import org.apache.hadoop.hive.metastore.TableType;
import org.apache.hadoop.hive.metastore.api.ColumnStatistics;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.ql.stats.StatsSetupConst;
import org.apache.log4j.Logger;

import com.cloudera.impala.analysis.TableName;
import com.cloudera.impala.thrift.TAccessLevel;
import com.cloudera.impala.thrift.TCatalogObject;
import com.cloudera.impala.thrift.TCatalogObjectType;
import com.cloudera.impala.thrift.TColumn;
import com.cloudera.impala.thrift.TTable;
import com.cloudera.impala.thrift.TTableDescriptor;
import com.cloudera.impala.thrift.TTableStats;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * Base class for table metadata.
 *
 * This includes the concept of clustering columns, which are columns by which the table
 * data is physically clustered. In other words, if two rows share the same values
 * for the clustering columns, those two rows are most likely colocated. Note that this
 * is more general than Hive's CLUSTER BY ... INTO BUCKETS clause (which partitions
 * a key range into a fixed number of buckets).
 */
public abstract class Table implements CatalogObject {
  private static final Logger LOG = Logger.getLogger(Table.class);

  // Lock used to serialize calls to the Hive MetaStore to work around MetaStore
  // concurrency bugs. Currently used to serialize calls to "getTable()" due to HIVE-5457.
  private static final Object metastoreAccessLock_ = new Object();
  private long catalogVersion_ = Catalog.INITIAL_CATALOG_VERSION;
  protected final org.apache.hadoop.hive.metastore.api.Table msTable_;

  protected final TableId id_;
  protected final Db db_;
  protected final String name_;
  protected final String owner_;
  protected TTableDescriptor tableDesc_;
  protected List<FieldSchema> fields_;
  protected TAccessLevel accessLevel_ = TAccessLevel.READ_WRITE;

  // Number of clustering columns.
  protected int numClusteringCols_;

  // estimated number of rows in table; -1: unknown.
  protected long numRows_ = -1;

  // colsByPos[i] refers to the ith column in the table. The first numClusteringCols are
  // the clustering columns.
  private final ArrayList<Column> colsByPos_;

  // map from lowercase column name to Column object.
  private final Map<String, Column> colsByName_;

  // The lastDdlTime for this table; -1 if not set
  protected long lastDdlTime_;

  // Set of supported table types.
  protected static EnumSet<TableType> SUPPORTED_TABLE_TYPES = EnumSet.of(
      TableType.EXTERNAL_TABLE, TableType.MANAGED_TABLE, TableType.VIRTUAL_VIEW);

  protected Table(TableId id, org.apache.hadoop.hive.metastore.api.Table msTable, Db db,
      String name, String owner) {
    id_ = id;
    msTable_ = msTable;
    db_ = db;
    name_ = name.toLowerCase();
    owner_ = owner;
    colsByPos_ = Lists.newArrayList();
    colsByName_ = Maps.newHashMap();
    lastDdlTime_ = (msTable_ != null) ?
        CatalogServiceCatalog.getLastDdlTime(msTable_) : -1;
  }

  //number of nodes that contain data for this table; -1: unknown
  public abstract int getNumNodes();
  public abstract TTableDescriptor toThriftDescriptor(Set<Long> referencedPartitions);
  public abstract TCatalogObjectType getCatalogObjectType();

  /**
   * Populate members of 'this' from metastore info. Reuse metadata from oldValue if the
   * metadata is still valid.
   */
  public abstract void load(Table oldValue, HiveMetaStoreClient client,
      org.apache.hadoop.hive.metastore.api.Table msTbl) throws TableLoadingException;

  public void addColumn(Column col) {
    colsByPos_.add(col);
    colsByName_.put(col.getName().toLowerCase(), col);
  }

  public void clearColumns() {
    colsByPos_.clear();
    colsByName_.clear();
  }

  /**
   * Updates the lastDdlTime for this Table, if the new value is greater
   * than the existing value. Does nothing if the new value is less than
   * or equal to the existing value.
   */
  public void updateLastDdlTime(long ddlTime) {
    // Ensure the lastDdlTime never goes backwards.
    if (ddlTime > lastDdlTime_) lastDdlTime_ = ddlTime;
  }

  /**
   * Loads the column stats for col from the Hive Metastore.
   */
  protected void loadColumnStats(Column col, HiveMetaStoreClient client) {
    ColumnStatistics colStats = null;
    try {
      colStats = client.getTableColumnStatistics(db_.getName(), name_, col.getName());
    } catch (Exception e) {
      // don't try to load stats for this column
      return;
    }

    // we should never see more than one ColumnStatisticsObj here
    if (colStats.getStatsObj().size() > 1) return;

    if (!ColumnStats.isSupportedColType(col.getType())) {
      LOG.warn(String.format("Column stats are available for table %s / " +
          "column '%s', but Impala does not currently support column stats for this " +
          "type of column (%s)",  name_, col.getName(), col.getType().toString()));
      return;
    }

    // Update the column stats data
    if (!col.updateStats(colStats.getStatsObj().get(0).getStatsData())) {
      LOG.warn(String.format("Applying the column stats update to table %s / " +
          "column '%s' did not succeed because column type (%s) was not compatible " +
          "with the column stats data. Performance may suffer until column stats are" +
          " regenerated for this column.",
          name_, col.getName(), col.getType().toString()));
    }
  }

  /**
   * Returns the value of the ROW_COUNT constant, or -1 if not found.
   */
  protected static long getRowCount(Map<String, String> parameters) {
    if (parameters == null) return -1;
    String numRowsStr = parameters.get(StatsSetupConst.ROW_COUNT);
    if (numRowsStr == null) return -1;
    try {
      return Long.valueOf(numRowsStr);
    } catch (NumberFormatException exc) {
      // ignore
    }
    return -1;
  }

  /**
   * Creates a table of the appropriate type based on the given hive.metastore.api.Table
   * object.
   */
  public static Table fromMetastoreTable(TableId id, Db db,
      org.apache.hadoop.hive.metastore.api.Table msTbl) {
    // Create a table of appropriate type
    Table table = null;
    if (TableType.valueOf(msTbl.getTableType()) == TableType.VIRTUAL_VIEW) {
      table = new View(id, msTbl, db, msTbl.getTableName(), msTbl.getOwner());
    } else if (msTbl.getSd().getInputFormat().equals(HBaseTable.getInputFormat())) {
      table = new HBaseTable(id, msTbl, db, msTbl.getTableName(), msTbl.getOwner());
    } else if (DataSourceTable.isDataSourceTable(msTbl)) {
      // It's important to check if this is a DataSourceTable before HdfsTable because
      // DataSourceTables are still represented by HDFS tables in the metastore but
      // have a special table property to indicate that Impala should use an external
      // data source.
      table = new DataSourceTable(id, msTbl, db, msTbl.getTableName(), msTbl.getOwner());
    } else if (HdfsFileFormat.isHdfsFormatClass(msTbl.getSd().getInputFormat())) {
      table = new HdfsTable(id, msTbl, db, msTbl.getTableName(), msTbl.getOwner());
    }
    return table;
  }

  /**
   * Factory method that creates a new Table from its Thrift representation.
   * Determines the type of table to create based on the Thrift table provided.
   */
  public static Table fromThrift(Db parentDb, TTable thriftTable)
      throws TableLoadingException {
    Table newTable;
    if (!thriftTable.isSetLoad_status() && thriftTable.isSetMetastore_table())  {
      newTable = Table.fromMetastoreTable(new TableId(thriftTable.getId()),
          parentDb, thriftTable.getMetastore_table());
    } else {
      newTable = IncompleteTable.createUninitializedTable(
          TableId.createInvalidId(), parentDb, thriftTable.getTbl_name());
    }
    newTable.loadFromThrift(thriftTable);
    newTable.validate();
    return newTable;
  }

  protected void loadFromThrift(TTable thriftTable) throws TableLoadingException {
    List<TColumn> columns = new ArrayList<TColumn>();
    columns.addAll(thriftTable.getClustering_columns());
    columns.addAll(thriftTable.getColumns());

    fields_ = new ArrayList<FieldSchema>();
    colsByPos_.clear();
    colsByPos_.ensureCapacity(columns.size());
    for (int i = 0; i < columns.size(); ++i) {
      Column col = Column.fromThrift(columns.get(i));
      colsByPos_.add(col.getPosition(), col);
      colsByName_.put(col.getName().toLowerCase(), col);
      fields_.add(new FieldSchema(col.getName(),
        col.getType().toString().toLowerCase(), col.getComment()));
    }

    numClusteringCols_ = thriftTable.getClustering_columns().size();

    // Estimated number of rows
    numRows_ = thriftTable.isSetTable_stats() ?
        thriftTable.getTable_stats().getNum_rows() : -1;

    // Default to READ_WRITE access if the field is not set.
    accessLevel_ = thriftTable.isSetAccess_level() ? thriftTable.getAccess_level() :
        TAccessLevel.READ_WRITE;
  }

  /**
   * Checks preconditions for this table to function as expected. Currently only checks
   * that all entries in colsByName_ use lower case keys.
   */
  public void validate() throws TableLoadingException {
    for (String colName: colsByName_.keySet()) {
      if (!colName.equals(colName.toLowerCase())) {
        throw new TableLoadingException(
            "Expected lower case column name but found: " + colName);
      }
    }
  }

  public TTable toThrift() {
    TTable table = new TTable(db_.getName(), name_);
    table.setId(id_.asInt());
    table.setAccess_level(accessLevel_);

    // Populate both regular columns and clustering columns (if there are any).
    table.setColumns(new ArrayList<TColumn>());
    table.setClustering_columns(new ArrayList<TColumn>());
    for (int i = 0; i < colsByPos_.size(); ++i) {
      TColumn colDesc = colsByPos_.get(i).toThrift();
      // Clustering columns come first.
      if (i < numClusteringCols_) {
        table.addToClustering_columns(colDesc);
      } else {
        table.addToColumns(colDesc);
      }
    }

    table.setMetastore_table(getMetaStoreTable());
    if (numRows_ != -1) {
      table.setTable_stats(new TTableStats());
      table.getTable_stats().setNum_rows(numRows_);
    }
    return table;
  }

  public TCatalogObject toTCatalogObject() {
    TCatalogObject catalogObject = new TCatalogObject();
    catalogObject.setType(getCatalogObjectType());
    catalogObject.setCatalog_version(getCatalogVersion());
    catalogObject.setTable(toThrift());
    return catalogObject;
  }

  /**
   * Gets the ColumnType from the given FieldSchema by using Impala's SqlParser.
   * Throws a TableLoadingException if the FieldSchema could not be parsed.
   * The type can either be:
   *   - Supported by Impala, in which case the type is returned.
   *   - A type Impala understands but is not yet implemented (e.g. date), the type is
   *     returned but type.IsSupported() returns false.
   *   - A type Impala can't understand at all, and a TableLoadingException is thrown.
   */
   protected Type parseColumnType(FieldSchema fs) throws TableLoadingException {
     Type type = Type.parseColumnType(fs);
     if (type == null) {
       throw new TableLoadingException(String.format(
           "Unsupported type '%s' in column '%s' of table '%s'",
           fs.getType(), fs.getName(), getName()));
     }
     return type;
   }

  /**
   * Returns true if this table is not a base table that stores data (e.g., a view).
   * Virtual tables should not be added to the descriptor table sent to the BE, i.e.,
   * toThrift() should not work on virtual tables.
   */
  public boolean isVirtualTable() { return false; }
  public Db getDb() { return db_; }
  public String getName() { return name_; }
  public String getFullName() { return (db_ != null ? db_.getName() + "." : "") + name_; }
  public TableName getTableName() {
    return new TableName(db_ != null ? db_.getName() : null, name_);
  }
  public String getOwner() { return owner_; }
  public ArrayList<Column> getColumns() { return colsByPos_; }

  /**
   * Returns a list of the column names ordered by position.
   */
  public List<String> getColumnNames() {
    List<String> colNames = Lists.<String>newArrayList();
    for (Column col: colsByPos_) {
      colNames.add(col.getName());
    }
    return colNames;
  }

  /**
   * Subclasses should override this if they provide a storage handler class. Currently
   * only HBase tables need to provide a storage handler.
   */
  public String getStorageHandlerClassName() { return null; }

  /**
   * Returns the list of all columns, but with partition columns at the end of
   * the list rather than the beginning. This is equivalent to the order in
   * which Hive enumerates columns.
   */
  public ArrayList<Column> getColumnsInHiveOrder() {
    ArrayList<Column> columns = Lists.newArrayList();
    for (Column column: colsByPos_.subList(numClusteringCols_, colsByPos_.size())) {
      columns.add(column);
    }

    for (Column column: colsByPos_.subList(0, numClusteringCols_)) {
      columns.add(column);
    }
    return columns;
  }

  /**
   * Case-insensitive lookup.
   */
  public Column getColumn(String name) { return colsByName_.get(name.toLowerCase()); }

  /**
   * Returns the metastore.api.Table object this Table was created from. Returns null
   * if the derived Table object was not created from a metastore Table (ex. InlineViews).
   */
  public org.apache.hadoop.hive.metastore.api.Table getMetaStoreTable() {
    return msTable_;
  }

  public int getNumClusteringCols() { return numClusteringCols_; }
  public TableId getId() { return id_; }
  public long getNumRows() { return numRows_; }

  @Override
  public long getCatalogVersion() { return catalogVersion_; }

  @Override
  public void setCatalogVersion(long catalogVersion) {
    catalogVersion_ = catalogVersion;
  }

  @Override
  public boolean isLoaded() { return true; }
}


text:
using System.Runtime.CompilerServices;

namespace System.Reflection.Metadata.Ecma335
{
    internal static class HasDeclSecurityTag
    {
        internal const int NumberOfBits = 2;
        internal const int LargeRowSize = 0x00000001 << (16 - NumberOfBits);
        internal const uint TypeDef = 0x00000000;
        internal const uint MethodDef = 0x00000001;
        internal const uint Assembly = 0x00000002;
        internal const uint TagMask = 0x00000003;
        internal const TableMask TablesReferenced =
          TableMask.TypeDef
          | TableMask.MethodDef
          | TableMask.Assembly;
        internal const uint TagToTokenTypeByteVector = (TokenTypeIds.TypeDef >> 24) | (TokenTypeIds.MethodDef >> 16) | (TokenTypeIds.Assembly >> 8);

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        internal static EntityHandle ConvertToHandle(uint hasDeclSecurity)
        {
            uint tokenType = (TagToTokenTypeByteVector >> ((int)(hasDeclSecurity & TagMask) << 3)) << TokenTypeIds.RowIdBitCount;
            uint rowId = (hasDeclSecurity >> NumberOfBits);

            if (tokenType == 0 || (rowId & ~TokenTypeIds.RIDMask) != 0)
            {
                Throw.InvalidCodedIndex();
            }

            return new EntityHandle(tokenType | rowId);
        }

        internal static uint ConvertToTag(EntityHandle handle)
        {
            uint tokenType = handle.Type;
            uint rowId = (uint)handle.RowId;
            return (tokenType >> TokenTypeIds.RowIdBitCount) switch
            {
                TokenTypeIds.TypeDef >> TokenTypeIds.RowIdBitCount => rowId << NumberOfBits | TypeDef,
                TokenTypeIds.MethodDef >> TokenTypeIds.RowIdBitCount => rowId << NumberOfBits | MethodDef,
                TokenTypeIds.Assembly >> TokenTypeIds.RowIdBitCount => rowId << NumberOfBits | Assembly,
                _ => 0,
            };
        }
    }
}


text:
package com.example.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/other")
public class OtherController {

	@GetMapping
	public String index() {
		return "other";
	}
}