text:
/**
 * The classical Pattern - Apply the parent
 * Rent-a-constructor (Stoyan Stefanov)
 */

/*-----------------------------------------------------------*/

function Parent(name) {
	this.name = name || 'Mauro';
}

Parent.prototype.getName = function () {
	return this.name;
};

/*-----------------------------------------------------------*/

/**
 * Child constructor
 *
 * Now the Child constructor function uses the Parent constructor
 * and applies it with the instance of Child as this, and the
 * given arguments to this instance.
 *
 * Drawbacks:
 * 1. Does not inherit anything from the prototype, there's
 * no link with the used constructor/s.
 *
 * @constructor
 */
function Child() {
	Parent.apply(this, arguments);
}

/*-----------------------------------------------------------*/

/**
 * Multiple inheritance
 */

/*-----------------------------------------------------------*/

function Cat() {
	this.legs = 4;
	this.say = function () {
		return 'Meaow';
	};
}

function Bird() {
	this.wings = 2;
	this.fly = true;
}

/*-----------------------------------------------------------*/

/**
 * CatWings
 *
 * Multiple inheritance/copy of parent's own members
 *
 * @constructor
 */
function CatWings() {
	Cat.apply(this);
	Bird.apply(this);
}

module.exports = { Parent: Parent, Child: Child, CatWings: CatWings, Cat: Cat, Bird: Bird };


text:
<?php

defined('_JEXEC') or die;

/**
 * Projectlog Component Category Tree
 *
 * @package     Projectlog.site
 * @subpackage  com_projectlog
 * @since       3.3.1
 */
class ProjectlogCategories extends JCategories
{
	/**
	 * Constructor
	 *
	 * @param   array $options Array of configuration options
	 *
	 * @return  ProjectlogCategories
	 * @see     JCategories
	 * @since   3.3.1
	 */
	public function __construct($options = array())
	{
		$options['table']      = '#__projectlog_projects';
		$options['extension']  = 'com_projectlog';
		$options['statefield'] = 'published';
		parent::__construct($options);
	}
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Graphics.Imaging;
using Windows.Media;
using Windows.Media.Capture;
using Windows.Media.FaceAnalysis;
using Windows.Media.MediaProperties;
using Windows.System.Threading;

namespace FaceTheremin
{
    public class FaceMatrix
    {
        private readonly int _rowsCount;
        private readonly int _columnsCount;

        // FaceTracker detects faces
        private readonly FaceTracker _faceTracker;

        // MediaCapture provides source for streaming element and frames for face detection
        private readonly MediaCapture _mediaCapture;

        // Time interval between two separate face detections (8.33 fps)
        private readonly TimeSpan _frameProcessingTimerInterval = TimeSpan.FromMilliseconds(120);

        // The cells which had faces on a previous frame
        private readonly List<Cell> _previousFrameCells = new List<Cell>();
        private readonly VideoFrame _previewFrame;

        public event EventHandler<FaceMatrixFrameEventArgs> Frame;

        private FaceMatrix(FaceTracker faceTracker, MediaCapture mediaCapture, int rowsCount, int columnsCount)
        {
            _faceTracker = faceTracker;
            _mediaCapture = mediaCapture;

            // get properties of the stream, we need them to get width/height for face detection
            var videoProperties = _mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties;
            _previewFrame = new VideoFrame(BitmapPixelFormat.Nv12, (int)videoProperties.Width, (int)videoProperties.Height);

            _rowsCount = rowsCount;
            _columnsCount = columnsCount;
        }

        public static async Task<FaceMatrix> CreateAsync(MediaCapture mediaCapture, int rowsCount, int columnsCount)
        {
            var faceTracker = await FaceTracker.CreateAsync();
            var faceMatrix = new FaceMatrix(faceTracker, mediaCapture, rowsCount, columnsCount);
            faceMatrix.StartRecognitionLoop();

            return faceMatrix;
        }

        private void StartRecognitionLoop()
        {
            ThreadPoolTimer.CreateTimer(ProcessCurrentVideoFrameAsync, _frameProcessingTimerInterval);
        }

        /// <summary>
        /// Detect faces and process them
        /// </summary>
        /// <param name="timer"></param>
        private async void ProcessCurrentVideoFrameAsync(ThreadPoolTimer timer)
        {
            // fill the frame
            await _mediaCapture.GetPreviewFrameAsync(_previewFrame);

            // collection for faces
            IList<DetectedFace> faces;
            if (FaceDetector.IsBitmapPixelFormatSupported(_previewFrame.SoftwareBitmap.BitmapPixelFormat))
            {
                // get detected faces on the frame
                faces = await _faceTracker.ProcessNextFrameAsync(_previewFrame);
            }
            else
            {
                throw new NotSupportedException($"PixelFormat {BitmapPixelFormat.Nv12} is not supported by FaceDetector.");
            }

            // get the size of frame webcam provided, we need it to scale image on the screen
            var previewFrameSize = new Size(_previewFrame.SoftwareBitmap.PixelWidth, _previewFrame.SoftwareBitmap.PixelHeight);
            ProcessFrameFaces(previewFrameSize, faces);

            // arrange the next processing time
            ThreadPoolTimer.CreateTimer(ProcessCurrentVideoFrameAsync, _frameProcessingTimerInterval);
        }

        /// <summary>
        /// Color the cells with faces and play sounds for them
        /// </summary>
        /// <param name="previewFrameSize">Webcam resolution</param>
        /// <param name="faces"></param>
        private void ProcessFrameFaces(Size previewFrameSize, IList<DetectedFace> faces)
        {
            // get cells with faces
            var cells = faces.Select(x => CreateFaceCell(previewFrameSize, x)).ToArray();
            // exclude cells were on the previous frame
            var newCells = cells.Except(_previousFrameCells).ToArray();

            OnFrame(new FaceMatrixFrameEventArgs
                    {
                        PreviewFrameSize = previewFrameSize,
                        DetectedFaces = faces.ToArray(),
                        PreviousFaceCells = _previousFrameCells.ToArray(),
                        NewFaceCells = newCells.ToArray()
                    });

            // remember current cells with faces for next frame processing
            _previousFrameCells.Clear();
            _previousFrameCells.AddRange(cells);
        }

        /// <summary>
        /// Get the cell for a face
        /// </summary>
        /// <param name="previewFrameSize">Webcam resolution</param>
        /// <param name="face">Detected face</param>
        /// <returns>Cell</returns>
        private Cell CreateFaceCell(Size previewFrameSize, DetectedFace face)
        {
            var cellX = (face.FaceBox.X + face.FaceBox.Width / 2) / (uint)(previewFrameSize.Width / _columnsCount);
            var cellY = (face.FaceBox.Y + face.FaceBox.Height / 2) / (uint)(previewFrameSize.Height / _rowsCount);

            return new Cell((int)cellX, (int)cellY);
        }

        protected virtual void OnFrame(FaceMatrixFrameEventArgs e)
        {
            Frame?.Invoke(this, e);
        }
    }

    public class FaceMatrixFrameEventArgs : EventArgs
    {
        public Size PreviewFrameSize { get; set; }
        public IList<DetectedFace> DetectedFaces { get; set; }
        public IList<Cell> PreviousFaceCells { get; set; }
        public IList<Cell> NewFaceCells { get; set; }
    }
}


text:
require "engine.class"

--- Handles a particles system
-- Used by engine.Map
module(..., package.seeall, class.make)

local __particles_gl = {}
setmetatable(__particles_gl, {__mode="v"})

--- Make a particle emitter
function _M:init(def, radius, args, shader)
	self.args = args
	self.def = def
	self.radius = radius or 1
	self.shader = shader

	self:loaded()
end

--- Serialization
function _M:save()
	return class.save(self, {
		ps = true,
		gl_texture = true,
		_shader = true,
	})
end

function _M:cloned()
	self:loaded()
end

local foo = {}
function _M:loaded()
	local base_size = nil
	local gl = nil
	local islast = false
	local sub_particle = nil
	local sub_particle_args = nil
	if type(self.def) == "string" then
		local f, err = loadfile("/data/gfx/particles/"..self.def..".lua")
		if not f and err then error(err) end
		local t = self.args or {}
		local _
		setfenv(f, setmetatable(t, {__index=_G}))
		_, _ , _, gl, _ = f()
		setmetatable(t, nil)

		if t.use_shader then self.shader = t.use_shader end
		if t.alterscreen then islast = true end
		if t.toback then self.toback = true end
		if t.sub_particle then sub_particle = t.sub_particle end
		if t.sub_particle_args then sub_particle_args = t.sub_particle_args end
		if t.can_shift then self.can_shift = true end
	else error("unsupported particle type: "..type(self.def))
	end

	gl = gl or "particle"
	if not __particles_gl[gl] then __particles_gl[gl] = core.display.loadImage("/data/gfx/"..gl..".png"):glTexture() end
	gl = __particles_gl[gl]

	-- Zoom accordingly
	self.base_size = base_size
	self:updateZoom()

	-- Serialize arguments for passing into the particles threads
	local args = table.serialize(self.args or {}, nil, true)
	args = args.."tile_w="..engine.Map.tile_w.."\ntile_h="..engine.Map.tile_h

	self.update = fct

	local sha = nil
	if self.shader then
		if not self._shader then
			local Shader = require 'engine.Shader'
			self._shader = Shader.new(self.shader.type, self.shader)
		end

		sha = self._shader.shad
	end

	self.ps = core.particles.newEmitter("/data/gfx/particles/"..self.def..".lua", args, self.zoom, config.settings.particles_density or 100, gl, sha, islast)
	self.gl_texture = gl

	if sub_particle then
		self:setSub(sub_particle, 1, sub_particle_args)
	end
end

function _M:setSub(def, radius, args, shader)
	self.subps = _M.new(def, radius, args, shader)
	self.ps:setSub(self.subps.ps)
end

function _M:updateZoom()
	self.zoom = self.zoom or 1
	if self.base_size then
		self.zoom = ((engine.Map.tile_w + engine.Map.tile_h) / 2) / self.base_size
	end
end

function _M:checkDisplay()
	if self.ps then return end
	self:loaded()
end

function _M:dieDisplay()
	if not self.ps then return end
	self.ps:die()
	self.ps = nil
end

function _M:shift(map, mo)
	if not self.can_shift then return end

	local adx, ady = mo:getWorldPos()
	if self._adx then
		self.ps:shift(self._adx - adx, self._ady - ady)
	end
	self._adx, self._ady = adx, ady
end

function _M:shiftCustom(dx, dy)
	if not self.can_shift then return end

	self.ps:shift(dx, dy)
end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>Qwero - Ultimate Clean & Advanced WEB front-end framework.</title>
    <link rel="stylesheet" href="css/qwero.css" media="screen" title="no title">
    <link rel="stylesheet" href="css/qwero-header.css" media="screen" title="no title">
    <link rel="stylesheet" href="css/qwero-sliper.css" media="screen" title="no title">
    <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" media="screen" title="no title">
    <link rel="stylesheet" href="style.css" media="screen" title="no title">
    <link href="https://fonts.googleapis.com/css?family=Quicksand" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.4.0/css/swiper.min.css" media="screen" title="no title">

Qwero

 TOP

 Documentation

 Collection

 Themes

 Github

                Menu

Hello

Hello

Hello

Hello

                   Edit

                   Delete

                Panel

H1 Heading

H2 Heading

H3 Heading

H4 Heading

H5 Heading

H6 Heading

This is p

                   Edit

                   Delete


text: <input ng-disabled="::val.Inherited" aria-label="FeatureValue" ng-model="val.Value" type="number" style="{{::vm.cellStyling(val)}}; text-align:right;" ></input>


text:
<?php

namespace Field\Support\Relations;

use Field\Models\Field;

trait BelongsToField
{
    /**
     * Get the field that owns the resource.
     *
     * @return  \Illuminate\Database\Eloquent\Model
     */
    public function field()
    {
        return $this->belongsTo(Field::class);
    }
}


text:
from src import foo
from src import bar

x = bar(1)

res = fo<caret>o(2)


text:
package reciter.database.dynamodb.repository;

import org.socialsignin.spring.data.dynamodb.repository.EnableScan;
import org.springframework.data.repository.CrudRepository;
import reciter.database.dynamodb.model.MeshTerm;

@EnableScan
public interface DynamoMeshTermRepository extends CrudRepository<MeshTerm, String> {
}


text:
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace HOLMS.Types.Operations.RoomClaims {

  /// Holder for reflection information generated from operations/room_claims/room_assignment_by_night.proto
  public static partial class RoomAssignmentByNightReflection {

    #region Descriptor
    /// File descriptor for operations/room_claims/room_assignment_by_night.proto
    public static pbr::FileDescriptor Descriptor {
      get { return descriptor; }
    }
    private static pbr::FileDescriptor descriptor;

    static RoomAssignmentByNightReflection() {
      byte[] descriptorData = global::System.Convert.FromBase64String(
          string.Concat(
            "CjVvcGVyYXRpb25zL3Jvb21fY2xhaW1zL3Jvb21fYXNzaWdubWVudF9ieV9u",
            "aWdodC5wcm90bxIiaG9sbXMudHlwZXMub3BlcmF0aW9ucy5yb29tX2NsYWlt",
            "cxodcHJpbWl0aXZlL3BiX2xvY2FsX2RhdGUucHJvdG8aJW9wZXJhdGlvbnMv",
            "cm9vbXMvcm9vbV9pbmRpY2F0b3IucHJvdG8ihAEKFVJvb21Bc3NpZ25tZW50",
            "QnlOaWdodBI5CgRyb29tGAEgASgLMisuaG9sbXMudHlwZXMub3BlcmF0aW9u",
            "cy5yb29tcy5Sb29tSW5kaWNhdG9yEjAKBGRhdGUYAiABKAsyIi5ob2xtcy50",
            "eXBlcy5wcmltaXRpdmUuUGJMb2NhbERhdGVCO1oVb3BlcmF0aW9ucy9yb29t",
            "Y2xhaW1zqgIhSE9MTVMuVHlwZXMuT3BlcmF0aW9ucy5Sb29tQ2xhaW1zYgZw",
            "cm90bzM="));
      descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
          new pbr::FileDescriptor[] { global::HOLMS.Types.Primitive.PbLocalDateReflection.Descriptor, global::HOLMS.Types.Operations.Rooms.RoomIndicatorReflection.Descriptor, },
          new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
            new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Operations.RoomClaims.RoomAssignmentByNight), global::HOLMS.Types.Operations.RoomClaims.RoomAssignmentByNight.Parser, new[]{ "Room", "Date" }, null, null, null)
          }));
    }
    #endregion

  }
  #region Messages
  public sealed partial class RoomAssignmentByNight : pb::IMessage<RoomAssignmentByNight> {
    private static readonly pb::MessageParser<RoomAssignmentByNight> _parser = new pb::MessageParser<RoomAssignmentByNight>(() => new RoomAssignmentByNight());
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public static pb::MessageParser<RoomAssignmentByNight> Parser { get { return _parser; } }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public static pbr::MessageDescriptor Descriptor {
      get { return global::HOLMS.Types.Operations.RoomClaims.RoomAssignmentByNightReflection.Descriptor.MessageTypes[0]; }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    pbr::MessageDescriptor pb::IMessage.Descriptor {
      get { return Descriptor; }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public RoomAssignmentByNight() {
      OnConstruction();
    }

    partial void OnConstruction();

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public RoomAssignmentByNight(RoomAssignmentByNight other) : this() {
      Room = other.room_ != null ? other.Room.Clone() : null;
      Date = other.date_ != null ? other.Date.Clone() : null;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public RoomAssignmentByNight Clone() {
      return new RoomAssignmentByNight(this);
    }

    /// Field number for the "room" field.
    public const int RoomFieldNumber = 1;
    private global::HOLMS.Types.Operations.Rooms.RoomIndicator room_;
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public global::HOLMS.Types.Operations.Rooms.RoomIndicator Room {
      get { return room_; }
      set {
        room_ = value;
      }
    }

    /// Field number for the "date" field.
    public const int DateFieldNumber = 2;
    private global::HOLMS.Types.Primitive.PbLocalDate date_;
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public global::HOLMS.Types.Primitive.PbLocalDate Date {
      get { return date_; }
      set {
        date_ = value;
      }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public override bool Equals(object other) {
      return Equals(other as RoomAssignmentByNight);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public bool Equals(RoomAssignmentByNight other) {
      if (ReferenceEquals(other, null)) {
        return false;
      }
      if (ReferenceEquals(other, this)) {
        return true;
      }
      if (!object.Equals(Room, other.Room)) return false;
      if (!object.Equals(Date, other.Date)) return false;
      return true;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public override int GetHashCode() {
      int hash = 1;
      if (room_ != null) hash ^= Room.GetHashCode();
      if (date_ != null) hash ^= Date.GetHashCode();
      return hash;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public override string ToString() {
      return pb::JsonFormatter.ToDiagnosticString(this);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public void WriteTo(pb::CodedOutputStream output) {
      if (room_ != null) {
        output.WriteRawTag(10);
        output.WriteMessage(Room);
      }
      if (date_ != null) {
        output.WriteRawTag(18);
        output.WriteMessage(Date);
      }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public int CalculateSize() {
      int size = 0;
      if (room_ != null) {
        size += 1 + pb::CodedOutputStream.ComputeMessageSize(Room);
      }
      if (date_ != null) {
        size += 1 + pb::CodedOutputStream.ComputeMessageSize(Date);
      }
      return size;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public void MergeFrom(RoomAssignmentByNight other) {
      if (other == null) {
        return;
      }
      if (other.room_ != null) {
        if (room_ == null) {
          room_ = new global::HOLMS.Types.Operations.Rooms.RoomIndicator();
        }
        Room.MergeFrom(other.Room);
      }
      if (other.date_ != null) {
        if (date_ == null) {
          date_ = new global::HOLMS.Types.Primitive.PbLocalDate();
        }
        Date.MergeFrom(other.Date);
      }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public void MergeFrom(pb::CodedInputStream input) {
      uint tag;
      while ((tag = input.ReadTag()) != 0) {
        switch(tag) {
          default:
            input.SkipLastField();
            break;
          case 10: {
            if (room_ == null) {
              room_ = new global::HOLMS.Types.Operations.Rooms.RoomIndicator();
            }
            input.ReadMessage(room_);
            break;
          }
          case 18: {
            if (date_ == null) {
              date_ = new global::HOLMS.Types.Primitive.PbLocalDate();
            }
            input.ReadMessage(date_);
            break;
          }
        }
      }
    }

  }

  #endregion

}

#endregion Designer generated code


text:
<?php

namespace Tempo\Bundle\AppBundle\Settings;

use Sylius\Bundle\SettingsBundle\Schema\SchemaInterface;
use Sylius\Bundle\SettingsBundle\Schema\SettingsBuilderInterface;
use Symfony\Component\Form\FormBuilderInterface;

class GeneralSettingsSchema implements SchemaInterface
{
    public function buildSettings(SettingsBuilderInterface $builder)
    {
        $builder
            ->setDefaults(array(
                'name'            => 'Tempo',
            ))
            ->setAllowedTypes(array(
                'name'            => array('string'),
            ))
        ;
    }

    public function buildForm(FormBuilderInterface $builder)
    {
        $builder
            ->add('name')
        ;
    }
}


text:
module Text.Highlighter
    ( module Text.Highlighter.Lexer
    , module Text.Highlighter.Lexers
    , module Text.Highlighter.Types
    , lexerFromFilename
    ) where

import Text.Highlighter.Lexer
import Text.Highlighter.Lexers
import Text.Highlighter.Types

import System.FilePath

lexerFromFilename :: FilePath -> Maybe Lexer
lexerFromFilename = flip lookup lexers . takeExtension


text:
DROP TABLE IF EXISTS thea_bsm;

CREATE TABLE thea_bsm STORED AS ORC tblproperties("orc.compress"="Zlib") AS SELECT * FROM thea_bsm_staging;


text:
/*
 * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
 * Use is subject to license terms.
 *
 * Copyright (c) 2011, 2015, Intel Corporation.
 */
/*
 * This file is part of Lustre, http://www.lustre.org/
 * Lustre is a trademark of Sun Microsystems, Inc.
 */

#include <linux/module.h>
#include <linux/sysctl.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/stat.h>
#include <linux/ctype.h>
#include <linux/bitops.h>
#include <linux/uaccess.h>
#include <linux/utsname.h>

#define DEBUG_SUBSYSTEM S_CLASS

#include "../../include/obd_support.h"
#include "../../include/lprocfs_status.h"

struct static_lustre_uintvalue_attr {
	struct {
		struct attribute attr;
		ssize_t (*show)(struct kobject *kobj, struct attribute *attr,
				char *buf);
		ssize_t (*store)(struct kobject *kobj, struct attribute *attr,
				 const char *buf, size_t len);
	} u;
	int *value;
};

static ssize_t static_uintvalue_show(struct kobject *kobj,
				     struct attribute *attr,
				     char *buf)
{
	struct static_lustre_uintvalue_attr *lattr = (void *)attr;

	return sprintf(buf, "%d\n", *lattr->value);
}

static ssize_t static_uintvalue_store(struct kobject *kobj,
				      struct attribute *attr,
				      const char *buffer, size_t count)
{
	struct static_lustre_uintvalue_attr *lattr  = (void *)attr;
	int rc;
	unsigned int val;

	rc = kstrtouint(buffer, 10, &val);
	if (rc)
		return rc;

	*lattr->value = val;

	return count;
}

#define LUSTRE_STATIC_UINT_ATTR(name, value) \
static struct static_lustre_uintvalue_attr lustre_sattr_##name =	\
					{__ATTR(name, 0644,		\
						static_uintvalue_show,	\
						static_uintvalue_store),\
					  value }

LUSTRE_STATIC_UINT_ATTR(timeout, &obd_timeout);

static ssize_t max_dirty_mb_show(struct kobject *kobj, struct attribute *attr,
				 char *buf)
{
	return sprintf(buf, "%ul\n",
			obd_max_dirty_pages / (1 << (20 - PAGE_SHIFT)));
}

static ssize_t max_dirty_mb_store(struct kobject *kobj, struct attribute *attr,
				  const char *buffer, size_t count)
{
	int rc;
	unsigned long val;

	rc = kstrtoul(buffer, 10, &val);
	if (rc)
		return rc;

	val *= 1 << (20 - PAGE_SHIFT); /* convert to pages */

	if (val > ((totalram_pages / 10) * 9)) {
		/* Somebody wants to assign too much memory to dirty pages */
		return -EINVAL;
	}

	if (val < 4 << (20 - PAGE_SHIFT)) {
		/* Less than 4 Mb for dirty cache is also bad */
		return -EINVAL;
	}

	obd_max_dirty_pages = val;

	return count;
}
LUSTRE_RW_ATTR(max_dirty_mb);

LUSTRE_STATIC_UINT_ATTR(debug_peer_on_timeout, &obd_debug_peer_on_timeout);
LUSTRE_STATIC_UINT_ATTR(dump_on_timeout, &obd_dump_on_timeout);
LUSTRE_STATIC_UINT_ATTR(dump_on_eviction, &obd_dump_on_eviction);
LUSTRE_STATIC_UINT_ATTR(at_min, &at_min);
LUSTRE_STATIC_UINT_ATTR(at_max, &at_max);
LUSTRE_STATIC_UINT_ATTR(at_extra, &at_extra);
LUSTRE_STATIC_UINT_ATTR(at_early_margin, &at_early_margin);
LUSTRE_STATIC_UINT_ATTR(at_history, &at_history);

static struct attribute *lustre_attrs[] = {
	&lustre_sattr_timeout.u.attr,
	&lustre_attr_max_dirty_mb.attr,
	&lustre_sattr_debug_peer_on_timeout.u.attr,
	&lustre_sattr_dump_on_timeout.u.attr,
	&lustre_sattr_dump_on_eviction.u.attr,
	&lustre_sattr_at_min.u.attr,
	&lustre_sattr_at_max.u.attr,
	&lustre_sattr_at_extra.u.attr,
	&lustre_sattr_at_early_margin.u.attr,
	&lustre_sattr_at_history.u.attr,
	NULL,
};

static struct attribute_group lustre_attr_group = {
	.attrs = lustre_attrs,
};

int obd_sysctl_init(void)
{
	return sysfs_create_group(lustre_kobj, &lustre_attr_group);
}


text:
<!DOCTYPE html>

	<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
	<title>JQuery Validation Engine</title>
	<link rel="stylesheet" href="../css/validationEngine.jquery.css" type="text/css"/>
	<link rel="stylesheet" href="../css/template.css" type="text/css"/>

		Evaluate form
		| Validate sport1 select field
		| Close favorite sport 1 prompt
		| Close all prompts on form
		| Update all prompts positions
		| Build a prompt on a div
		| Close div prompt
		| Back to index

		This demonstration shows the different validators available

This is a div element

	<form id="formID" class="formular" method="post">
		<fieldset>
			<legend>
				Required!
			</legend>

				Field is required :
				<input value="" class="validate[required] text-input" type="text" name="req" id="req" data-errormessage-value-missing="This input is required!" />

			<legend>
				Placeholder & required
			</legend>

				Favorite sport 1:
				<select name="sport" id="sport" class="validate[required]" data-errormessage-value-missing="This select is required!" >
					<option value="">Choose a sport</option>
					<option value="option1">Tennis</option>
					<option value="option2">Football</option>
					<option value="option3">Golf</option>
				</select>

		</fieldset>

		<fieldset>
			<legend>
				Function
			</legend>

				Write 'HELLO' :
				<input value="" class="validate[required,funcCall[checkHELLO]] text-input" type="text" id="lastname" name="lastname" data-errormessage-custom-error="Let me give you a hint: write HELLO"  />

				validate[required,funcCall[checkHELLO]]

		</fieldset>

		<fieldset>
			<legend>
				MinSize
			</legend>

				Minimum field size

				<input value="" class="validate[required,minSize[6]] text-input" type="text" name="minsize" id="minsize" data-errormessage-range-underflow="You do not have the minimum required" />

				validate[required,minSize[6]]

		</fieldset>

		<fieldset>
			<legend>
				MaxSize
			</legend>

				Maximum field size, optional

				<input value="0123456789" class="validate[optional,maxSize[6]] text-input" type="text" name="maxsize" id="maxsize"  data-errormessage-range-overflow="You went too far"  />

				validate[maxSize[6]]

				note that the field is optional - it won't fail if it has no value

		</fieldset>

		<fieldset>
			<legend>
				Past
			</legend>

				Checks that the value is a date in the past

				Please enter a date ealier than 2010/01/01
				<input value="2012/06/30" class="validate[custom[date],past[2010/01/01]] text-input" type="text" name="past" id="past" data-errormessage-value-missing="Stop being in the past" data-errormessage-custom-error="Stop being in the past" data-errormessage-type-mismatch="Stop being in the past" />

				validate[custom[date],past[2010/01/01]]

		</fieldset>
		<fieldset>
			<legend>
				IP Address
			</legend>

				IP:
				<input value="192.168.3." class="validate[required,custom[ipv4]] text-input" type="text" name="ip" id="ip"  data-errormessage-custom-error="Wrong IP" />

		</fieldset>

		<input class="submit" type="submit" value="Validate & Send the form!"/>

	</form>


text:
import json

from pylib.base import base_test_result

def GenerateResultsDict(test_run_results):
  """Create a results dict from |test_run_results| suitable for writing to JSON.
  Args:
    test_run_results: a list of base_test_result.TestRunResults objects.
  Returns:
    A results dict that mirrors the one generated by
      base/test/launcher/test_results_tracker.cc:SaveSummaryAsJSON.
  """
  # Example json output.
  # {
  #   "global_tags": [],
  #   "all_tests": [
  #     "test1",
  #     "test2",
  #    ],
  #   "disabled_tests": [],
  #   "per_iteration_data": [
  #     {
  #       "test1": [
  #         {
  #           "status": "SUCCESS",
  #           "elapsed_time_ms": 1,
  #           "output_snippet": "",
  #           "output_snippet_base64": "",
  #           "losless_snippet": "",
  #         },
  #       ],
  #       "test2": [
  #         {
  #           "status": "FAILURE",
  #           "elapsed_time_ms": 12,
  #           "output_snippet": "",
  #           "output_snippet_base64": "",
  #           "losless_snippet": "",
  #         },
  #       ],
  #     },
  #     {
  #       "test1": [
  #         {
  #           "status": "SUCCESS",
  #           "elapsed_time_ms": 1,
  #           "output_snippet": "",
  #           "output_snippet_base64": "",
  #           "losless_snippet": "",
  #         },
  #       ],
  #       "test2": [
  #         {
  #           "status": "FAILURE",
  #           "elapsed_time_ms": 12,
  #           "output_snippet": "",
  #           "output_snippet_base64": "",
  #           "losless_snippet": "",
  #         },
  #       ],
  #     },
  #     ...
  #   ],
  # }

  def status_as_string(s):
    if s == base_test_result.ResultType.PASS:
      return 'SUCCESS'
    elif s == base_test_result.ResultType.SKIP:
      return 'SKIPPED'
    elif s == base_test_result.ResultType.FAIL:
      return 'FAILURE'
    elif s == base_test_result.ResultType.CRASH:
      return 'CRASH'
    elif s == base_test_result.ResultType.TIMEOUT:
      return 'TIMEOUT'
    elif s == base_test_result.ResultType.UNKNOWN:
      return 'UNKNOWN'

  all_tests = set()
  per_iteration_data = []
  for test_run_result in test_run_results:
    iteration_data = {
      t.GetName(): [{
        'status': status_as_string(t.GetType()),
        'elapsed_time_ms': t.GetDuration(),
        'output_snippet': '',
        'losless_snippet': '',
        'output_snippet_base64:': '',
      }]
      for t in test_run_result.GetAll()
    }
    all_tests = all_tests.union(set(iteration_data.iterkeys()))
    per_iteration_data.append(iteration_data)

  return {
    'global_tags': [],
    'all_tests': sorted(list(all_tests)),
    # TODO(jbudorick): Add support for disabled tests within base_test_result.
    'disabled_tests': [],
    'per_iteration_data': per_iteration_data,
  }

def GenerateJsonResultsFile(test_run_result, file_path):
  """Write |test_run_result| to JSON.

  This emulates the format of the JSON emitted by
  base/test/launcher/test_results_tracker.cc:SaveSummaryAsJSON.

  Args:
    test_run_result: a base_test_result.TestRunResults object.
    file_path: The path to the JSON file to write.
  """
  with open(file_path, 'w') as json_result_file:
    json_result_file.write(json.dumps(GenerateResultsDict(test_run_result)))

def ParseResultsFromJson(json_results):
  """Creates a list of BaseTestResult objects from JSON.

  Args:
    json_results: A JSON dict in the format created by
                  GenerateJsonResultsFile.
  """

  def string_as_status(s):
    if s == 'SUCCESS':
      return base_test_result.ResultType.PASS
    elif s == 'SKIPPED':
      return base_test_result.ResultType.SKIP
    elif s == 'FAILURE':
      return base_test_result.ResultType.FAIL
    elif s == 'CRASH':
      return base_test_result.ResultType.CRASH
    elif s == 'TIMEOUT':
      return base_test_result.ResultType.TIMEOUT
    else:
      return base_test_result.ResultType.UNKNOWN

  results_list = []
  testsuite_runs = json_results['per_iteration_data']
  for testsuite_run in testsuite_runs:
    for test, test_runs in testsuite_run.iteritems():
      results_list.extend(
          [base_test_result.BaseTestResult(test,
                                           string_as_status(tr['status']),
                                           duration=tr['elapsed_time_ms'])
          for tr in test_runs])
  return results_list


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

<title>Database</title>
<meta name="date" content="2014-12-16">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

weka.clusterers.forOPTICSAndDBScan.Databases

Interface Database

All Known Implementing Classes:

SequentialDatabase

public interface Database

 Database.java

 Authors: Rainer Holzmann, Zhanna Melnikova-Albrecht, Matthias Schubert

 Date: Aug 20, 2004

 Time: 1:03:43 PM

 $ Revision 1.4 $

Version:

$Revision: 1.2 $

Author:

Matthias Schubert (schubert@dbs.ifi.lmu.de), Zhanna Melnikova-Albrecht (melnikov@cip.ifi.lmu.de), Rainer Holzmann (holzmann@cip.ifi.lmu.de)

Method Summary

Methods

Modifier and Type
Method and Description

boolean
contains(DataObject dataObject_Query)

Tests if the database contains the dataObject_Query

java.util.List
coreDistance(int minPoints,
            double epsilon,
            DataObject dataObject)

Calculates the coreDistance for the specified DataObject.

java.util.Iterator
dataObjectIterator()

Returns an iterator over all the dataObjects in the database

java.util.List
epsilonRangeQuery(double epsilon,
                 DataObject queryDataObject)

Performs an epsilon range query for this dataObject

double[]
getAttributeMaxValues()

Returns the array of maximum-values for each attribute

double[]
getAttributeMinValues()

Returns the array of minimum-values for each attribute

DataObject
getDataObject(java.lang.String key)

Select a dataObject from the database

Instances
getInstances()

Returns the original instances delivered from WEKA

void
insert(DataObject dataObject)

Inserts a new dataObject into the database

java.util.List
k_nextNeighbourQuery(int k,
                    double epsilon,
                    DataObject dataObject)

Emits the k next-neighbours and performs an epsilon-range-query at the parallel.

java.util.Iterator
keyIterator()

Returns an iterator over all the keys

void
setMinMaxValues()

Sets the minimum and maximum values for each attribute in different arrays
 by walking through every DataObject of the database

int
size()

Returns the size of the database (the number of dataObjects in the database)

Method Detail

getDataObject

DataObject getDataObject(java.lang.String key)

Select a dataObject from the database

Parameters:

key - The key that is associated with the dataObject

Returns:

dataObject

size

int size()

Returns the size of the database (the number of dataObjects in the database)

Returns:

size

keyIterator

java.util.Iterator keyIterator()

Returns an iterator over all the keys

Returns:

iterator

dataObjectIterator

java.util.Iterator dataObjectIterator()

Returns an iterator over all the dataObjects in the database

Returns:

iterator

contains

boolean contains(DataObject dataObject_Query)

Tests if the database contains the dataObject_Query

Parameters:

dataObject_Query - The query-object

Returns:

true if the database contains dataObject_Query, else false

insert

void insert(DataObject dataObject)

Inserts a new dataObject into the database

Parameters:

dataObject -

getInstances

Instances getInstances()

Returns the original instances delivered from WEKA

Returns:

instances

setMinMaxValues

void setMinMaxValues()

Sets the minimum and maximum values for each attribute in different arrays
 by walking through every DataObject of the database

getAttributeMinValues

double[] getAttributeMinValues()

Returns the array of minimum-values for each attribute

Returns:

attributeMinValues

getAttributeMaxValues

double[] getAttributeMaxValues()

Returns the array of maximum-values for each attribute

Returns:

attributeMaxValues

epsilonRangeQuery

java.util.List epsilonRangeQuery(double epsilon,
                               DataObject queryDataObject)

Performs an epsilon range query for this dataObject

Parameters:

epsilon - Specifies the range for the query

queryDataObject - The dataObject that is used as query-object for epsilon range query

Returns:

List with all the DataObjects that are within the specified range

k_nextNeighbourQuery

java.util.List k_nextNeighbourQuery(int k,
                                  double epsilon,
                                  DataObject dataObject)

Emits the k next-neighbours and performs an epsilon-range-query at the parallel.
 The returned list contains two elements:
 At index=0 --> list with all k next-neighbours;
 At index=1 --> list with all dataObjects within epsilon;

Parameters:

k - number of next neighbours

epsilon - Specifies the range for the query

dataObject - the start object

Returns:

list with the k-next neighbours (PriorityQueueElements) and a list
         with candidates from the epsilon-range-query (EpsilonRange_ListElements)

coreDistance

java.util.List coreDistance(int minPoints,
                          double epsilon,
                          DataObject dataObject)

Calculates the coreDistance for the specified DataObject.
 The returned list contains three elements:
 At index=0 --> list with all k next-neighbours;
 At index=1 --> list with all dataObjects within epsilon;
 At index=2 --> coreDistance as Double-value

Parameters:

minPoints - minPoints-many neighbours within epsilon must be found to have a non-undefined coreDistance

epsilon - Specifies the range for the query

dataObject - Calculate coreDistance for this dataObject

Returns:

list with the k-next neighbours (PriorityQueueElements) and a list
         with candidates from the epsilon-range-query (EpsilonRange_ListElements) and
         the double-value for the calculated coreDistance

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package org.apache.flink.runtime.metrics.groups;

import org.apache.flink.configuration.ConfigConstants;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.MetricOptions;
import org.apache.flink.core.testutils.BlockerSync;
import org.apache.flink.metrics.CharacterFilter;
import org.apache.flink.metrics.Metric;
import org.apache.flink.metrics.MetricConfig;
import org.apache.flink.metrics.MetricGroup;
import org.apache.flink.metrics.reporter.MetricReporter;
import org.apache.flink.runtime.clusterframework.types.ResourceID;
import org.apache.flink.runtime.metrics.MetricRegistry;
import org.apache.flink.runtime.metrics.MetricRegistryImpl;
import org.apache.flink.runtime.metrics.MetricRegistryTestUtils;
import org.apache.flink.runtime.metrics.NoOpMetricRegistry;
import org.apache.flink.runtime.metrics.ReporterSetup;
import org.apache.flink.runtime.metrics.dump.QueryScopeInfo;
import org.apache.flink.runtime.metrics.scope.ScopeFormat;
import org.apache.flink.runtime.metrics.util.TestReporter;
import org.apache.flink.runtime.metrics.util.TestingMetricRegistry;
import org.apache.flink.util.TestLogger;

import org.hamcrest.collection.IsMapContaining;
import org.junit.Test;

import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

/** Tests for the {@link AbstractMetricGroup}. */
public class AbstractMetricGroupTest extends TestLogger {
    /**
     * Verifies that no {@link NullPointerException} is thrown when {@link
     * AbstractMetricGroup#getAllVariables()} is called and the parent is null.
     */
    @Test
    public void testGetAllVariables() throws Exception {
        MetricRegistryImpl registry =
                new MetricRegistryImpl(
                        MetricRegistryTestUtils.defaultMetricRegistryConfiguration());

        AbstractMetricGroup group =
                new AbstractMetricGroup<AbstractMetricGroup<?>>(registry, new String[0], null) {
                    @Override
                    protected QueryScopeInfo createQueryServiceMetricInfo(CharacterFilter filter) {
                        return null;
                    }

                    @Override
                    protected String getGroupName(CharacterFilter filter) {
                        return "";
                    }
                };
        assertTrue(group.getAllVariables().isEmpty());

        registry.shutdown().get();
    }

    @Test
    public void testGetAllVariablesWithOutExclusions() {
        MetricRegistry registry = NoOpMetricRegistry.INSTANCE;

        AbstractMetricGroup<?> group = new ProcessMetricGroup(registry, "host");
        assertThat(group.getAllVariables(), IsMapContaining.hasKey(ScopeFormat.SCOPE_HOST));
    }

    @Test
    public void testGetAllVariablesWithExclusions() {
        MetricRegistry registry = NoOpMetricRegistry.INSTANCE;

        AbstractMetricGroup<?> group = new ProcessMetricGroup(registry, "host");
        assertEquals(
                group.getAllVariables(-1, Collections.singleton(ScopeFormat.SCOPE_HOST)).size(), 0);
    }

    @Test
    public void testGetAllVariablesWithExclusionsForReporters() {
        MetricRegistry registry = TestingMetricRegistry.builder().setNumberReporters(2).build();

        AbstractMetricGroup<?> group =
                new GenericMetricGroup(registry, null, "test") {
                    @Override
                    protected void putVariables(Map<String, String> variables) {
                        variables.put("k1", "v1");
                        variables.put("k2", "v2");
                    }
                };

        group.getAllVariables(-1, Collections.emptySet());

        assertThat(
                group.getAllVariables(0, Collections.singleton("k1")),
                not(IsMapContaining.hasKey("k1")));
        assertThat(
                group.getAllVariables(0, Collections.singleton("k1")),
                IsMapContaining.hasKey("k2"));
        assertThat(
                group.getAllVariables(1, Collections.singleton("k2")),
                IsMapContaining.hasKey("k1"));
        assertThat(
                group.getAllVariables(1, Collections.singleton("k2")),
                not(IsMapContaining.hasKey("k2")));
    }

    // ========================================================================
    // Scope Caching
    // ========================================================================

    private static final CharacterFilter FILTER_C =
            new CharacterFilter() {
                @Override
                public String filterCharacters(String input) {
                    return input.replace("C", "X");
                }
            };
    private static final CharacterFilter FILTER_B =
            new CharacterFilter() {
                @Override
                public String filterCharacters(String input) {
                    return input.replace("B", "X");
                }
            };

    @Test
    public void testScopeCachingForMultipleReporters() throws Exception {
        Configuration config = new Configuration();
        config.setString(MetricOptions.SCOPE_NAMING_TM, "A.B.C.D");

        MetricConfig metricConfig1 = new MetricConfig();
        metricConfig1.setProperty(ConfigConstants.METRICS_REPORTER_SCOPE_DELIMITER, "-");

        MetricConfig metricConfig2 = new MetricConfig();
        metricConfig2.setProperty(ConfigConstants.METRICS_REPORTER_SCOPE_DELIMITER, "!");

        config.setString(
                ConfigConstants.METRICS_REPORTER_PREFIX
                        + "test1."
                        + ConfigConstants.METRICS_REPORTER_CLASS_SUFFIX,
                TestReporter1.class.getName());
        config.setString(
                ConfigConstants.METRICS_REPORTER_PREFIX
                        + "test1."
                        + ConfigConstants.METRICS_REPORTER_SCOPE_DELIMITER,
                "-");
        config.setString(
                ConfigConstants.METRICS_REPORTER_PREFIX
                        + "test2."
                        + ConfigConstants.METRICS_REPORTER_CLASS_SUFFIX,
                TestReporter2.class.getName());
        config.setString(
                ConfigConstants.METRICS_REPORTER_PREFIX
                        + "test2."
                        + ConfigConstants.METRICS_REPORTER_SCOPE_DELIMITER,
                "!");

        MetricRegistryImpl testRegistry =
                new MetricRegistryImpl(
                        MetricRegistryTestUtils.fromConfiguration(config),
                        Arrays.asList(
                                ReporterSetup.forReporter(
                                        "test1", metricConfig1, new TestReporter1()),
                                ReporterSetup.forReporter(
                                        "test2", metricConfig2, new TestReporter2())));
        try {
            MetricGroup tmGroup =
                    TaskManagerMetricGroup.createTaskManagerMetricGroup(
                            testRegistry, "host", new ResourceID("id"));
            tmGroup.counter("1");
            assertEquals(
                    "Reporters were not properly instantiated",
                    2,
                    testRegistry.getReporters().size());
            for (MetricReporter reporter : testRegistry.getReporters()) {
                ScopeCheckingTestReporter typedReporter = (ScopeCheckingTestReporter) reporter;
                if (typedReporter.failureCause != null) {
                    throw typedReporter.failureCause;
                }
            }
        } finally {
            testRegistry.shutdown().get();
        }
    }

    @Test
    public void testLogicalScopeCachingForMultipleReporters() throws Exception {
        MetricRegistryImpl testRegistry =
                new MetricRegistryImpl(
                        MetricRegistryTestUtils.defaultMetricRegistryConfiguration(),
                        Arrays.asList(
                                ReporterSetup.forReporter("test1", new LogicalScopeReporter1()),
                                ReporterSetup.forReporter("test2", new LogicalScopeReporter2())));
        try {
            MetricGroup tmGroup =
                    TaskManagerMetricGroup.createTaskManagerMetricGroup(
                                    testRegistry, "host", new ResourceID("id"))
                            .addGroup("B")
                            .addGroup("C");
            tmGroup.counter("1");
            assertEquals(
                    "Reporters were not properly instantiated",
                    2,
                    testRegistry.getReporters().size());
            for (MetricReporter reporter : testRegistry.getReporters()) {
                ScopeCheckingTestReporter typedReporter = (ScopeCheckingTestReporter) reporter;
                if (typedReporter.failureCause != null) {
                    throw typedReporter.failureCause;
                }
            }
        } finally {
            testRegistry.shutdown().get();
        }
    }

    private abstract static class ScopeCheckingTestReporter extends TestReporter {
        protected Exception failureCause;

        @Override
        public void notifyOfAddedMetric(Metric metric, String metricName, MetricGroup group) {
            try {
                checkScopes(metric, metricName, group);
            } catch (Exception e) {
                if (failureCause == null) {
                    failureCause = e;
                }
            }
        }

        public abstract void checkScopes(Metric metric, String metricName, MetricGroup group);
    }

    /** Reporter that verifies the scope caching behavior. */
    public static class TestReporter1 extends ScopeCheckingTestReporter {
        @Override
        public String filterCharacters(String input) {
            return FILTER_B.filterCharacters(input);
        }

        @Override
        public void checkScopes(Metric metric, String metricName, MetricGroup group) {
            // the first call determines which filter is applied to all future calls; in this case
            // no filter is used at all
            assertEquals("A-B-C-D-1", group.getMetricIdentifier(metricName));
            // from now on the scope string is cached and should not be reliant on the given filter
            assertEquals("A-B-C-D-1", group.getMetricIdentifier(metricName, FILTER_C));
            assertEquals("A-B-C-D-1", group.getMetricIdentifier(metricName, this));
            // the metric name however is still affected by the filter as it is not cached
            assertEquals(
                    "A-B-C-D-4",
                    group.getMetricIdentifier(
                            metricName,
                            new CharacterFilter() {
                                @Override
                                public String filterCharacters(String input) {
                                    return input.replace("B", "X").replace("1", "4");
                                }
                            }));
        }
    }

    /** Reporter that verifies the scope caching behavior. */
    public static class TestReporter2 extends ScopeCheckingTestReporter {
        @Override
        public String filterCharacters(String input) {
            return FILTER_C.filterCharacters(input);
        }

        @Override
        public void checkScopes(Metric metric, String metricName, MetricGroup group) {
            // the first call determines which filter is applied to all future calls
            assertEquals("A!B!X!D!1", group.getMetricIdentifier(metricName, this));
            // from now on the scope string is cached and should not be reliant on the given filter
            assertEquals("A!B!X!D!1", group.getMetricIdentifier(metricName));
            assertEquals("A!B!X!D!1", group.getMetricIdentifier(metricName, FILTER_C));
            // the metric name however is still affected by the filter as it is not cached
            assertEquals(
                    "A!B!X!D!3",
                    group.getMetricIdentifier(
                            metricName,
                            new CharacterFilter() {
                                @Override
                                public String filterCharacters(String input) {
                                    return input.replace("A", "X").replace("1", "3");
                                }
                            }));
        }
    }

    /** Reporter that verifies the logical-scope caching behavior. */
    public static final class LogicalScopeReporter1 extends ScopeCheckingTestReporter {
        @Override
        public String filterCharacters(String input) {
            return FILTER_B.filterCharacters(input);
        }

        @Override
        public void checkScopes(Metric metric, String metricName, MetricGroup group) {
            final String logicalScope =
                    ((FrontMetricGroup<AbstractMetricGroup<?>>) group).getLogicalScope(this, '-');
            assertEquals("taskmanager-X-C", logicalScope);
        }
    }

    /** Reporter that verifies the logical-scope caching behavior. */
    public static final class LogicalScopeReporter2 extends ScopeCheckingTestReporter {
        @Override
        public String filterCharacters(String input) {
            return FILTER_C.filterCharacters(input);
        }

        @Override
        public void checkScopes(Metric metric, String metricName, MetricGroup group) {
            final String logicalScope =
                    ((FrontMetricGroup<AbstractMetricGroup<?>>) group).getLogicalScope(this, ',');
            assertEquals("taskmanager,B,X", logicalScope);
        }
    }

    @Test
    public void testScopeGenerationWithoutReporters() throws Exception {
        Configuration config = new Configuration();
        config.setString(MetricOptions.SCOPE_NAMING_TM, "A.B.C.D");
        MetricRegistryImpl testRegistry =
                new MetricRegistryImpl(MetricRegistryTestUtils.fromConfiguration(config));

        try {
            TaskManagerMetricGroup group =
                    TaskManagerMetricGroup.createTaskManagerMetricGroup(
                            testRegistry, "host", new ResourceID("id"));
            assertEquals(
                    "MetricReporters list should be empty", 0, testRegistry.getReporters().size());

            // default delimiter should be used
            assertEquals("A.B.X.D.1", group.getMetricIdentifier("1", FILTER_C));
            // no caching should occur
            assertEquals("A.X.C.D.1", group.getMetricIdentifier("1", FILTER_B));
            // invalid reporter indices do not throw errors
            assertEquals("A.X.C.D.1", group.getMetricIdentifier("1", FILTER_B, -1, '.'));
            assertEquals("A.X.C.D.1", group.getMetricIdentifier("1", FILTER_B, 2, '.'));
        } finally {
            testRegistry.shutdown().get();
        }
    }

    @Test
    public void testGetAllVariablesDoesNotDeadlock() throws InterruptedException {
        final BlockerSync parentSync = new BlockerSync();
        final BlockerSync childSync = new BlockerSync();

        AtomicReference<BlockerSync> syncRef = new AtomicReference<>();
        final MetricRegistry registry =
                TestingMetricRegistry.builder()
                        .setRegisterConsumer(
                                (metric, metricName, group) -> {
                                    syncRef.get().blockNonInterruptible();
                                    group.getAllVariables();
                                })
                        .build();

        final MetricGroup parent =
                new GenericMetricGroup(
                        registry,
                        UnregisteredMetricGroups.createUnregisteredTaskManagerMetricGroup(),
                        "parent");
        final MetricGroup child = parent.addGroup("child");

        final Thread parentRegisteringThread = new Thread(() -> parent.counter("parent_counter"));
        final Thread childRegisteringThread = new Thread(() -> child.counter("child_counter"));

        try {
            // start both threads and have them block in the registry, so they acquire the lock of
            // their respective group
            syncRef.set(childSync);
            childRegisteringThread.start();
            childSync.awaitBlocker();

            syncRef.set(parentSync);
            parentRegisteringThread.start();
            parentSync.awaitBlocker();

            // the parent thread remains blocked to simulate the child thread holding some lock in
            // the registry/reporter
            // the child thread continues execution and calls getAllVariables()
            // in the past this would block indefinitely since the method acquires the locks of all
            // parent groups
            childSync.releaseBlocker();
            // wait with a timeout to ensure the finally block is executed _at some point_,
            // un-blocking the parent
            childRegisteringThread.join(1000 * 10);

            parentSync.releaseBlocker();
            parentRegisteringThread.join();
        } finally {
            parentSync.releaseBlocker();
            childSync.releaseBlocker();
            parentRegisteringThread.join();
            childRegisteringThread.join();
        }
    }
}


text:
export interface ConsultTokenRequestModel {
  cardToken: string;
}


text:
"""WebSocket protocol versions 13 and 8."""

import collections
import json
import random
import re
import sys
import zlib
from enum import IntEnum
from struct import Struct

from .helpers import NO_EXTENSIONS
from .log import ws_logger

__all__ = ('WS_CLOSED_MESSAGE', 'WS_CLOSING_MESSAGE', 'WS_KEY',
           'WebSocketReader', 'WebSocketWriter', 'WSMessage',
           'WebSocketError', 'WSMsgType', 'WSCloseCode')

class WSCloseCode(IntEnum):
    OK = 1000
    GOING_AWAY = 1001
    PROTOCOL_ERROR = 1002
    UNSUPPORTED_DATA = 1003
    INVALID_TEXT = 1007
    POLICY_VIOLATION = 1008
    MESSAGE_TOO_BIG = 1009
    MANDATORY_EXTENSION = 1010
    INTERNAL_ERROR = 1011
    SERVICE_RESTART = 1012
    TRY_AGAIN_LATER = 1013

ALLOWED_CLOSE_CODES = {int(i) for i in WSCloseCode}

class WSMsgType(IntEnum):
    # websocket spec types
    CONTINUATION = 0x0
    TEXT = 0x1
    BINARY = 0x2
    PING = 0x9
    PONG = 0xa
    CLOSE = 0x8

    # aiohttp specific types
    CLOSING = 0x100
    CLOSED = 0x101
    ERROR = 0x102

    text = TEXT
    binary = BINARY
    ping = PING
    pong = PONG
    close = CLOSE
    closing = CLOSING
    closed = CLOSED
    error = ERROR

WS_KEY = b'258EAFA5-E914-47DA-95CA-C5AB0DC85B11'

UNPACK_LEN2 = Struct('!H').unpack_from
UNPACK_LEN3 = Struct('!Q').unpack_from
UNPACK_CLOSE_CODE = Struct('!H').unpack
PACK_LEN1 = Struct('!BB').pack
PACK_LEN2 = Struct('!BBH').pack
PACK_LEN3 = Struct('!BBQ').pack
PACK_CLOSE_CODE = Struct('!H').pack
MSG_SIZE = 2 ** 14
DEFAULT_LIMIT = 2 ** 16

_WSMessageBase = collections.namedtuple('_WSMessageBase',
                                        ['type', 'data', 'extra'])

class WSMessage(_WSMessageBase):

    def json(self, *, loads=json.loads):
        """Return parsed JSON data.

        .. versionadded:: 0.22
        """
        return loads(self.data)

WS_CLOSED_MESSAGE = WSMessage(WSMsgType.CLOSED, None, None)
WS_CLOSING_MESSAGE = WSMessage(WSMsgType.CLOSING, None, None)

class WebSocketError(Exception):
    """WebSocket protocol parser error."""

    def __init__(self, code, message):
        self.code = code
        super().__init__(message)

class WSHandshakeError(Exception):
    """WebSocket protocol handshake error."""

native_byteorder = sys.byteorder

# Used by _websocket_mask_python
_XOR_TABLE = [bytes(a ^ b for a in range(256)) for b in range(256)]

def _websocket_mask_python(mask, data):
    """Websocket masking function.

    `mask` is a `bytes` object of length 4; `data` is a `bytearray`
    object of any length. The contents of `data` are masked with `mask`,
    as specified in section 5.3 of RFC 6455.

    Note that this function mutates the `data` argument.

    This pure-python implementation may be replaced by an optimized
    version when available.

    """
    assert isinstance(data, bytearray), data
    assert len(mask) == 4, mask

    if data:
        a, b, c, d = (_XOR_TABLE[n] for n in mask)
        data[::4] = data[::4].translate(a)
        data[1::4] = data[1::4].translate(b)
        data[2::4] = data[2::4].translate(c)
        data[3::4] = data[3::4].translate(d)

if NO_EXTENSIONS:
    _websocket_mask = _websocket_mask_python
else:
    try:
        from ._websocket import _websocket_mask_cython  # type: ignore
        _websocket_mask = _websocket_mask_cython
    except ImportError:  # pragma: no cover
        _websocket_mask = _websocket_mask_python

_WS_DEFLATE_TRAILING = bytes([0x00, 0x00, 0xff, 0xff])

_WS_EXT_RE = re.compile(r'^(?:;\s*(?:'
                        r'(server_no_context_takeover)|'
                        r'(client_no_context_takeover)|'
                        r'(server_max_window_bits(?:=(\d+))?)|'
                        r'(client_max_window_bits(?:=(\d+))?)))*$')

_WS_EXT_RE_SPLIT = re.compile(r'permessage-deflate([^,]+)?')

def ws_ext_parse(extstr, isserver=False):
    if not extstr:
        return 0, False

    compress = 0
    notakeover = False
    for ext in _WS_EXT_RE_SPLIT.finditer(extstr):
        defext = ext.group(1)
        # Return compress = 15 when get `permessage-deflate`
        if not defext:
            compress = 15
            break
        match = _WS_EXT_RE.match(defext)
        if match:
            compress = 15
            if isserver:
                # Server never fail to detect compress handshake.
                # Server does not need to send max wbit to client
                if match.group(4):
                    compress = int(match.group(4))
                    # Group3 must match if group4 matches
                    # Compress wbit 8 does not support in zlib
                    # If compress level not support,
                    # CONTINUE to next extension
                    if compress > 15 or compress < 9:
                        compress = 0
                        continue
                if match.group(1):
                    notakeover = True
                # Ignore regex group 5 & 6 for client_max_window_bits
                break
            else:
                if match.group(6):
                    compress = int(match.group(6))
                    # Group5 must match if group6 matches
                    # Compress wbit 8 does not support in zlib
                    # If compress level not support,
                    # FAIL the parse progress
                    if compress > 15 or compress < 9:
                        raise WSHandshakeError('Invalid window size')
                if match.group(2):
                    notakeover = True
                # Ignore regex group 5 & 6 for client_max_window_bits
                break
        # Return Fail if client side and not match
        elif not isserver:
            raise WSHandshakeError('Extension for deflate not supported' +
                                   ext.group(1))

    return compress, notakeover

def ws_ext_gen(compress=15, isserver=False,
               server_notakeover=False):
    # client_notakeover=False not used for server
    # compress wbit 8 does not support in zlib
    if compress < 9 or compress > 15:
        raise ValueError('Compress wbits must between 9 and 15, '
                         'zlib does not support wbits=8')
    enabledext = ['permessage-deflate']
    if not isserver:
        enabledext.append('client_max_window_bits')

    if compress < 15:
        enabledext.append('server_max_window_bits=' + str(compress))
    if server_notakeover:
        enabledext.append('server_no_context_takeover')
    # if client_notakeover:
    #     enabledext.append('client_no_context_takeover')
    return '; '.join(enabledext)

class WSParserState(IntEnum):
    READ_HEADER = 1
    READ_PAYLOAD_LENGTH = 2
    READ_PAYLOAD_MASK = 3
    READ_PAYLOAD = 4

class WebSocketReader:

    def __init__(self, queue, max_msg_size, compress=True):
        self.queue = queue
        self._max_msg_size = max_msg_size

        self._exc = None
        self._partial = bytearray()
        self._state = WSParserState.READ_HEADER

        self._opcode = None
        self._frame_fin = False
        self._frame_opcode = None
        self._frame_payload = bytearray()

        self._tail = b''
        self._has_mask = False
        self._frame_mask = None
        self._payload_length = 0
        self._payload_length_flag = 0
        self._compressed = None
        self._decompressobj = None
        self._compress = compress

    def feed_eof(self):
        self.queue.feed_eof()

    def feed_data(self, data):
        if self._exc:
            return True, data

        try:
            return self._feed_data(data)
        except Exception as exc:
            self._exc = exc
            self.queue.set_exception(exc)
            return True, b''

    def _feed_data(self, data):
        for fin, opcode, payload, compressed in self.parse_frame(data):
            if compressed and not self._decompressobj:
                self._decompressobj = zlib.decompressobj(wbits=-zlib.MAX_WBITS)
            if opcode == WSMsgType.CLOSE:
                if len(payload) >= 2:
                    close_code = UNPACK_CLOSE_CODE(payload[:2])[0]
                    if (close_code < 3000 and
                            close_code not in ALLOWED_CLOSE_CODES):
                        raise WebSocketError(
                            WSCloseCode.PROTOCOL_ERROR,
                            'Invalid close code: {}'.format(close_code))
                    try:
                        close_message = payload[2:].decode('utf-8')
                    except UnicodeDecodeError as exc:
                        raise WebSocketError(
                            WSCloseCode.INVALID_TEXT,
                            'Invalid UTF-8 text message') from exc
                    msg = WSMessage(WSMsgType.CLOSE, close_code, close_message)
                elif payload:
                    raise WebSocketError(
                        WSCloseCode.PROTOCOL_ERROR,
                        'Invalid close frame: {} {} {!r}'.format(
                            fin, opcode, payload))
                else:
                    msg = WSMessage(WSMsgType.CLOSE, 0, '')

                self.queue.feed_data(msg, 0)

            elif opcode == WSMsgType.PING:
                self.queue.feed_data(
                    WSMessage(WSMsgType.PING, payload, ''), len(payload))

            elif opcode == WSMsgType.PONG:
                self.queue.feed_data(
                    WSMessage(WSMsgType.PONG, payload, ''), len(payload))

            elif opcode not in (
                    WSMsgType.TEXT, WSMsgType.BINARY) and self._opcode is None:
                raise WebSocketError(
                    WSCloseCode.PROTOCOL_ERROR,
                    "Unexpected opcode={!r}".format(opcode))
            else:
                # load text/binary
                if not fin:
                    # got partial frame payload
                    if opcode != WSMsgType.CONTINUATION:
                        self._opcode = opcode
                    self._partial.extend(payload)
                    if (self._max_msg_size and
                            len(self._partial) >= self._max_msg_size):
                        raise WebSocketError(
                            WSCloseCode.MESSAGE_TOO_BIG,
                            "Message size {} exceeds limit {}".format(
                                len(self._partial), self._max_msg_size))
                else:
                    # previous frame was non finished
                    # we should get continuation opcode
                    if self._partial:
                        if opcode != WSMsgType.CONTINUATION:
                            raise WebSocketError(
                                WSCloseCode.PROTOCOL_ERROR,
                                'The opcode in non-fin frame is expected '
                                'to be zero, got {!r}'.format(opcode))

                    if opcode == WSMsgType.CONTINUATION:
                        opcode = self._opcode
                        self._opcode = None

                    self._partial.extend(payload)
                    if (self._max_msg_size and
                            len(self._partial) >= self._max_msg_size):
                        raise WebSocketError(
                            WSCloseCode.MESSAGE_TOO_BIG,
                            "Message size {} exceeds limit {}".format(
                                len(self._partial), self._max_msg_size))

                    # Decompress process must to be done after all packets
                    # received.
                    if compressed:
                        self._partial.extend(_WS_DEFLATE_TRAILING)
                        payload_merged = self._decompressobj.decompress(
                            self._partial, self._max_msg_size)
                        if self._decompressobj.unconsumed_tail:
                            left = len(self._decompressobj.unconsumed_tail)
                            raise WebSocketError(
                                WSCloseCode.MESSAGE_TOO_BIG,
                                "Decompressed message size exceeds limit {}".
                                format(self._max_msg_size + left,
                                       self._max_msg_size))
                    else:
                        payload_merged = bytes(self._partial)

                    self._partial.clear()

                    if opcode == WSMsgType.TEXT:
                        try:
                            text = payload_merged.decode('utf-8')
                            self.queue.feed_data(
                                WSMessage(WSMsgType.TEXT, text, ''), len(text))
                        except UnicodeDecodeError as exc:
                            raise WebSocketError(
                                WSCloseCode.INVALID_TEXT,
                                'Invalid UTF-8 text message') from exc
                    else:
                        self.queue.feed_data(
                            WSMessage(WSMsgType.BINARY, payload_merged, ''),
                            len(payload_merged))

        return False, b''

    def parse_frame(self, buf):
        """Return the next frame from the socket."""
        frames = []
        if self._tail:
            buf, self._tail = self._tail + buf, b''

        start_pos = 0
        buf_length = len(buf)

        while True:
            # read header
            if self._state == WSParserState.READ_HEADER:
                if buf_length - start_pos >= 2:
                    data = buf[start_pos:start_pos+2]
                    start_pos += 2
                    first_byte, second_byte = data

                    fin = (first_byte >> 7) & 1
                    rsv1 = (first_byte >> 6) & 1
                    rsv2 = (first_byte >> 5) & 1
                    rsv3 = (first_byte >> 4) & 1
                    opcode = first_byte & 0xf

                    # frame-fin = %x0 ; more frames of this message follow
                    #           / %x1 ; final frame of this message
                    # frame-rsv1 = %x0 ;
                    #    1 bit, MUST be 0 unless negotiated otherwise
                    # frame-rsv2 = %x0 ;
                    #    1 bit, MUST be 0 unless negotiated otherwise
                    # frame-rsv3 = %x0 ;
                    #    1 bit, MUST be 0 unless negotiated otherwise
                    #
                    # Remove rsv1 from this test for deflate development
                    if rsv2 or rsv3 or (rsv1 and not self._compress):
                        raise WebSocketError(
                            WSCloseCode.PROTOCOL_ERROR,
                            'Received frame with non-zero reserved bits')

                    if opcode > 0x7 and fin == 0:
                        raise WebSocketError(
                            WSCloseCode.PROTOCOL_ERROR,
                            'Received fragmented control frame')

                    has_mask = (second_byte >> 7) & 1
                    length = second_byte & 0x7f

                    # Control frames MUST have a payload
                    # length of 125 bytes or less
                    if opcode > 0x7 and length > 125:
                        raise WebSocketError(
                            WSCloseCode.PROTOCOL_ERROR,
                            'Control frame payload cannot be '
                            'larger than 125 bytes')

                    # Set compress status if last package is FIN
                    # OR set compress status if this is first fragment
                    # Raise error if not first fragment with rsv1 = 0x1
                    if self._frame_fin or self._compressed is None:
                        self._compressed = True if rsv1 else False
                    elif rsv1:
                        raise WebSocketError(
                            WSCloseCode.PROTOCOL_ERROR,
                            'Received frame with non-zero reserved bits')

                    self._frame_fin = fin
                    self._frame_opcode = opcode
                    self._has_mask = has_mask
                    self._payload_length_flag = length
                    self._state = WSParserState.READ_PAYLOAD_LENGTH
                else:
                    break

            # read payload length
            if self._state == WSParserState.READ_PAYLOAD_LENGTH:
                length = self._payload_length_flag
                if length == 126:
                    if buf_length - start_pos >= 2:
                        data = buf[start_pos:start_pos+2]
                        start_pos += 2
                        length = UNPACK_LEN2(data)[0]
                        self._payload_length = length
                        self._state = (
                            WSParserState.READ_PAYLOAD_MASK
                            if self._has_mask
                            else WSParserState.READ_PAYLOAD)
                    else:
                        break
                elif length > 126:
                    if buf_length - start_pos >= 8:
                        data = buf[start_pos:start_pos+8]
                        start_pos += 8
                        length = UNPACK_LEN3(data)[0]
                        self._payload_length = length
                        self._state = (
                            WSParserState.READ_PAYLOAD_MASK
                            if self._has_mask
                            else WSParserState.READ_PAYLOAD)
                    else:
                        break
                else:
                    self._payload_length = length
                    self._state = (
                        WSParserState.READ_PAYLOAD_MASK
                        if self._has_mask
                        else WSParserState.READ_PAYLOAD)

            # read payload mask
            if self._state == WSParserState.READ_PAYLOAD_MASK:
                if buf_length - start_pos >= 4:
                    self._frame_mask = buf[start_pos:start_pos+4]
                    start_pos += 4
                    self._state = WSParserState.READ_PAYLOAD
                else:
                    break

            if self._state == WSParserState.READ_PAYLOAD:
                length = self._payload_length
                payload = self._frame_payload

                chunk_len = buf_length - start_pos
                if length >= chunk_len:
                    self._payload_length = length - chunk_len
                    payload.extend(buf[start_pos:])
                    start_pos = buf_length
                else:
                    self._payload_length = 0
                    payload.extend(buf[start_pos:start_pos+length])
                    start_pos = start_pos + length

                if self._payload_length == 0:
                    if self._has_mask:
                        _websocket_mask(self._frame_mask, payload)

                    frames.append((
                        self._frame_fin,
                        self._frame_opcode,
                        payload,
                        self._compressed))

                    self._frame_payload = bytearray()
                    self._state = WSParserState.READ_HEADER
                else:
                    break

        self._tail = buf[start_pos:]

        return frames

class WebSocketWriter:

    def __init__(self, protocol, transport, *,
                 use_mask=False, limit=DEFAULT_LIMIT, random=random.Random(),
                 compress=0, notakeover=False):
        self.protocol = protocol
        self.transport = transport
        self.use_mask = use_mask
        self.randrange = random.randrange
        self.compress = compress
        self.notakeover = notakeover
        self._closing = False
        self._limit = limit
        self._output_size = 0
        self._compressobj = None

    async def _send_frame(self, message, opcode, compress=None):
        """Send a frame over the websocket with message as its payload."""
        if self._closing:
            ws_logger.warning('websocket connection is closing.')

        rsv = 0

        # Only compress larger packets (disabled)
        # Does small packet needs to be compressed?
        # if self.compress and opcode < 8 and len(message) > 124:
        if (compress or self.compress) and opcode < 8:
            if compress:
                # Do not set self._compress if compressing is for this frame
                compressobj = zlib.compressobj(wbits=-compress)
            else:  # self.compress
                if not self._compressobj:
                    self._compressobj = zlib.compressobj(wbits=-self.compress)
                compressobj = self._compressobj

            message = compressobj.compress(message)
            message = message + compressobj.flush(
                zlib.Z_FULL_FLUSH if self.notakeover else zlib.Z_SYNC_FLUSH)
            if message.endswith(_WS_DEFLATE_TRAILING):
                message = message[:-4]
            rsv = rsv | 0x40

        msg_length = len(message)

        use_mask = self.use_mask
        if use_mask:
            mask_bit = 0x80
        else:
            mask_bit = 0

        if msg_length < 126:
            header = PACK_LEN1(0x80 | rsv | opcode, msg_length | mask_bit)
        elif msg_length < (1 << 16):
            header = PACK_LEN2(0x80 | rsv | opcode, 126 | mask_bit, msg_length)
        else:
            header = PACK_LEN3(0x80 | rsv | opcode, 127 | mask_bit, msg_length)
        if use_mask:
            mask = self.randrange(0, 0xffffffff)
            mask = mask.to_bytes(4, 'big')
            message = bytearray(message)
            _websocket_mask(mask, message)
            self.transport.write(header + mask + message)
            self._output_size += len(header) + len(mask) + len(message)
        else:
            if len(message) > MSG_SIZE:
                self.transport.write(header)
                self.transport.write(message)
            else:
                self.transport.write(header + message)

            self._output_size += len(header) + len(message)

        if self._output_size > self._limit:
            self._output_size = 0
            await self.protocol._drain_helper()

    async def pong(self, message=b''):
        """Send pong message."""
        if isinstance(message, str):
            message = message.encode('utf-8')
        return await self._send_frame(message, WSMsgType.PONG)

    async def ping(self, message=b''):
        """Send ping message."""
        if isinstance(message, str):
            message = message.encode('utf-8')
        return await self._send_frame(message, WSMsgType.PING)

    async def send(self, message, binary=False, compress=None):
        """Send a frame over the websocket with message as its payload."""
        if isinstance(message, str):
            message = message.encode('utf-8')
        if binary:
            return await self._send_frame(message, WSMsgType.BINARY, compress)
        else:
            return await self._send_frame(message, WSMsgType.TEXT, compress)

    async def close(self, code=1000, message=b''):
        """Close the websocket, sending the specified code and message."""
        if isinstance(message, str):
            message = message.encode('utf-8')
        try:
            return await self._send_frame(
                PACK_CLOSE_CODE(code) + message, opcode=WSMsgType.CLOSE)
        finally:
            self._closing = True


text:
package config

import (
	"path/filepath"
)

const (
	ContainerIPStorePrefix    = "/jdjr/containers"
	ContainerDomainsStorePath = "/jdjr/container-domains"
	HostAssignedIPStorePath   = "/jdjr/hosts/assigned"
)

func GetHostIPConfigStorePath(ip string) string {
	return filepath.Join("/jdjr/hosts/config", ip)
}

func ContainerIPPoolSotrePath(ipNet string) string {
	return filepath.Join(ContainerIPStorePrefix, ipNet, "pool")
}

func ContainerAssignedIPSotrePath(ipNet string) string {
	return filepath.Join(ContainerIPStorePrefix, ipNet, "assigned")
}

func ContainerIPConfigSotrePath(ipNet string) string {
	return filepath.Join(ContainerIPStorePrefix, ipNet, "config")
}


text:
using System;

namespace SanAndreasUnity.Importing.Items.Definitions
{
    [Flags]
    public enum ObjectFlag : uint
    {
        None = 0,
        WetEffect = 1,
        RenderAtNight = 2,
        Alpha1 = 4,
        Alpha2 = 8,
        RenderAtDay = 16,
        Interior = 32,
        DisableShadowMesh = 64,
        NoCull = 128,
        DisableDrawDist = 256,
        Breakable = 512,
        BreakableCrack = 1024,
        GarageDoor = 2048,
        MultiClumpCollide = 4096,
        WeatherBrightness = 32768,
        ExplodeHit = 65536,
        MultiClumpSpray = 1048576,
        NoBackCull = 2097152
    }

    [Section("objs")]
    public class ObjectDef : Definition, IObjectDefinition
    {
        public readonly int Id;

        int IObjectDefinition.Id
        {
            get { return Id; }
        }

        public readonly string ModelName;
        public readonly string TextureDictionaryName;

        public readonly float DrawDist;
        public readonly ObjectFlag Flags;

        public ObjectDef(string line) : base(line)
        {
            Id = GetInt(0);
            ModelName = GetString(1);
            TextureDictionaryName = GetString(2);
            DrawDist = GetSingle(3);
            Flags = (ObjectFlag) GetInt(4);
        }

        public bool HasFlag(ObjectFlag flag)
        {
            return (Flags & flag) == flag;
        }
    }
}


text:
package e2enode

import (
	"fmt"
	"time"

	"github.com/onsi/ginkgo/v2"
	"github.com/onsi/gomega"
	"github.com/onsi/gomega/gstruct"
	"github.com/onsi/gomega/types"

	v1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/resource"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	kubeletconfig "k8s.io/kubernetes/pkg/kubelet/apis/config"
	"k8s.io/kubernetes/pkg/kubelet/cm/cpumanager"
	"k8s.io/kubernetes/pkg/kubelet/cm/cpuset"
	"k8s.io/kubernetes/test/e2e/framework"
	e2emetrics "k8s.io/kubernetes/test/e2e/framework/metrics"
	e2epod "k8s.io/kubernetes/test/e2e/framework/pod"
	e2eskipper "k8s.io/kubernetes/test/e2e/framework/skipper"
	admissionapi "k8s.io/pod-security-admission/api"
)

var _ = SIGDescribe("CPU Manager Metrics [Serial][Feature:CPUManager]", func() {
	f := framework.NewDefaultFramework("cpumanager-metrics")
	f.NamespacePodSecurityEnforceLevel = admissionapi.LevelPrivileged

	ginkgo.Context("when querying /metrics", func() {
		var oldCfg *kubeletconfig.KubeletConfiguration
		var testPod *v1.Pod
		var smtLevel int

		ginkgo.BeforeEach(func() {
			var err error
			if oldCfg == nil {
				oldCfg, err = getCurrentKubeletConfig()
				framework.ExpectNoError(err)
			}

			fullCPUsOnlyOpt := fmt.Sprintf("option=%s", cpumanager.FullPCPUsOnlyOption)
			_, cpuAlloc, _ := getLocalNodeCPUDetails(f)
			smtLevel = getSMTLevel()

			// strict SMT alignment is trivially verified and granted on non-SMT systems
			if smtLevel < 2 {
				e2eskipper.Skipf("Skipping CPU Manager %s tests since SMT disabled", fullCPUsOnlyOpt)
			}

			// our tests want to allocate up to a full core, so we need at last 2*2=4 virtual cpus
			if cpuAlloc < int64(smtLevel*2) {
				e2eskipper.Skipf("Skipping CPU Manager %s tests since the CPU capacity < 4", fullCPUsOnlyOpt)
			}

			framework.Logf("SMT level %d", smtLevel)

			// TODO: we assume the first available CPUID is 0, which is pretty fair, but we should probably
			// check what we do have in the node.
			cpuPolicyOptions := map[string]string{
				cpumanager.FullPCPUsOnlyOption: "true",
			}
			newCfg := configureCPUManagerInKubelet(oldCfg,
				&cpuManagerKubeletArguments{
					policyName:              string(cpumanager.PolicyStatic),
					reservedSystemCPUs:      cpuset.NewCPUSet(0),
					enableCPUManagerOptions: true,
					options:                 cpuPolicyOptions,
				},
			)
			updateKubeletConfig(f, newCfg, true)
		})

		ginkgo.AfterEach(func() {
			if testPod != nil {
				deletePodSyncByName(f, testPod.Name)
			}
			updateKubeletConfig(f, oldCfg, true)
		})

		ginkgo.It("should report zero pinning counters after a fresh restart", func() {
			// we updated the kubelet config in BeforeEach, so we can assume we start fresh.
			// being [Serial], we can also assume noone else but us is running pods.
			ginkgo.By("Checking the cpumanager metrics right after the kubelet restart, with no pods running")

			matchResourceMetrics := gstruct.MatchKeys(gstruct.IgnoreExtras, gstruct.Keys{
				"kubelet_cpu_manager_pinning_requests_total": gstruct.MatchAllElements(nodeID, gstruct.Elements{
					"": timelessSample(0),
				}),
				"kubelet_cpu_manager_pinning_errors_total": gstruct.MatchAllElements(nodeID, gstruct.Elements{
					"": timelessSample(0),
				}),
			})

			ginkgo.By("Giving the Kubelet time to start up and produce metrics")
			gomega.Eventually(getCPUManagerMetrics, 1*time.Minute, 15*time.Second).Should(matchResourceMetrics)
			ginkgo.By("Ensuring the metrics match the expectations a few more times")
			gomega.Consistently(getCPUManagerMetrics, 1*time.Minute, 15*time.Second).Should(matchResourceMetrics)
		})

		ginkgo.It("should report pinning failures when the cpumanager allocation is known to fail", func() {
			ginkgo.By("Creating the test pod which will be rejected for SMTAlignmentError")
			testPod = e2epod.NewPodClient(f).Create(makeGuaranteedCPUExclusiveSleeperPod("smt-align-err", 1))

			// we updated the kubelet config in BeforeEach, so we can assume we start fresh.
			// being [Serial], we can also assume noone else but us is running pods.
			ginkgo.By("Checking the cpumanager metrics right after the kubelet restart, with pod failed to admit")

			matchResourceMetrics := gstruct.MatchKeys(gstruct.IgnoreExtras, gstruct.Keys{
				"kubelet_cpu_manager_pinning_requests_total": gstruct.MatchAllElements(nodeID, gstruct.Elements{
					"": timelessSample(1),
				}),
				"kubelet_cpu_manager_pinning_errors_total": gstruct.MatchAllElements(nodeID, gstruct.Elements{
					"": timelessSample(1),
				}),
			})

			ginkgo.By("Giving the Kubelet time to start up and produce metrics")
			gomega.Eventually(getCPUManagerMetrics, 1*time.Minute, 15*time.Second).Should(matchResourceMetrics)
			ginkgo.By("Ensuring the metrics match the expectations a few more times")
			gomega.Consistently(getCPUManagerMetrics, 1*time.Minute, 15*time.Second).Should(matchResourceMetrics)
		})

		ginkgo.It("should not report any pinning failures when the cpumanager allocation is expected to succeed", func() {
			ginkgo.By("Creating the test pod")
			testPod = e2epod.NewPodClient(f).Create(makeGuaranteedCPUExclusiveSleeperPod("smt-align-ok", smtLevel))

			// we updated the kubelet config in BeforeEach, so we can assume we start fresh.
			// being [Serial], we can also assume noone else but us is running pods.
			ginkgo.By("Checking the cpumanager metrics right after the kubelet restart, with pod should be admitted")

			matchResourceMetrics := gstruct.MatchKeys(gstruct.IgnoreExtras, gstruct.Keys{
				"kubelet_cpu_manager_pinning_requests_total": gstruct.MatchAllElements(nodeID, gstruct.Elements{
					"": timelessSample(1),
				}),
				"kubelet_cpu_manager_pinning_errors_total": gstruct.MatchAllElements(nodeID, gstruct.Elements{
					"": timelessSample(0),
				}),
			})

			ginkgo.By("Giving the Kubelet time to start up and produce metrics")
			gomega.Eventually(getCPUManagerMetrics, 1*time.Minute, 15*time.Second).Should(matchResourceMetrics)
			ginkgo.By("Ensuring the metrics match the expectations a few more times")
			gomega.Consistently(getCPUManagerMetrics, 1*time.Minute, 15*time.Second).Should(matchResourceMetrics)
		})
	})
})

func getCPUManagerMetrics() (e2emetrics.KubeletMetrics, error) {
	// we are running out of good names, so we need to be unnecessarily specific to avoid clashes
	ginkgo.By("getting CPU Manager metrics from the metrics API")
	return e2emetrics.GrabKubeletMetricsWithoutProxy(framework.TestContext.NodeName+":10255", "/metrics")
}

func makeGuaranteedCPUExclusiveSleeperPod(name string, cpus int) *v1.Pod {
	return &v1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			Name: name + "-pod",
		},
		Spec: v1.PodSpec{
			RestartPolicy: v1.RestartPolicyNever,
			Containers: []v1.Container{
				{
					Name:  name + "-cnt",
					Image: busyboxImage,
					Resources: v1.ResourceRequirements{
						Requests: v1.ResourceList{
							v1.ResourceCPU:    resource.MustParse(fmt.Sprintf("%d", cpus)),
							v1.ResourceMemory: resource.MustParse("64Mi"),
						},
						Limits: v1.ResourceList{
							v1.ResourceCPU:    resource.MustParse(fmt.Sprintf("%d", cpus)),
							v1.ResourceMemory: resource.MustParse("64Mi"),
						},
					},
					Command: []string{"sh", "-c", "sleep", "1d"},
				},
			},
		},
	}
}

func timelessSample(value interface{}) types.GomegaMatcher {
	return gstruct.PointTo(gstruct.MatchAllFields(gstruct.Fields{
		// We already check Metric when matching the Id
		"Metric":    gstruct.Ignore(),
		"Value":     gomega.BeNumerically("==", value),
		"Timestamp": gstruct.Ignore(),
	}))
}


text:
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/skip';
import 'rxjs/add/operator/takeUntil';
import { from } from 'rxjs/observable/from';
import { Injectable } from '@angular/core';
import { Effect, Actions } from '@ngrx/effects';
import { Action, Store } from '@ngrx/store';
import { Observable } from 'rxjs/Observable';
import { EventsService } from '../../../services/schedule';
import {
  TIMEOFFS_GET,
  UPDATE_TIMEOFFS_STATUSES_AND_FETCH,
  TimeoffsGetAction,
  TimeoffsGetCompleteAction,
  TimeoffsErrorAction,
} from '../../actions/schedule/timeoffs';
import { ErrorsAction } from '../../actions/errors';
import { IState as IStoreState } from '../../reducers';

@Injectable()
export class TimeoffsEffects {
  @Effect() private fetchTimeoffs$: Observable<Action> = this.actions$
    .ofType(TIMEOFFS_GET)
    .debounceTime(300)
    .withLatestFrom(this.store, (action, state) =>
      ({ action, token: state.session.sessionObject.authorization_token }))
    .switchMap(({ action, token }: { action: TimeoffsGetAction, token: string }) => {
      return this.eventsService.getTimeoffs(action.payload, token)
        .map((response) => {
          if (action.successCallback) {
            action.successCallback();
          }
          return new TimeoffsGetCompleteAction(response);
        })
        .catch((err) => from([
          new TimeoffsErrorAction(),
          new ErrorsAction(err.json(), err.status),
        ]));
    });

  @Effect() private updateTimeoffsStatusesAndFetch$: Observable<Action> = this.actions$
    .ofType(UPDATE_TIMEOFFS_STATUSES_AND_FETCH)
    .debounceTime(300)
    .withLatestFrom(this.store, (action, state) =>
      ({ action, token: state.session.sessionObject.authorization_token }))
    .switchMap(({ action, token }: { action: any, token: string }) => {
      return this.eventsService.updateTimeoffsStatuses(action.payload.updatePayload, token)
        .map(() => {
          if (action.payload.successCallback) {
            action.payload.successCallback();
          }
          return new TimeoffsGetAction(action.payload.filter);
        })
        .catch((err) => from([
          new TimeoffsErrorAction(),
          new ErrorsAction(err.json(), err.status),
        ]));
    });

  constructor(
    private actions$: Actions,
    private eventsService: EventsService,
    private store: Store<IStoreState>,
  ) { }
}


text:
Any assets your custom module might contain (images, video, icons,...)
reside in this directory.


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.07.10 at 01:22:30 오후 KST
//

package org.onem2m.xml.protocols;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

/**
 *
Java class for anyArgType complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="anyArgType">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}NCName"/>
 *         <element name="value" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "anyArgType", propOrder = {
    "name",
    "value"
})
public class AnyArgType {

    @XmlElement(required = true)
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "NCName")
    protected String name;
    @XmlElement(required = true)
    protected Object value;

    /**
     * Gets the value of the name property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getName() {
        return name;
    }

    /**
     * Sets the value of the name property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setName(String value) {
        this.name = value;
    }

    /**
     * Gets the value of the value property.
     *
     * @return
     *     possible object is
     *     {@link Object }
     *
     */
    public Object getValue() {
        return value;
    }

    /**
     * Sets the value of the value property.
     *
     * @param value
     *     allowed object is
     *     {@link Object }
     *
     */
    public void setValue(Object value) {
        this.value = value;
    }

}


text:
Validate that an image is well-formed

```
crane validate [flags]
```

### Options

```
      --fast             Skip downloading/digesting layers
  -h, --help             help for validate
      --remote string    Name of remote image to validate
      --tarball string   Path to tarball to validate
```

### Options inherited from parent commands

```
      --allow-nondistributable-artifacts   Allow pushing non-distributable (foreign) layers
      --insecure                           Allow image references to be fetched without TLS
      --platform platform                  Specifies the platform in the form os/arch[/variant][:osversion] (e.g. linux/amd64). (default all)
  -v, --verbose                            Enable debug logs
```

### SEE ALSO

* [crane](crane.md)	 - Crane is a tool for managing container images


text:
<?xml version="1.0"?>
<LayoutRoot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" PanelVersion="2">
  <RootPanel Orientation="Horizontal">
    <LayoutAnchorablePane DockWidth="637.6" DocMinWidth="100">
      <LayoutAnchorable CanHide="False" AutoHideWidth="300" AutoHideMinWidth="100" AutoHideMinHeight="100" Title="Grid" IsSelected="True" ContentId="pgrid" CanClose="False" LastActivationTimeStamp="05/29/2016 12:43:24" />
    </LayoutAnchorablePane>
    <LayoutDocumentPane DockWidth="0.628478950388084*" />
  </RootPanel>
  <TopSide />
  <RightSide />
  <LeftSide>
    <LayoutAnchorGroup>
      <LayoutAnchorable CanHide="False" AutoHideMinWidth="100" AutoHideMinHeight="100" Title="Flag" ContentId="pflag" CanClose="False" LastActivationTimeStamp="05/29/2016 12:50:22" />
    </LayoutAnchorGroup>
  </LeftSide>
  <BottomSide />
  <FloatingWindows />
  <Hidden />
</LayoutRoot>


text:
package commands

import (
	"github.com/brooklyncentral/brooklyn-cli/net"
)

type CatalogPolicies struct {
	network *net.Network
}

func NewCatalogPolicies(network *net.Network) (cmd *CatalogPolicies) {
	cmd = new(CatalogPolicies)
	cmd.network = network
	return
}


text:
/*
NOTE: THIS TEST ONLY WORKS WITH WAC RUNTIMES.
*/
window.onload = function WACtest() {
    if (window.deviceapis) {

        var feature_name = "feature:a9bb79c1";
        var param_name   = "TEST";
        var param_value  = "The arrow should point right -->";
        var title        = document.title;
        var body         = document.body;
        var verdict      = document.getElementById("verdict");
        var reason       = document.getElementById("reason");

        function pass(message) {
            title = "PASS";
            body.style.background = "green";
            verdict.innerHTML = "PASS";
            reason.innerHTML = message;
        }

        function fail(message) {
            title = "FAIL";
            body.style.background = "red";
            verdict.innerHTML = "FAIL";
            reason.innerHTML = message;
        }

        try {
            var features = window.deviceapis.listActivatedFeatures();
            for (var i = 0; i < features.length; i++) {
                if (features[i].uri == feature_name) {
                    var params = features[i].params;
                    for (var j = 0; j < params.length; j++) {
                        if (params[j].name === param_name) {
                            if (params[j].value === param_value){
                                pass("The \"" + param_name + "\" param's value attribute matched \"" + param_value + "\"");
                                return;
                            } else {
                                fail("The \"" + param_name + "\" param's value attribute was \"" + params[j].value + "\". It should be \"" + param_value + "\"");
                                return;
                            }
                        }
                    }
                    fail("The \"" + param_name + "\" param was not found.");
                    return;
                }
            }
            fail("Feature \"" + feature_name + "\" was not found.");
        } catch (e) {
            fail(e);
        }

    }
}


text:
/*****************************************************************************\
Simple ensure authenticated middleware, which is responsible for validating
that a user is authenticated, else forwards to the login page.
\*****************************************************************************/
module.exports = function(request, response, next_route) {
    if(request.isAuthenticated()) {
        return next_route();
    } else {
        response.redirect('/login');
    }
};


text:
@interface DetailsViewController : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *screenNameLabel;
@property (weak, nonatomic) IBOutlet UITextField *tweetTextField;

@end


text:
fail ()
{
  echo "Test failed: $*"
  exit 1
}

echo_v ()
{
  if [ "$verbose" = "1" ]; then
    echo "$*"
  fi
}

error_out=/dev/null
if [ "$1" = "-v" ]; then
  verbose=1
  error_out=/dev/stderr
fi
for I in ${srcdir:-.}/collate/*.in; do
  echo_v "Sorting $I"
  name=`basename $I .in`
  ./unicode-collate $I > collate.out
  if [ $? -eq 2 ]; then
    exit 0
  fi
  diff collate.out ${srcdir:-.}/collate/$name.unicode ||
    fail "unexpected error when using g_utf8_collate() on $I"
  ./unicode-collate --key $I > collate.out
  diff collate.out ${srcdir:-.}/collate/$name.unicode ||
    fail "unexpected error when using g_utf8_collate_key() on $I"
  ./unicode-collate --file $I > collate.out
  diff collate.out ${srcdir:-.}/collate/$name.file ||
    fail "unexpected error when using g_utf8_collate_key_for_filename() on $I"
done

echo_v "All tests passed."