text:
#include "svga_cmd.h"

#include "pipe/p_state.h"
#include "pipe/p_defines.h"
#include "util/u_inlines.h"
#include "os/os_thread.h"
#include "util/u_format.h"
#include "util/u_math.h"
#include "util/u_memory.h"

#include "svga_format.h"
#include "svga_screen.h"
#include "svga_context.h"
#include "svga_resource_texture.h"
#include "svga_surface.h"
#include "svga_debug.h"

void
svga_texture_copy_handle(struct svga_context *svga,
                         struct svga_winsys_surface *src_handle,
                         unsigned src_x, unsigned src_y, unsigned src_z,
                         unsigned src_level, unsigned src_face,
                         struct svga_winsys_surface *dst_handle,
                         unsigned dst_x, unsigned dst_y, unsigned dst_z,
                         unsigned dst_level, unsigned dst_face,
                         unsigned width, unsigned height, unsigned depth)
{
   struct svga_surface dst, src;
   enum pipe_error ret;
   SVGA3dCopyBox box, *boxes;

   assert(svga);

   src.handle = src_handle;
   src.real_level = src_level;
   src.real_face = src_face;
   src.real_zslice = 0;

   dst.handle = dst_handle;
   dst.real_level = dst_level;
   dst.real_face = dst_face;
   dst.real_zslice = 0;

   box.x = dst_x;
   box.y = dst_y;
   box.z = dst_z;
   box.w = width;
   box.h = height;
   box.d = depth;
   box.srcx = src_x;
   box.srcy = src_y;
   box.srcz = src_z;

/*
   SVGA_DBG(DEBUG_VIEWS, "mipcopy src: %p %u (%ux%ux%u), dst: %p %u (%ux%ux%u)\n",
            src_handle, src_level, src_x, src_y, src_z,
            dst_handle, dst_level, dst_x, dst_y, dst_z);
*/

   ret = SVGA3D_BeginSurfaceCopy(svga->swc,
                                 &src.base,
                                 &dst.base,
                                 &boxes, 1);
   if (ret != PIPE_OK) {
      svga_context_flush(svga, NULL);
      ret = SVGA3D_BeginSurfaceCopy(svga->swc,
                                    &src.base,
                                    &dst.base,
                                    &boxes, 1);
      assert(ret == PIPE_OK);
   }
   *boxes = box;
   SVGA_FIFOCommitAll(svga->swc);
}

struct svga_winsys_surface *
svga_texture_view_surface(struct svga_context *svga,
                          struct svga_texture *tex,
                          SVGA3dSurfaceFlags flags,
                          SVGA3dSurfaceFormat format,
                          unsigned start_mip,
                          unsigned num_mip,
                          int face_pick,
                          int zslice_pick,
                          struct svga_host_surface_cache_key *key) /* OUT */
{
   struct svga_screen *ss = svga_screen(svga->pipe.screen);
   struct svga_winsys_surface *handle;
   uint32_t i, j;
   unsigned z_offset = 0;

   SVGA_DBG(DEBUG_PERF,
            "svga: Create surface view: face %d zslice %d mips %d..%d\n",
            face_pick, zslice_pick, start_mip, start_mip+num_mip-1);

   key->flags = flags;
   key->format = format;
   key->numMipLevels = num_mip;
   key->size.width = u_minify(tex->b.b.width0, start_mip);
   key->size.height = u_minify(tex->b.b.height0, start_mip);
   key->size.depth = zslice_pick < 0 ? u_minify(tex->b.b.depth0, start_mip) : 1;
   key->cachable = 1;
   assert(key->size.depth == 1);

   if (tex->b.b.target == PIPE_TEXTURE_CUBE && face_pick < 0) {
      key->flags |= SVGA3D_SURFACE_CUBEMAP;
      key->numFaces = 6;
   } else {
      key->numFaces = 1;
   }

   if (key->format == SVGA3D_FORMAT_INVALID) {
      key->cachable = 0;
      return NULL;
   }

   SVGA_DBG(DEBUG_DMA, "surface_create for texture view\n");
   handle = svga_screen_surface_create(ss, key);
   if (!handle) {
      key->cachable = 0;
      return NULL;
   }

   SVGA_DBG(DEBUG_DMA, " --> got sid %p (texture view)\n", handle);

   if (face_pick < 0)
      face_pick = 0;

   if (zslice_pick >= 0)
      z_offset = zslice_pick;

   for (i = 0; i < key->numMipLevels; i++) {
      for (j = 0; j < key->numFaces; j++) {
         if (tex->defined[j + face_pick][i + start_mip]) {
            unsigned depth = (zslice_pick < 0 ?
                              u_minify(tex->b.b.depth0, i + start_mip) :
                              1);

            svga_texture_copy_handle(svga,
                                     tex->handle,
                                     0, 0, z_offset,
                                     i + start_mip,
                                     j + face_pick,
                                     handle, 0, 0, 0, i, j,
                                     u_minify(tex->b.b.width0, i + start_mip),
                                     u_minify(tex->b.b.height0, i + start_mip),
                                     depth);
         }
      }
   }

   return handle;
}

static struct pipe_surface *
svga_create_surface(struct pipe_context *pipe,
                    struct pipe_resource *pt,
                    const struct pipe_surface *surf_tmpl)
{
   struct svga_context *svga = svga_context(pipe);
   struct svga_texture *tex = svga_texture(pt);
   struct pipe_screen *screen = pipe->screen;
   struct svga_screen *ss = svga_screen(screen);
   struct svga_surface *s;
   unsigned face, zslice;
   /* XXX surfaces should only be used for rendering purposes nowadays */
   boolean render = (surf_tmpl->usage & (PIPE_BIND_RENDER_TARGET |
                                         PIPE_BIND_DEPTH_STENCIL)) ? TRUE : FALSE;
   boolean view = FALSE;
   SVGA3dSurfaceFlags flags;
   SVGA3dSurfaceFormat format;

   assert(surf_tmpl->u.tex.first_layer == surf_tmpl->u.tex.last_layer);

   s = CALLOC_STRUCT(svga_surface);
   if (!s)
      return NULL;

   if (pt->target == PIPE_TEXTURE_CUBE) {
      face = surf_tmpl->u.tex.first_layer;
      zslice = 0;
   }
   else {
      face = 0;
      zslice = surf_tmpl->u.tex.first_layer;
   }

   pipe_reference_init(&s->base.reference, 1);
   pipe_resource_reference(&s->base.texture, pt);
   s->base.context = pipe;
   s->base.format = surf_tmpl->format;
   s->base.width = u_minify(pt->width0, surf_tmpl->u.tex.level);
   s->base.height = u_minify(pt->height0, surf_tmpl->u.tex.level);
   s->base.usage = surf_tmpl->usage;
   s->base.u.tex.level = surf_tmpl->u.tex.level;
   s->base.u.tex.first_layer = surf_tmpl->u.tex.first_layer;
   s->base.u.tex.last_layer = surf_tmpl->u.tex.last_layer;

   if (!render) {
      flags = SVGA3D_SURFACE_HINT_TEXTURE;
   } else {
      if (surf_tmpl->usage & PIPE_BIND_RENDER_TARGET) {
         flags = SVGA3D_SURFACE_HINT_RENDERTARGET;
      }
      if (surf_tmpl->usage & PIPE_BIND_DEPTH_STENCIL) {
         flags = SVGA3D_SURFACE_HINT_DEPTHSTENCIL;
      }
   }

   format = svga_translate_format(ss, surf_tmpl->format, surf_tmpl->usage);
   assert(format != SVGA3D_FORMAT_INVALID);

   if (svga_screen(screen)->debug.force_surface_view)
      view = TRUE;

   /* Currently only used for compressed textures */
   if (render &&
       format != svga_translate_format(ss, surf_tmpl->format, surf_tmpl->usage)) {
      view = TRUE;
   }

   if (surf_tmpl->u.tex.level != 0 &&
       svga_screen(screen)->debug.force_level_surface_view)
      view = TRUE;

   if (pt->target == PIPE_TEXTURE_3D)
      view = TRUE;

   if (svga_screen(screen)->debug.no_surface_view)
      view = FALSE;

   if (view) {
      SVGA_DBG(DEBUG_VIEWS, "svga: Surface view: yes %p, level %u face %u z %u, %p\n",
               pt, surf_tmpl->u.tex.level, face, zslice, s);

      s->handle = svga_texture_view_surface(svga, tex, flags, format,
                                            surf_tmpl->u.tex.level,
                                            1, face, zslice, &s->key);
      s->real_face = 0;
      s->real_level = 0;
      s->real_zslice = 0;
   } else {
      SVGA_DBG(DEBUG_VIEWS, "svga: Surface view: no %p, level %u, face %u, z %u, %p\n",
               pt, surf_tmpl->u.tex.level, face, zslice, s);

      memset(&s->key, 0, sizeof s->key);
      s->handle = tex->handle;
      s->real_face = face;
      s->real_zslice = zslice;
      s->real_level = surf_tmpl->u.tex.level;
   }

   return &s->base;
}

static void
svga_surface_destroy(struct pipe_context *pipe,
                     struct pipe_surface *surf)
{
   struct svga_surface *s = svga_surface(surf);
   struct svga_texture *t = svga_texture(surf->texture);
   struct svga_screen *ss = svga_screen(surf->texture->screen);

   if (s->handle != t->handle) {
      SVGA_DBG(DEBUG_DMA, "unref sid %p (tex surface)\n", s->handle);
      svga_screen_surface_destroy(ss, &s->key, &s->handle);
   }

   pipe_resource_reference(&surf->texture, NULL);
   FREE(surf);
}

static INLINE void
svga_mark_surface_dirty(struct pipe_surface *surf)
{
   struct svga_surface *s = svga_surface(surf);

   if (!s->dirty) {
      struct svga_texture *tex = svga_texture(surf->texture);

      s->dirty = TRUE;

      if (s->handle == tex->handle) {
         /* hmm so 3d textures always have all their slices marked ? */
         if (surf->texture->target == PIPE_TEXTURE_CUBE)
            tex->defined[surf->u.tex.first_layer][surf->u.tex.level] = TRUE;
         else
            tex->defined[0][surf->u.tex.level] = TRUE;
      }
      else {
         /* this will happen later in svga_propagate_surface */
      }
   }
}

void
svga_mark_surfaces_dirty(struct svga_context *svga)
{
   unsigned i;

   for (i = 0; i < PIPE_MAX_COLOR_BUFS; i++) {
      if (svga->curr.framebuffer.cbufs[i])
         svga_mark_surface_dirty(svga->curr.framebuffer.cbufs[i]);
   }
   if (svga->curr.framebuffer.zsbuf)
      svga_mark_surface_dirty(svga->curr.framebuffer.zsbuf);
}

/**
 * Progagate any changes from surfaces to texture.
 * pipe is optional context to inline the blit command in.
 */
void
svga_propagate_surface(struct svga_context *svga, struct pipe_surface *surf)
{
   struct svga_surface *s = svga_surface(surf);
   struct svga_texture *tex = svga_texture(surf->texture);
   struct svga_screen *ss = svga_screen(surf->texture->screen);
   unsigned zslice, face;

   if (!s->dirty)
      return;

   if (surf->texture->target == PIPE_TEXTURE_CUBE) {
      zslice = 0;
      face = surf->u.tex.first_layer;
   }
   else {
      zslice = surf->u.tex.first_layer;
      face = 0;
   }

   s->dirty = FALSE;
   ss->texture_timestamp++;
   tex->view_age[surf->u.tex.level] = ++(tex->age);

   if (s->handle != tex->handle) {
      SVGA_DBG(DEBUG_VIEWS,
               "svga: Surface propagate: tex %p, level %u, from %p\n",
               tex, surf->u.tex.level, surf);
      svga_texture_copy_handle(svga,
                               s->handle, 0, 0, 0, s->real_level, s->real_face,
                               tex->handle, 0, 0, zslice, surf->u.tex.level, face,
                               u_minify(tex->b.b.width0, surf->u.tex.level),
                               u_minify(tex->b.b.height0, surf->u.tex.level), 1);
      tex->defined[face][surf->u.tex.level] = TRUE;
   }
}

/**
 * Check if we should call svga_propagate_surface on the surface.
 */
boolean
svga_surface_needs_propagation(struct pipe_surface *surf)
{
   struct svga_surface *s = svga_surface(surf);
   struct svga_texture *tex = svga_texture(surf->texture);

   return s->dirty && s->handle != tex->handle;
}

void
svga_init_surface_functions(struct svga_context *svga)
{
   svga->pipe.create_surface = svga_create_surface;
   svga->pipe.surface_destroy = svga_surface_destroy;
}


text:
<!doctype html>
<html>
<head>
  <script src="//cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/0.5.1-1/webcomponents.min.js"></script>
  <link rel="import" href="podcast-player.html"/>
</head>
<body>
  <podcast-player src="https://archive.org/download/MartinLutherKing-IHaveADream/MartinLutherKing-IHaveADream.mp3"></podcast-player>
</body>
</html>

redpajama_set_name: RedPajamaGithub


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

#nullable disable

using System;
using System.Collections.Generic;
using System.Threading;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Interop;

namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Input
{
    public abstract class AbstractSendKeys
    {
        protected abstract void ActivateMainWindow();

        protected abstract void WaitForApplicationIdle(CancellationToken cancellationToken);

        public void Send(params object[] keys)
        {
            var inputs = new List<NativeMethods.INPUT>(keys.Length);

            foreach (var key in keys)
            {
                if (key is string s)
                {
                    var text = s.Replace("\r\n", "\r")
                                .Replace("\n", "\r");

                    foreach (var ch in text)
                    {
                        AddInputs(inputs, ch);
                    }
                }
                else if (key is char c)
                {
                    AddInputs(inputs, c);
                }
                else if (key is VirtualKey virtualKey)
                {
                    AddInputs(inputs, virtualKey);
                }
                else if (key is KeyPress keyPress)
                {
                    AddInputs(inputs, keyPress);
                }
                else if (key == null)
                {
                    throw new ArgumentNullException(nameof(keys));
                }
                else
                {
                    throw new ArgumentException($"Unexpected type encountered: {key.GetType()}", nameof(keys));
                }
            }

            SendInputs(inputs.ToArray());
        }

        private static void AddInputs(List<NativeMethods.INPUT> inputs, char ch)
        {
            var result = NativeMethods.VkKeyScan(ch);
            if (result == -1)
            {
                // This is a unicode character that must be handled differently.

                AddUnicodeInputs(inputs, ch);
                return;
            }

            var virtualKey = (VirtualKey)(result & 0xff);
            var shiftState = (ShiftState)(((ushort)result >> 8) & 0xff);

            AddInputs(inputs, virtualKey, shiftState);
        }

        private static void AddUnicodeInputs(List<NativeMethods.INPUT> inputs, char ch)
        {
            var keyDownInput = new NativeMethods.INPUT
            {
                Type = NativeMethods.INPUT_KEYBOARD,
                Input =
                {
                    ki = new NativeMethods.KEYBDINPUT
                    {
                        wVk = 0,
                        wScan = ch,
                        dwFlags = NativeMethods.KEYEVENTF_UNICODE,
                        time = 0,
                        dwExtraInfo = NativeMethods.GetMessageExtraInfo(),
                    }
                }
            };

            var keyUpInput = new NativeMethods.INPUT
            {
                Type = NativeMethods.INPUT_KEYBOARD,
                Input =
                {
                    ki = new NativeMethods.KEYBDINPUT
                    {
                        wVk = 0,
                        wScan = ch,
                        dwFlags = NativeMethods.KEYEVENTF_UNICODE | NativeMethods.KEYEVENTF_KEYUP,
                        time = 0,
                        dwExtraInfo = NativeMethods.GetMessageExtraInfo(),
                    }
                }
            };

            inputs.Add(keyDownInput);
            inputs.Add(keyUpInput);
        }

        private static void AddInputs(List<NativeMethods.INPUT> inputs, VirtualKey virtualKey, uint dwFlags)
        {
            NativeMethods.INPUT input;
            var scanCode = NativeMethods.MapVirtualKey((uint)virtualKey, NativeMethods.MAPVK_VK_TO_VSC);
            if (scanCode != 0)
            {
                input = new NativeMethods.INPUT
                {
                    Type = NativeMethods.INPUT_KEYBOARD,
                    Input =
                    {
                        ki = new NativeMethods.KEYBDINPUT
                        {
                            wVk = 0,
                            wScan = (ushort)scanCode,
                            dwFlags = dwFlags | NativeMethods.KEYEVENTF_SCANCODE,
                            time = 0,
                            dwExtraInfo = NativeMethods.GetMessageExtraInfo(),
                        }
                    }
                };
            }
            else
            {
                input = new NativeMethods.INPUT
                {
                    Type = NativeMethods.INPUT_KEYBOARD,
                    Input =
                    {
                        ki = new NativeMethods.KEYBDINPUT
                        {
                            wVk = (ushort)virtualKey,
                            wScan = 0,
                            dwFlags = dwFlags,
                            time = 0,
                            dwExtraInfo = NativeMethods.GetMessageExtraInfo(),
                        }
                    }
                };
            }

            if (IsExtendedKey(virtualKey))
            {
                input.Input.ki.dwFlags |= NativeMethods.KEYEVENTF_EXTENDEDKEY;
            }

            inputs.Add(input);
        }

        private static bool IsExtendedKey(VirtualKey virtualKey)
            => (virtualKey >= VirtualKey.PageUp && virtualKey <= VirtualKey.Down)
            || virtualKey == VirtualKey.Insert
            || virtualKey == VirtualKey.Delete;

        private static void AddInputs(List<NativeMethods.INPUT> inputs, KeyPress keyPress)
            => AddInputs(inputs, keyPress.VirtualKey, keyPress.ShiftState);

        private static void AddInputs(List<NativeMethods.INPUT> inputs, VirtualKey virtualKey, ShiftState shiftState = 0)
        {
            if ((shiftState & ShiftState.Shift) != 0)
            {
                AddInputs(inputs, VirtualKey.Shift, NativeMethods.KEYEVENTF_NONE);
            }

            if ((shiftState & ShiftState.Ctrl) != 0)
            {
                AddInputs(inputs, VirtualKey.Control, NativeMethods.KEYEVENTF_NONE);
            }

            if ((shiftState & ShiftState.Alt) != 0)
            {
                AddInputs(inputs, VirtualKey.Alt, NativeMethods.KEYEVENTF_NONE);
            }

            AddInputs(inputs, virtualKey, NativeMethods.KEYEVENTF_NONE);
            AddInputs(inputs, virtualKey, NativeMethods.KEYEVENTF_KEYUP);

            if ((shiftState & ShiftState.Shift) != 0)
            {
                AddInputs(inputs, VirtualKey.Shift, NativeMethods.KEYEVENTF_KEYUP);
            }

            if ((shiftState & ShiftState.Ctrl) != 0)
            {
                AddInputs(inputs, VirtualKey.Control, NativeMethods.KEYEVENTF_KEYUP);
            }

            if ((shiftState & ShiftState.Alt) != 0)
            {
                AddInputs(inputs, VirtualKey.Alt, NativeMethods.KEYEVENTF_KEYUP);
            }
        }

        private void SendInputs(NativeMethods.INPUT[] inputs)
        {
            ActivateMainWindow();

            IntegrationHelper.SendInput(inputs);

            WaitForApplicationIdle(CancellationToken.None);
        }
    }
}


text:
import { Column } from './column';
import { sortArray } from '../util/sort';
import { StringBuilder } from '../../mol-util';

/** A collection of columns */
type Table<Schema extends Table.Schema = any> = {
    readonly _rowCount: number,
    readonly _columns: ReadonlyArray<string>,
    readonly _schema: Schema
} & Table.Columns<Schema>

/** An immutable table */
namespace Table {
    export type Schema = { [field: string]: Column.Schema }
    export type Columns<S extends Schema> = { [C in keyof S]: Column<S[C]['T']> }
    export type Row<S extends Schema> = { [C in keyof S]: S[C]['T'] }
    export type Arrays<S extends Schema> = { [C in keyof S]: ArrayLike<S[C]['T']> }
    export type PartialColumns<S extends Schema> = { [C in keyof S]?: Column<S[C]['T']> }
    export type PartialTable<S extends Table.Schema> = { readonly _rowCount: number, readonly _columns: ReadonlyArray<string> } & PartialColumns<S>

    export function is(t: any): t is Table<any> {
        return t && typeof t._rowCount === 'number' && !!t._columns && !!t._schema;
    }

    export function pickColumns<S extends Schema>(schema: S, table: PartialTable<S>, guard: Partial<Columns<S>> = {}): Table<S> {
        const ret = Object.create(null);
        const keys = Object.keys(schema);
        ret._rowCount = table._rowCount;
        ret._columns = keys;
        ret._schema = schema;
        for (const k of keys) {
            if (!!table[k]) ret[k] = table[k];
            else if (!!guard[k]) ret[k] = guard[k];
            else throw Error(`Cannot find column '${k}'.`);
        }
        return ret;
    }

    export function ofColumns<S extends Schema, R extends Table<S> = Table<S>>(schema: S, columns: Columns<S>): R {
        const _columns = Object.keys(columns);
        const _rowCount = columns[_columns[0]].rowCount;
        return { _rowCount, _columns, _schema: schema, ...(columns as any) };
    }

    export function ofPartialColumns<S extends Schema, R extends Table<S> = Table<S>>(schema: S, partialColumns: PartialColumns<S>, rowCount: number): R {
        const ret = Object.create(null);
        const columns = Object.keys(schema);
        ret._rowCount = rowCount;
        ret._columns = columns;
        ret._schema = schema;
        for (const k of columns) {
            if (k in partialColumns) ret[k] = partialColumns[k];
            else ret[k] = Column.Undefined(rowCount, schema[k]);
        }
        return ret;
    }

    export function ofUndefinedColumns<S extends Schema, R extends Table<S> = Table<S>>(schema: S, rowCount: number): R {
        const ret = Object.create(null);
        const columns = Object.keys(schema);
        ret._rowCount = rowCount;
        ret._columns = columns;
        ret._schema = schema;
        for (const k of columns) {
            ret[k] = Column.Undefined(rowCount, schema[k]);
        }
        return ret;
    }

    export function ofRows<S extends Schema, R extends Table<S> = Table<S>>(schema: S, rows: ArrayLike<Partial<Row<S>>>): R {
        const ret = Object.create(null);
        const rowCount = rows.length;
        const columns = Object.keys(schema);
        ret._rowCount = rowCount;
        ret._columns = columns;
        ret._schema = schema;
        for (const k of columns) {
            (ret as any)[k] = Column.ofLambda({
                rowCount,
                schema: schema[k],
                value: r => rows[r][k],
                valueKind: r => typeof rows[r][k] === 'undefined' ? Column.ValueKind.NotPresent : Column.ValueKind.Present
            });
        }
        return ret as R;
    }

    export function ofArrays<S extends Schema, R extends Table<S> = Table<S>>(schema: S, arrays: Partial<Arrays<S>>): R {
        const ret = Object.create(null);
        const columns = Object.keys(schema);
        ret._rowCount = 0;
        ret._columns = columns;
        ret._schema = schema;
        for (const k of columns) {
            if (typeof arrays[k] !== 'undefined') {
                (ret as any)[k] = Column.ofArray({ array: arrays[k]!, schema: schema[k] });
                ret._rowCount = arrays[k]?.length;
            } else {
                (ret as any)[k] = Column.Undefined(ret._rowCount, schema[k]);
            }
        }
        return ret as R;
    }

    export function view<S extends R, R extends Schema>(table: Table<S>, schema: R, view: ArrayLike<number>) {
        const ret = Object.create(null);
        const columns = Object.keys(schema);
        ret._rowCount = view.length;
        ret._columns = columns;
        ret._schema = schema;
        for (const k of columns) {
            (ret as any)[k] = Column.view(table[k], view);
        }
        return ret as Table<R>;
    }

    export function pick<S extends R, R extends Schema>(table: Table<S>, schema: R, test: (i: number) => boolean) {
        const _view: number[] = [];
        for (let i = 0, il = table._rowCount; i < il; ++i) {
            if (test(i)) _view.push(i);
        }
        return view(table, schema, _view);
    }

    export function window<S extends R, R extends Schema>(table: Table<S>, schema: R, start: number, end: number) {
        if (start === 0 && end === table._rowCount) return table;
        const ret = Object.create(null);
        const columns = Object.keys(schema);
        ret._rowCount = end - start;
        ret._columns = columns;
        ret._schema = schema;
        for (const k of columns) {
            (ret as any)[k] = Column.window(table[k], start, end);
        }
        return ret as Table<R>;
    }

    export function concat<S extends R, R extends Schema>(tables: Table<S>[], schema: R) {
        const ret = Object.create(null);
        const columns = Object.keys(schema);
        ret._rowCount = 0;
        for (const table of tables) {
            ret._rowCount += table._rowCount;
        }
        const arrays: any = {};
        for (const column of columns) {
            arrays[column] = new Array(ret._rowCount);
        }
        ret._columns = columns;
        ret._schema = schema;
        let offset = 0;
        for (const table of tables) {
            for (const k of columns) {
                Column.copyToArray(table[k], arrays[k], offset);
            }
            offset += table._rowCount;
        }
        for (const k of columns) {
            ret[k] = Column.ofArray({ array: arrays[k], schema: schema[k] });
        }
        return ret as Table<R>;
    }

    export function columnToArray<S extends Schema>(table: Table<S>, name: keyof S, array?: Column.ArrayCtor<any>) {
        (table as Columns<S>)[name] = Column.asArrayColumn((table as Columns<S>)[name], array);
    }

    /** Sort and return a new table */
    export function sort<T extends Table>(table: T, cmp: (i: number, j: number) => number) {
        const indices = new Int32Array(table._rowCount);
        for (let i = 0, _i = indices.length; i < _i; i++) indices[i] = i;
        sortArray(indices, (_, i, j) => cmp(i, j));

        let isIdentity = true;
        for (let i = 0, _i = indices.length; i < _i; i++) {
            if (indices[i] !== i) {
                isIdentity = false;
                break;
            }
        }
        if (isIdentity) return table;

        const ret = Object.create(null);
        ret._rowCount = table._rowCount;
        ret._columns = table._columns;
        ret._schema = table._schema;
        for (const c of table._columns) {
            ret[c] = Column.view((table as any)[c], indices, false);
        }
        return ret;
    }

    export function areEqual<T extends Table<any>>(a: T, b: T) {
        if (a._rowCount !== b._rowCount) return false;
        if (a._columns.length !== b._columns.length) return false;
        for (const c of a._columns) {
            if (!b[c]) return false;
        }

        for (const c of a._columns) {
            if (!Column.areEqual(a[c], b[c])) return false;
        }

        return true;
    }

    /** Allocate a new object with the given row values. */
    export function getRow<S extends Schema>(table: Table<S>, index: number) {
        const row: Row<S> = Object.create(null);
        const { _columns: cols } = table;
        for (let i = 0; i < cols.length; i++) {
            const c = cols[i] as keyof S;
            row[c] = table[c].value(index);
        }
        return row;
    }

    /** Pick the first row for which `test` evaluates to true */
    export function pickRow<S extends Schema>(table: Table<S>, test: (i: number) => boolean) {
        for (let i = 0, il = table._rowCount; i < il; ++i) {
            if (test(i)) return getRow(table, i);
        }
    }

    export function getRows<S extends Schema>(table: Table<S>) {
        const ret: Row<S>[] = [];
        const { _rowCount: c } = table;
        for (let i = 0; i < c; i++) {
            ret[i] = getRow(table, i);
        }
        return ret;
    }

    export function toArrays<S extends Schema>(table: Table<S>) {
        const arrays: { [k: string]: ArrayLike<any> } = {};
        const { _columns } = table;
        for (let i = 0; i < _columns.length; i++) {
            const c = _columns[i];
            arrays[c] = table[c].toArray();
        }
        return arrays as { [k in keyof S]: ArrayLike<S[k]['T']> };
    }

    export function formatToString<S extends Schema>(table: Table<S>) {
        const sb = StringBuilder.create();

        const { _columns: cols, _rowCount } = table;

        let headerLength = 1;
        StringBuilder.write(sb, '|');
        for (let i = 0; i < cols.length; i++) {
            StringBuilder.write(sb, cols[i]);
            StringBuilder.write(sb, '|');
            headerLength += cols[i].length + 1;
        }
        StringBuilder.newline(sb);
        StringBuilder.write(sb, new Array(headerLength + 1).join('-'));
        StringBuilder.newline(sb);

        for (let r = 0; r < _rowCount; r++) {
            StringBuilder.write(sb, '|');
            for (let i = 0; i < cols.length; i++) {
                const c = table[cols[i]];
                if (c.valueKind(r) === Column.ValueKind.Present) {
                    StringBuilder.write(sb, c.value(r));
                    StringBuilder.write(sb, '|');
                } else {
                    StringBuilder.write(sb, '.|');
                }
            }
            StringBuilder.newline(sb);
        }
        return StringBuilder.getString(sb);
    }
}

export { Table };


text: (function(expose) {


text:
class AddSlugIndex < ActiveRecord::Migration
  def self.up
    add_index :schools, :slug
  end

  def self.down
  end
end


text:
package com.jme3.ai.navigation.detour;

import com.jme3.ai.navigation.utils.Converter;
import com.jme3.ai.navigation.utils.SWIGTYPE_p_float;
import com.jme3.ai.navigation.utils.RecastJNI;
import com.jme3.ai.navigation.utils.SWIGTYPE_p_unsigned_char;
import com.jme3.math.Vector3f;
import com.jme3.scene.Mesh;

/**
 * Defines a navigation mesh tile.
 *
 * Tiles generally only exist within the context of a dtNavMesh object.
 *
 * Some tile content is optional. For example, a tile may not contain any
 * off-mesh connections. In this case the associated pointer will be null.
 *
 * If a detail mesh exists it will share vertices with the base polygon mesh.
 * Only the vertices unique to the detail mesh will be stored in detailVerts.
 *
 * Warning: Tiles returned by a NavMesh object are not guarenteed to be
 * populated. For example: The tile at a location might not have been loaded
 * yet, or may have been removed. In this case, pointers will be null. So if in
 * doubt, check the polygon count in the tile's header to determine if a tile
 * has polygons defined.
 *
 * @see NavMesh
 *
 * @author Tihomir Radosavljevic
 * @version 1.0
 */
public class MeshTile {

    private long swigCPtr;
    protected boolean swigCMemOwn;

    public MeshTile() {
        this(RecastJNI.new_dtMeshTile(), true);
    }

    public MeshTile(long cPtr, boolean cMemoryOwn) {
        swigCMemOwn = cMemoryOwn;
        swigCPtr = cPtr;
    }

    public static long getCPtr(MeshTile obj) {
        return (obj == null) ? 0 : obj.swigCPtr;
    }

    @Override
    protected void finalize() {
        delete();
    }

    public synchronized void delete() {
        if (swigCPtr != 0) {
            if (swigCMemOwn) {
                swigCMemOwn = false;
                RecastJNI.delete_dtMeshTile(swigCPtr);
            }
            swigCPtr = 0;
        }
    }

    /**
     *
     * @param value Counter describing modifications to the tile.
     */
    public void setSalt(long value) {
        RecastJNI.dtMeshTile_salt_set(swigCPtr, this, value);
    }

    /**
     *
     * @return Counter describing modifications to the tile.
     */
    public long getSalt() {
        return RecastJNI.dtMeshTile_salt_get(swigCPtr, this);
    }

//    /**
//     *
//     * @param value Index to the next free link.
//     */
//    public void setLinksFreeList(long value) {
//        RecastJNI.dtMeshTile_linksFreeList_set(swigCPtr, this, value);
//    }

    /**
     *
     * @return Index to the next free link.
     */
    public long getLinksFreeList() {
        return RecastJNI.dtMeshTile_linksFreeList_get(swigCPtr, this);
    }

    /**
     *
     * @param value The tile header.
     */
    public void setHeader(MeshHeader value) {
        RecastJNI.dtMeshTile_header_set(swigCPtr, this, MeshHeader.getCPtr(value), value);
    }

    /**
     *
     * @return The tile header.
     */
    public MeshHeader getHeader() {
        long cPtr = RecastJNI.dtMeshTile_header_get(swigCPtr, this);
        return (cPtr == 0) ? null : new MeshHeader(cPtr, false);
    }

    /**
     *
     * @param value The tile polygons.
     */
    public void setPolys(Poly value) {
        RecastJNI.dtMeshTile_polys_set(swigCPtr, this, Poly.getCPtr(value), value);
    }

    /**
     *
     * @return The tile polygons.
     */
    public Poly[] getPolys() {
        long cPtr = RecastJNI.dtMeshTile_polys_get(swigCPtr, this);
        return (cPtr == 0) ? null : Converter.convertToPolys(cPtr, getHeader().getPolyCount());
    }

    /**
     *
     * @param vertices The tile vertices.
     */
    public void setVertices(Vector3f[] vertices) {
        SWIGTYPE_p_float value = Converter.convertToSWIGTYPE_p_float(vertices);
        RecastJNI.dtMeshTile_verts_set(swigCPtr, this, SWIGTYPE_p_float.getCPtr(value));
    }

    /**
     *
     * @return The tile vertices.
     */
    public Vector3f[] getVertices() {
        long cPtr = RecastJNI.dtMeshTile_verts_get(swigCPtr, this);
        return (cPtr == 0) ? null : Converter.convertToVector3f(cPtr, getHeader().getVerticesCount());
    }

    /**
     *
     * @param value The tile links.
     */
    public void setLinks(Link[] value) {
        RecastJNI.dtMeshTile_links_set(swigCPtr, this, Link.getCPtr(value[0]), value[0]);
    }

    /**
     *
     * @return The tile links.
     */
    public Link[] getLinks() {
        long cPtr = RecastJNI.dtMeshTile_links_get(swigCPtr, this);
        return (cPtr == 0) ? null : Converter.convertToLinks(cPtr, getHeader().getMaxLinkCount());
    }

    /**
     *
     * @param value The tile's detail sub-meshes.
     */
    public void setDetailMeshes(PolyDetail[] value) {
        RecastJNI.dtMeshTile_detailMeshes_set(swigCPtr, this, PolyDetail.getCPtr(value[0]), value[0]);
    }

    /**
     *
     * @return The tile's detail sub-meshes.
     */
    public PolyDetail[] getDetailMeshes() {
        long cPtr = RecastJNI.dtMeshTile_detailMeshes_get(swigCPtr, this);
        return (cPtr == 0) ? null : Converter.convertToPolyDetails(cPtr, getHeader().getDetailMeshCount());
    }

    /**
     *
     * @param detailVertices The detail mesh's unique vertices. [(x, y, z) *
     */
    public void setDetailVertices(Vector3f[] detailVertices) {
        SWIGTYPE_p_float value = Converter.convertToSWIGTYPE_p_float(detailVertices);
        RecastJNI.dtMeshTile_detailVerts_set(swigCPtr, this, SWIGTYPE_p_float.getCPtr(value));
    }

    /**
     *
     * @return The detail mesh's unique vertices. [(x, y, z) *
     */
    public Vector3f[] getDetailVertices() {
        long cPtr = RecastJNI.dtMeshTile_detailVerts_get(swigCPtr, this);
        return (cPtr == 0) ? null : Converter.convertToVector3f(cPtr, getHeader().getDetailVerticesCount());
    }

    /**
     *
     * @param detailTriangles The detail mesh's triangles. [(vertA, vertB,
     * vertC)]
     */
    public void setDetailTriangles(char[] detailTriangles) {
        SWIGTYPE_p_unsigned_char value = Converter.convertToSWIGTYPE_p_unsigned_char(detailTriangles);
        RecastJNI.dtMeshTile_detailTris_set(swigCPtr, this, SWIGTYPE_p_unsigned_char.getCPtr(value));
    }

    /**
     *
     * @return The detail mesh's triangles. [(vertA, vertB, vertC)]
     */
    public char[] getDetailTriangles() {
        long cPtr = RecastJNI.dtMeshTile_detailTris_get(swigCPtr, this);
        return (cPtr == 0) ? null : Converter.convertToChars(cPtr, getHeader().getDetailTrianglesCount() * 3);
    }

    /**
     * -not tested yet
     *
     * @param value The tile bounding volume nodes.
     */
    public void setBvTree(BVNode value) {
        RecastJNI.dtMeshTile_bvTree_set(swigCPtr, this, BVNode.getCPtr(value), value);
    }

    /**
     * -not tested yet
     *
     * @return The tile bounding volume nodes.
     */
    public BVNode getBvTree() {
        long cPtr = RecastJNI.dtMeshTile_bvTree_get(swigCPtr, this);
        return (cPtr == 0) ? null : new BVNode(cPtr, false);
    }

    /**
     *
     * @param value The tile off-mesh connections.
     */
    public void setOffMeshConnections(OffMeshConnection value) {
        RecastJNI.dtMeshTile_offMeshCons_set(swigCPtr, this, OffMeshConnection.getCPtr(value), value);
    }

    /**
     *
     * @return The tile off-mesh connections.
     */
    public OffMeshConnection[] getOffMeshConnections() {
        long cPtr = RecastJNI.dtMeshTile_offMeshCons_get(swigCPtr, this);
        return (cPtr == 0) ? null : Converter.convertToOffMeshConnections(cPtr, getHeader().getOffMeshConnectionsCount());
    }

    /**
     *
     * @param data The tile data. (Not directly accessed under normal
     * situations.)
     */
    public void setData(char[] data) {
        SWIGTYPE_p_unsigned_char value = Converter.convertToSWIGTYPE_p_unsigned_char(data);
        RecastJNI.dtMeshTile_data_set(swigCPtr, this, SWIGTYPE_p_unsigned_char.getCPtr(value));
    }

    /**
     *
     * @return The tile data. (Not directly accessed under normal situations.)
     */
    public char[] getData() {
        long cPtr = RecastJNI.dtMeshTile_data_get(swigCPtr, this);
        return (cPtr == 0) ? null : Converter.convertToChars(cPtr, getDataSize());
    }

    /**
     *
     * @param value Size of the tile data.
     */
    public void setDataSize(int value) {
        RecastJNI.dtMeshTile_dataSize_set(swigCPtr, this, value);
    }

    /**
     *
     * @return Size of the tile data.
     */
    public int getDataSize() {
        return RecastJNI.dtMeshTile_dataSize_get(swigCPtr, this);
    }

    /**
     *
     * @param value Tile flags.
     */
    public void setFlags(int value) {
        RecastJNI.dtMeshTile_flags_set(swigCPtr, this, value);
    }

    /**
     *
     * @return Tile flags.
     */
    public int getFlags() {
        return RecastJNI.dtMeshTile_flags_get(swigCPtr, this);
    }

    /**
     *
     * @param value The next free tile, or the next tile in the spatial grid.
     */
    public void setNext(MeshTile value) {
        RecastJNI.dtMeshTile_next_set(swigCPtr, this, MeshTile.getCPtr(value), value);
    }

    /**
     *
     * @return The next free tile, or the next tile in the spatial grid.
     */
    public MeshTile getNext() {
        long cPtr = RecastJNI.dtMeshTile_next_get(swigCPtr, this);
        return (cPtr == 0) ? null : new MeshTile(cPtr, false);
    }

    protected void setSwigCPtr(long swigCPtr) {
        if (this.swigCPtr==swigCPtr) {
            return;
        }
        delete();
        this.swigCPtr = swigCPtr;
    }
}


text:
redirect_from:
- /ucp/installation/system-requirements/
description: Learn about the system requirements for installing Docker Universal Control
  Plane.
keywords:
- docker, ucp, architecture, requirements
title: UCP System requirements
---

Docker Universal Control Plane can be installed on-premises or on the cloud.
Before installing, be sure your infrastructure has these requirements.

## Hardware and software requirements

You can install UCP on-premises or on a cloud provider. To install UCP,
all nodes must have:

* Linux kernel version 3.10 or higher
* CS Docker Engine version 1.10 or higher. Learn about the
[operating systems supported by CS Docker Engine](/cs-engine/install/).
* 2.00 GB of RAM
* 3.00 GB of available disk space
* A static IP address

For highly-available installations, you also need a way to transfer files
between hosts.

## Ports used

When installing UCP on a host, make sure the following ports are open:

| Hosts              | Direction | Port                    | Purpose                                                                    |
|:-------------------|:---------:|:------------------------|:---------------------------------------------------------------------------|
| controllers, nodes |    in     | TCP 443  (configurable) | Web app and CLI client access to UCP.                                      |
| controllers, nodes |    in     | TCP 2375                | Heartbeat for nodes, to ensure they are running.                           |
| controllers        |    in     | TCP 2376 (configurable) | Swarm manager accepts requests from UCP controller.                        |
| controllers, nodes |  in, out  | TCP + UDP 4789          | Overlay networking.                                                        |
| controllers, nodes |  in, out  | TCP + UDP 7946          | Overlay networking.                                                        |
| controllers, nodes |    in     | TCP 12376               | Proxy for TLS, provides access to UCP, Swarm, and Engine.                  |
| controller         |    in     | TCP 12379               | Internal node configuration, cluster configuration, and HA.                |
| controller         |    in     | TCP 12380               | Internal node configuration, cluster configuration, and HA.                |
| controller         |    in     | TCP 12381               | Proxy for TLS, provides access to UCP.                                     |
| controller         |    in     | TCP 12382               | Manages TLS and requests from swarm manager.                               |
| controller         |    in     | TCP 12383               | Used by the authentication storage backend.                                |
| controller         |    in     | TCP 12384               | Used by authentication storage backend for replication across controllers. |
| controller         |    in     | TCP 12385               | The port where the authentication API is exposed.                          |
| controller         |    in     | TCP 12386               | Used by the authentication worker.                                         |

## Compatibility and maintenance lifecycle

Docker Datacenter is a software subscription that includes 3 products:

* CS Docker Engine,
* Docker Trusted Registry,
* Docker Universal Control Plane.

[Learn more about the maintenance lifecycle for these products](http://success.docker.com/Get_Help/Compatibility_Matrix_and_Maintenance_Lifecycle).

## Where to go next

* [UCP architecture](../architecture.md)
* [Plan a production installation](plan-production-install.md)


text:
var MapDivisionNode = function(map, id, srs, extents, heightRange, partitioning) {
    this.map = map;
    this.id = id;
    this.srs = this.map.getMapsSrs(srs);
    this.extents = extents;
    this.heightRange =  heightRange;
    this.partitioning = partitioning;
    this.isPole = (id[0] == 1 && ((id[1] == 0 && id[2] == 1)||(id[1] == 1 && id[2] == 0)));
};

MapDivisionNode.prototype.getInnerCoords = function (coords) {
    return this.srs.convertCoordsFrom(coords, this.map.getNavigationSrs());
};

MapDivisionNode.prototype.getOuterCoords = function (coords) {
    return this.srs.convertCoordsTo(coords, this.map.getNavigationSrs());
};

MapDivisionNode.prototype.getPhysicalCoords = function (coords, skipVerticalAdjust) {
    return this.srs.convertCoordsTo(coords, this.map.getPhysicalSrs(), skipVerticalAdjust);
};

MapDivisionNode.prototype.getPhysicalCoordsFast = function (coords, skipVerticalAdjust, coords2, index, index2) {
    return this.srs.convertCoordsToFast(coords, this.map.getPhysicalSrs(), skipVerticalAdjust, coords2, index, index2);
};

MapDivisionNode.prototype.getExtents = function (coords) {
    return this.srs.convertCoordsFrom(coords, this.map.getNavigationSrs());
};

export default MapDivisionNode;


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

set RUNHOME=%~dp0
echo ### RUNHOME: %RUNHOME%

echo ### Starting umc-service
cd /d %RUNHOME%

rem set JAVA_HOME=C:\Program Files\Java\jdk1.7.0_79
set JAVA="%JAVA_HOME%\bin\java.exe"
set port=8311
set jvm_opts=-Xms50m -Xmx128m
rem set jvm_opts=%jvm_opts% -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=%port%,server=y,suspend=n
set class_path=%RUNHOME%;%RUNHOME%etsivnfm-adapter-service.jar
echo ### jvm_opts: %jvm_opts%
echo ### class_path: %class_path%

%JAVA% -classpath %class_path% %jvm_opts% org.openo.orchestrator.nfv.nsoc.ia.vnfm.etsi.VnfmAdapterApp  server %RUNHOME%conf/etsi-vnfm-adapter.yml

IF ERRORLEVEL 1 goto showerror
exit
:showerror
echo WARNING: Error occurred during startup or Server abnormally stopped by way of killing the process,Please check!
echo After checking, press any key to close
rem pause
exit


text:
'use strict';

(() => {

  let prefix = '/',

    event = 'DOMContentLoaded';

  document.addEventListener(event, function () {

    (function (system) {

      var sys = {

        'configuration': {

          'map': {

            'app': `${prefix}scripts`,

            '@angular/core': 'npm:@angular/core/bundles/core.umd.js',

            '@angular/common': 'npm:@angular/common/bundles/common.umd.js',

            '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',

            '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',

            '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',

            '@angular/http': 'npm:@angular/http/bundles/http.umd.js',

            '@angular/router': 'npm:@angular/router/bundles/router.umd.js',

            '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

            'rxjs': 'npm:rxjs',

            'lodash': 'npm:lodash',

            'async': 'npm:async',

            'howler': 'npm:howler',

            'hammerjs': 'npm:hammerjs',

            'json': 'npm:systemjs-plugin-json/json.js',

            'moment-timezone': 'npm:moment-timezone',

            'reflect-metadata': 'npm:reflect-metadata',

            'moment': 'npm:moment',

            'zone.js': 'npm:zone.js',

            'core-js': 'npm:core-js',

            'ng2-toasty': 'npm:ng2-toasty/bundles/index.umd.js',

            'configuration': `${prefix}config/default.json`,

            'package': `${prefix}package.json`

          },

          'paths': {

            'npm:': '/modules/'

          },

          'packages': {

            'app': {

              'main': 'app',

              'defaultExtension': 'js'

            },

            'core-js': {

              'main': './index.js',

              'defaultExtension': 'js'

            },

            'zone.js': {

              'main': './dist/zone-node.js',

              'defaultExtension': 'js'

            },

            'reflect-metadata': {

              'main': './Reflect.js',

              'defaultExtension': 'js'

            },

            'hammerjs': {

              'main': './hammer.js',

              'defaultExtension': 'js'

            },

            'async': {

              'main': './dist/async.js',

              'defaultExtension': 'js'

            },

            'rxjs': {

              'defaultExtension': 'js'

            },

            'lodash': {

              'main': './index',

              'defaultExtension': 'js'

            },

            'moment': {

              'main': './moment.js',

              'defaultExtension': 'js'

            },

            'moment-timezone': {

              'main': './index.js',

              'defaultExtension': 'js'

            },

            'howler': {

              'main': './dist/howler.js',

              'defaultExtension': 'js'

            }

          }

        },

        config: function () {

          system.config(
            this
              .configuration
          );

          return this;

        },

        addMeta: function () {

          let json = {

            'loader': 'json'

          };

          this.configuration.meta = {};

          this.configuration.meta[`${prefix}config/*.json`] = json;

          this.configuration.meta[`/modules/moment-timezone/data/packed/latest.json`] = json;

          this.configuration.meta[`${prefix}package.json`] = json;

          return this;

        },

        import: function (name) {

          system.import(`${prefix}config/default.json!json`);

          system.import(`${prefix}package.json!json`);

          system
            .import(name)
            .catch(function (err) {

              return console
                .error(err);

            });

          return this;

        }

      };

      if (sys && system) {

        sys
          .addMeta()
          .config()
          .import('app');

      }

    })(window.System || {});

  });

})();


text:
require 'rubygems'
require 'bundler/setup'

require 'ruby_stix'
require 'ruby_stix/api'

RSpec.configure do |config|
  # nothing to configure really...
end


text:
   git log v0.4.0..v0.4.1

 * Tested in Node.JS 0.8 through 4.2 and 5.5
 * Emit an error with the 'close' event if server-initiated

## Changes in v0.4.0

   git log v0.3.2..v0.4.0

 * Tested on Node.JS 0.8 through 4.0 (and intervening io.js releases)
 * Change meaning of 'b' fields in tables to match RabbitMQ (and AMQP
   specification)
 * Can now pass an object in place of connection URL
   ([PR 159](https://github.com/squaremo/amqp.node/pull/159); thanks
   to @ben-page)
 * Operator-initiated connection close no longer results in 'error'
   event
   ([issue 110](https://github.com/squaremo/amqp.node/issues/110))
 * Channel and Connection errors have now a `.code` field with the
   AMQP reply-code, which may help distinguish error cases
   ([PR 150](https://github.com/squaremo/amqp.node/pull/150); thanks
   to @hippich)
 * Connection.close will resolve to an error if the connection is
   already closed
   ([issue 181](https://github.com/squaremo/amqp.node/issues/181))
 * Connection establishment will resolve with an error if the
   TCP-level connection or the handshake times out
   ([PR 169](https://github.com/squaremo/amqp.node/pull/169); thanks
   to @zweifisch and @RoCat, who both submitted fixes)
 * Add the `maxPriority` option as an alias for the `'x-max-priority'`
   queue argument
   ([PR 180](https://github.com/squaremo/amqp.node/pull/180); thanks
   to @ebardes)

## Changes in v0.3.2 (since v0.3.1)

   git log v0.3.1..v0.3.2

 * Make the engine specification more flexible to admit io.js releases

## Changes in v0.3.1 (since v0.3.0)

   git log v0.3.0..v0.3.1

### Fixes

 * Fail in the right way when a channel cannot be allocated [issue
 129](https://github.com/squaremo/amqp.node/issues/129)
 * Make `waitForConfirms` work properly in callback API [PR
   116](https://github.com/squaremo/amqp.node/pull/116)

### Enhancements

 * Two new options while connecting:
   [timeout](https://github.com/squaremo/amqp.node/pull/118) and [keep
   alive](https://github.com/squaremo/amqp.node/pull/125) (thanks to
   @rexxars and @jcrugzz respectively)

## Changes in v0.3.0 (since v0.2.1)

   git log v0.2.1..v0.3.0

### Enhancements

 * Allow additional client properties to be set for a connection
   [Issue 98](https://github.com/squaremo/amqp.node/issues/98) and
   [PR 80](https://github.com/squaremo/amqp.node/pull/80)
 * New method in channel API to wait for all unconfirmed messages
   [Issue 89](https://github.com/squaremo/amqp.node/issues/89)
 * Now supports RabbitMQ's `EXTERNAL` authentication plugin
   [Issue 105](https://github.com/squaremo/amqp.node/issues/105)

## Changes in v0.2.1 (since v0.2.0)

### Fixes

 * Do tuning negotation properly [PR
   84](https://github.com/squaremo/amqp.node/pull/84)

## Changes in v0.2.0 (since v0.1.3)

    git log v0.1.3..v0.2.0

### Fixes

 * Correctly deal with missing fields (issue 48)

### Enhancements

 * Added a callback-oriented API, parallel to the existing,
   promise-oriented API.
 * The response to assertExchange now contains the exchange name,
   analagous to assertQueue (issue 49)
 * The channel method `prefetch` now has a global flag, to be
   [compatible with newer RabbitMQ][rabbitmq-prefetch-global].

## Changes in v0.1.3 (since v0.1.2)

    git log v0.1.2..v0.1.3

### Enhancements

 * Add support in the API for using Basic.Reject rather than
   Basic.Nack, the latter of which is a RabbitMQ extension and not in
   older versions of RabbitMQ.

## Changes in v0.1.2 (since v0.1.1)

    git log v0.1.1..v0.1.2

### Fixes

 * Restore support for publishing zero-length messages

### Enhancements

 * Recognise [authentication failures][rabbitmq-auth-failure]
 * An option to set TCP_NODELAY on connection sockets

## Changes in v0.1.1 (since v0.1.0)

    git log v0.1.0..v0.1.1

### Fixes

 * Safer frame construction, no longer relies on allocating a large,
   fixed-size buffer and hoping it's big enough
 * The ports of RabbitMQ tutorials now avoid a race between publishing
   and closing the connection

### Enhancements

 * Support for RabbitMQ's consumer priority extension
 * Support for RabbitMQ's connnection.blocked extension
 * Better write speed from batching frames for small messages
 * Other minor efficiency gains in method encoding and decoding
 * Channel and connection state errors (e.g., trying to write when
   closed) include a stack trace from when they moved to that state
 * The `arguments` table, passed as an option to some methods, can
   include fields in its prototype chain
 * Provide the more accurately named `persistent` as a near equivalent
   of `deliveryMode`

## Changes in v0.1.0 (since v0.0.2)

    git log v0.0.2..v0.1.0

### Breaking changes

 * Consumer callbacks are invoked with `null` if the consumer is
   cancelled (see
   [RabbitMQ's consumer cancel notification][rabbitmq-consumer-cancel])
 * In confirm channels, instead of `#publish` and `#sendToQueue`
   returning promises, they return a boolean as for normal channels,
   and take a Node.JS-style `function (err, ok)` callback for the
   server ack or nack

### Fixes

 * Overlapping channel and connection close frames are dealt with
   gracefully
 * Exceptions thrown in consumer callbacks are raised as `'error'`
   events
 * Zero-size messages are handled
 * Avoid monkey-patching `Buffer`, and eschew
   `require('util')._extend`

### Enhancements

 * Channels now behave like `Writable` streams with regard to `#publish`
   and `#sendToQueue`, returning a boolean from those methods and
   emitting `'drain'`
 * Connections now multiplex frames from channels fairly
 * Low-level channel machinery is now fully callback-based

[rabbitmq-consumer-cancel]: http://www.rabbitmq.com/consumer-cancel.html
[rabbitmq-auth-failure]: http://www.rabbitmq.com/auth-notification.html
[rabbitmq-prefetch-global]: http://www.rabbitmq.com/consumer-prefetch.html


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

namespace Zenject
{
#if UNITY_EDITOR
    public static class StaticMemoryPoolRegistry
    {
        public static event Action<IMemoryPool> PoolAdded = delegate {};
        public static event Action<IMemoryPool> PoolRemoved = delegate {};

        readonly static List<IMemoryPool> _pools = new List<IMemoryPool>();

        public static IEnumerable<IMemoryPool> Pools
        {
            get { return _pools; }
        }

        public static void Add(IMemoryPool memoryPool)
        {
            _pools.Add(memoryPool);
            PoolAdded(memoryPool);
        }

        public static void Remove(IMemoryPool memoryPool)
        {
            _pools.RemoveWithConfirm(memoryPool);
            PoolRemoved(memoryPool);
        }
    }
#endif
}


text:
package com.shuai.demo.protocol;

import java.util.List;

import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;

import android.content.Context;

import com.shuai.demo.data.Constants;
import com.shuai.demo.utils.AppUtils;

/**
 * 协议url辅助拼接类
 */
public class UrlHelper {
	private static String getUrl(String relativePath, List<BasicNameValuePair> params) {
		StringBuilder builder = new StringBuilder(Constants.SERVER_ADDRESS);
		builder.append("/").append(relativePath);
		String query = params == null ? "" : URLEncodedUtils.format(params, "UTF-8");
		if (query.length() != 0)
			builder.append("?").append(query);

		return builder.toString();
	}

	/**
	 * 增加公共参数,如版本号
	 * @param params
	 */
	public static void addCommonParameters(Context context,List<BasicNameValuePair> params){
		params.add(new BasicNameValuePair("version", AppUtils.getVersionName(context)));
	    params.add(new BasicNameValuePair("protocol_version", Constants.PROTOCOL_VERSION));
	    params.add(new BasicNameValuePair("channel", AppUtils.getChannel(context)));
	    params.add(new BasicNameValuePair("device", Constants.DEVICE_INFO));
	}

}


text:
using namespace triagens::basics;

namespace triagens {
  namespace rest {

// -----------------------------------------------------------------------------
// constructors and destructors
// -----------------------------------------------------------------------------

    PathHandler::PathHandler (HttpRequest* request, Options const* options)
      : HttpHandler(request),
        path(options->path),
        contentType(options->contentType),
        allowSymbolicLink(options->allowSymbolicLink),
        defaultFile(options->defaultFile),
        cacheMaxAge(options->cacheMaxAge),
        maxAgeHeader("max-age=") {

      std::string::size_type pos = path.size();

      while (1 < pos && path[pos - 1] == '/') {
        path.erase(--pos);
      }

      maxAgeHeader += StringUtils::itoa(cacheMaxAge);
    }

// -----------------------------------------------------------------------------
    // Handler methods
// -----------------------------------------------------------------------------

    HttpHandler::status_t PathHandler::execute () {
      static std::string const allowed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890. +-_=";

      std::vector<std::string> names = _request->suffix();
      std::string name = path;
      std::string last = "";

      if (names.empty() && ! defaultFile.empty()) {
        std::string url = _request->requestPath();

        if (! url.empty() && url[url.size() - 1] != '/') {
          url += '/';
        }
        url += defaultFile;

        _response = createResponse(HttpResponse::MOVED_PERMANENTLY);

        _response->setHeader("location", url);
        _response->setContentType("text/html");

        _response->body().appendText("<title>Moved</title>
Moved

This page has moved to body().appendText(url);
        _response->body().appendText(">");
        _response->body().appendText(url);
        _response->body().appendText(".
");

        return status_t(HANDLER_DONE);
      }

      for (std::vector<std::string>::const_iterator j = names.begin();  j != names.end();  ++j) {
        std::string const& next = *j;

        if (next == ".") {
          LOG_WARNING("file '%s' contains '.'", name.c_str());

          _response = createResponse(HttpResponse::FORBIDDEN);
          _response->body().appendText("path contains '.'");
          return status_t(HANDLER_DONE);
        }

        if (next == "..") {
          LOG_WARNING("file '%s' contains '..'", name.c_str());

          _response = createResponse(HttpResponse::FORBIDDEN);
          _response->body().appendText("path contains '..'");
          return status_t(HANDLER_DONE);
        }

        std::string::size_type sc = next.find_first_not_of(allowed);

        if (sc != std::string::npos) {
          LOG_WARNING("file '%s' contains illegal character", name.c_str());

          _response = createResponse(HttpResponse::FORBIDDEN);
          _response->body().appendText("path contains illegal character '" + std::string(1, next[sc]) + "'");
          return status_t(HANDLER_DONE);
        }

        if (! path.empty()) {
          if (! FileUtils::isDirectory(path)) {
            LOG_WARNING("file '%s' not found", name.c_str());

            _response = createResponse(HttpResponse::NOT_FOUND);
            _response->body().appendText("file not found");
            return status_t(HANDLER_DONE);
          }
        }

        name += "/" + next;
        last = next;

        if (! allowSymbolicLink && FileUtils::isSymbolicLink(name)) {
          LOG_WARNING("file '%s' contains symbolic link", name.c_str());

          _response = createResponse(HttpResponse::FORBIDDEN);
          _response->body().appendText("symbolic links are not allowed");
          return status_t(HANDLER_DONE);
        }
      }

      if (! FileUtils::isRegularFile(name)) {
        LOG_WARNING("file '%s' not found", name.c_str());

        _response = createResponse(HttpResponse::NOT_FOUND);
        _response->body().appendText("file not found");
        return status_t(HANDLER_DONE);
      }

      _response = createResponse(HttpResponse::OK);

      try {
        FileUtils::slurp(name, _response->body());
      }
      catch (...) {
        LOG_WARNING("file '%s' not readable", name.c_str());

        _response = createResponse(HttpResponse::NOT_FOUND);
        _response->body().appendText("file not readable");
        return status_t(HANDLER_DONE);
      }

      // check if we should use caching and this is an HTTP GET request
      if (cacheMaxAge > 0 &&
          _request->requestType() == HttpRequest::HTTP_REQUEST_GET) {
        // yes, then set a pro-caching header
        _response->setHeader("cache-control", strlen("cache-control"), maxAgeHeader);
      }

      std::string::size_type d = last.find_last_of('.');

      if (d != std::string::npos) {
        std::string suffix = last.substr(d + 1);

        if (suffix.size() > 0) {
          // look up the mimetype
          const char* mimetype = TRI_GetMimetype(suffix.c_str());

          if (mimetype != 0) {
            _response->setContentType(mimetype);

            return status_t(HANDLER_DONE);
          }
        }
        else {
          // note: changed the log level to debug. an unknown content-type does not justify a warning
          LOG_TRACE("unknown suffix '%s'", suffix.c_str());
        }
      }

      _response->setContentType(contentType);

      return status_t(HANDLER_DONE);
    }

    void PathHandler::handleError (TriagensError const&) {
      _response = createResponse(HttpResponse::SERVER_ERROR);
    }
  }
}
// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:


text:
module Jekyll

  class AmpGeneratorPage < Generator
    safe true

    def generate(site)
      paginate(site)
    end

    def paginate(site)
      amp_posts = site.posts.find_all {|post| post.data['is_extend'] != true}.sort_by {|post| -post.date.to_f}
      num_pages = AmpPagerPa.calculate_pages(amp_posts, site.config['paginate'].to_i)

      (1..num_pages).each do |page|
        pager = AmpPagerPa.new(site, page, amp_posts, num_pages)
        dir = File.join('amp', page > 1 ? "page#{page}" : '')
        page = AmpPagePa.new(site, site.source, dir)
        page.pager = pager
        site.pages << page
      end
    end
  end

  class AmpPagePa < Page
    def initialize(site, base, dir)
      @site = site
      @base = base
      @dir = dir
      @name = 'index.html'
      self.process(@name)
      self.read_yaml(File.join(base, '_layouts'), 'amp_list_post.html')
    end
  end

  class AmpPagerPa < Jekyll::Paginate::Pager

    def initialize(site, page, all_posts, num_pages = nil)
      super site, page, all_posts, num_pages
    end

    alias_method :original_to_liquid, :to_liquid

    def to_liquid
      liquid = original_to_liquid
      liquid
    end
  end

end


text:
#pragma once
#include <assert.h>
#include <cuda_fp16.h>
#include <cuda_runtime.h>

namespace fastertransformer {

void invokeReverseRollCol32(int8_t*       dst,
                            const int8_t* src,
                            int           batch,
                            int           window_num,
                            int           window_len,
                            int           window_size,
                            int           H,
                            int           W,
                            int           dim,
                            int           shift_size,
                            cudaStream_t  stream);

template<typename T>
void invokeReverseRoll(T*           dst,
                       const T*     src,
                       int          batch,
                       int          window_num,
                       int          window_len,
                       int          window_size,
                       int          H,
                       int          W,
                       int          dim,
                       int          shift_size,
                       cudaStream_t stream);

}  // namespace fastertransformer


text:
"""Perform quality checks on Gettext PO, XLIFF and TMX localization files.

Snippet files are created whenever a test fails.  These can be examined,
corrected and merged back into the originals using pomerge.

See:
http://docs.translatehouse.org/projects/translate-toolkit/en/latest/commands/pofilter.html
for examples and usage instructions and
http://docs.translatehouse.org/projects/translate-toolkit/en/latest/commands/pofilter_tests.html
for full descriptions of all tests.
"""

import os

from translate.storage import factory
from translate.storage.poheader import poheader
from translate.filters import checks
from translate.filters import autocorrect
from translate.misc import optrecurse

def build_checkerconfig(options):
    """Prepare the checker config from the given options.  This is mainly
    factored out for the sake of unit tests."""
    checkerconfig = checks.CheckerConfig(targetlanguage=options.targetlanguage)

    if options.notranslatefile:
        options.notranslatefile = os.path.expanduser(options.notranslatefile)

        if not os.path.exists(options.notranslatefile):
            self.error("notranslatefile %r does not exist" % options.notranslatefile)

        notranslatewords = [line.strip() for line in open(options.notranslatefile).readlines()]
        notranslatewords = dict.fromkeys([key for key in notranslatewords])

        checkerconfig.notranslatewords.update(notranslatewords)

    if options.musttranslatefile:
        options.musttranslatefile = os.path.expanduser(options.musttranslatefile)

        if not os.path.exists(options.musttranslatefile):
            self.error("musttranslatefile %r does not exist" % options.musttranslatefile)

        musttranslatewords = [line.strip() for line in open(options.musttranslatefile).readlines()]
        musttranslatewords = dict.fromkeys([key for key in musttranslatewords])

        checkerconfig.musttranslatewords.update(musttranslatewords)

    if options.validcharsfile:
        options.validcharsfile = os.path.expanduser(options.validcharsfile)

        if not os.path.exists(options.validcharsfile):
            self.error("validcharsfile %r does not exist" % options.validcharsfile)

        validchars = open(options.validcharsfile).read()

        checkerconfig.updatevalidchars(validchars)

    return checkerconfig

class pocheckfilter:

    def __init__(self, options, checkerclasses=None, checkerconfig=None):
        # excludefilters={}, limitfilters=None, includefuzzy=True, includereview=True, autocorrect=False):
        """Builds a checkfilter using the given checker (a list is allowed too)"""
        if checkerclasses is None:
            checkerclasses = [checks.StandardChecker, checks.StandardUnitChecker]

        self.checker = checks.TeeChecker(checkerconfig=checkerconfig,
                                         excludefilters=options.excludefilters,
                                         limitfilters=options.limitfilters,
                                         checkerclasses=checkerclasses,
                                         languagecode=checkerconfig.targetlanguage)
        self.options = options

    def getfilterdocs(self):
        """Lists the docs for filters available on checker."""
        filterdict = self.checker.getfilters()
        filterdocs = ["%s\t%s" % (name, filterfunc.__doc__) for (name, filterfunc) in filterdict.iteritems()]
        filterdocs.sort()

        return "\n".join(filterdocs)

    def filterunit(self, unit):
        """Runs filters on an element."""

        if unit.isheader():
            return []

        if not self.options.includefuzzy and unit.isfuzzy():
            return []

        if not self.options.includereview and unit.isreview():
            return []

        failures = self.checker.run_filters(unit, categorised=True)

        if failures and self.options.autocorrect:
            # we can't get away with bad unquoting / requoting if we're going to change the result...
            correction = autocorrect.correct(unit.source, unit.target)

            if correction:
                unit.target = correction
                return autocorrect
            else:
                # ignore failures we can't correct when in autocorrect mode
                return []

        return failures

    def filterfile(self, transfile):
        """Runs filters on a translation store object.

        :param transfile: A translation store object.
        :return: A new translation store object with the results of
                 the filter included.
        """
        newtransfile = type(transfile)()
        newtransfile.setsourcelanguage(transfile.getsourcelanguage())
        newtransfile.settargetlanguage(transfile.gettargetlanguage())

        for unit in transfile.units:
            filter_result = self.filterunit(unit)

            if filter_result:
                if filter_result != autocorrect:
                    for filter_name in filter_result.iterkeys():
                        filter_message = filter_result[filter_name]['message']

                        if self.options.addnotes:
                            unit.adderror(filter_name, filter_message)
                        if isinstance(filter_message, checks.SeriousFilterFailure):
                            unit.markfuzzy()

                newtransfile.addunit(unit)

        if isinstance(newtransfile, poheader):
            newtransfile.updateheader(add=True, **transfile.parseheader())

        return newtransfile

class FilterOptionParser(optrecurse.RecursiveOptionParser):
    """A specialized Option Parser for filter tools..."""

    def __init__(self, formats):
        """Construct the specialized Option Parser."""
        optrecurse.RecursiveOptionParser.__init__(self, formats)

        self.set_usage()
        self.add_option("-l", "--listfilters", action="callback", dest='listfilters',
            default=False, callback_kwargs={'dest_value': True},
            callback=self.parse_noinput, help="list filters available")

    def parse_noinput(self, option, opt, value, parser, *args, **kwargs):
        """This sets an option to *True*, but also sets input to *-*
        to prevent an error."""
        setattr(parser.values, option.dest, kwargs['dest_value'])
        parser.values.input = "-"

    def run(self):
        """Parses the arguments, and runs recursiveprocess with the
        resulting options."""
        (options, args) = self.parse_args()

        if options.filterclass is None:
            checkerclasses = [checks.StandardChecker, checks.StandardUnitChecker]
        else:
            checkerclasses = [options.filterclass, checks.StandardUnitChecker]

        checkerconfig = build_checkerconfig(options)
        options.checkfilter = pocheckfilter(options, checkerclasses, checkerconfig)

        if not options.checkfilter.checker.combinedfilters:
            self.error("No valid filters were specified")

        options.inputformats = self.inputformats
        options.outputoptions = self.outputoptions

        if options.listfilters:
            print options.checkfilter.getfilterdocs()
        else:
            self.recursiveprocess(options)

def runfilter(inputfile, outputfile, templatefile, checkfilter=None):
    """Reads in inputfile, filters using checkfilter, writes to outputfile."""
    fromfile = factory.getobject(inputfile)
    tofile = checkfilter.filterfile(fromfile)

    if tofile.isempty():
        return 0

    outputfile.write(str(tofile))

    return 1

def cmdlineparser():
    formats = {"po": ("po", runfilter), "pot": ("pot", runfilter),
            "xliff": ("xliff", runfilter), "xlf": ("xlf", runfilter),
            "tmx": ("tmx", runfilter),
            None: ("po", runfilter)}

    parser = FilterOptionParser(formats)

    parser.add_option("", "--review", dest="includereview",
        action="store_true", default=True,
        help="include units marked for review (default)")
    parser.add_option("", "--noreview", dest="includereview",
        action="store_false", default=True,
        help="exclude units marked for review")
    parser.add_option("", "--fuzzy", dest="includefuzzy",
        action="store_true", default=True,
        help="include units marked fuzzy (default)")
    parser.add_option("", "--nofuzzy", dest="includefuzzy",
        action="store_false", default=True,
        help="exclude units marked fuzzy")
    parser.add_option("", "--nonotes", dest="addnotes",
        action="store_false", default=True,
        help="don't add notes about the errors")
    parser.add_option("", "--autocorrect", dest="autocorrect",
        action="store_true", default=False,
        help="output automatic corrections where possible rather than describing issues")
    parser.add_option("", "--language", dest="targetlanguage", default=None,
        help="set target language code (e.g. af-ZA) [required for spell check and recommended in general]", metavar="LANG")
    parser.add_option("", "--openoffice", dest="filterclass",
        action="store_const", default=None, const=checks.OpenOfficeChecker,
        help="use the standard checks for OpenOffice translations")
    parser.add_option("", "--mozilla", dest="filterclass",
        action="store_const", default=None, const=checks.MozillaChecker,
        help="use the standard checks for Mozilla translations")
    parser.add_option("", "--drupal", dest="filterclass",
        action="store_const", default=None, const=checks.DrupalChecker,
        help="use the standard checks for Drupal translations")
    parser.add_option("", "--gnome", dest="filterclass",
        action="store_const", default=None, const=checks.GnomeChecker,
        help="use the standard checks for Gnome translations")
    parser.add_option("", "--kde", dest="filterclass",
        action="store_const", default=None, const=checks.KdeChecker,
        help="use the standard checks for KDE translations")
    parser.add_option("", "--wx", dest="filterclass",
        action="store_const", default=None, const=checks.KdeChecker,
        help="use the standard checks for wxWidgets translations")
    parser.add_option("", "--excludefilter", dest="excludefilters",
        action="append", default=[], type="string", metavar="FILTER",
        help="don't use FILTER when filtering")
    parser.add_option("-t", "--test", dest="limitfilters",
        action="append", default=None, type="string", metavar="FILTER",
        help="only use test FILTERs specified with this option when filtering")
    parser.add_option("", "--notranslatefile", dest="notranslatefile",
        default=None, type="string", metavar="FILE",
        help="read list of untranslatable words from FILE (must not be translated)")
    parser.add_option("", "--musttranslatefile", dest="musttranslatefile",
        default=None, type="string", metavar="FILE",
        help="read list of translatable words from FILE (must be translated)")
    parser.add_option("", "--validcharsfile", dest="validcharsfile",
        default=None, type="string", metavar="FILE",
        help="read list of all valid characters from FILE (must be in UTF-8)")

    parser.passthrough.append('checkfilter')
    parser.description = __doc__

    return parser

def main():
    parser = cmdlineparser()
    parser.run()

if __name__ == '__main__':
    main()


text:
package org.apache.webdav.lib;

import java.util.Map;

/**
 * The Subscriber interface
 *
 */
public interface Subscriber {
    public final static String URI = "uri";
    public final static String SOURCE_URI = "source-uri";
    public final static String TARGET_URI = "target-uri";

    public void notify(String uri, Map information);
}


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

module ActionView
  module Helpers
    # Provides a set of helpers for calling Prototype JavaScript functions,
    # including functionality to call remote methods using
    # Ajax[http://www.adaptivepath.com/publications/essays/archives/000385.php].
    # This means that you can call actions in your controllers without
    # reloading the page, but still update certain parts of it using
    # injections into the DOM. The common use case is having a form that adds
    # a new element to a list without reloading the page.
    #
    # To be able to use these helpers, you must include the Prototype
    # JavaScript framework in your pages. See the documentation for
    # ActionView::Helpers::JavaScriptHelper for more information on including
    # the necessary JavaScript.
    #
    # See link_to_remote for documentation of options common to all Ajax
    # helpers.
    #
    # See also ActionView::Helpers::ScriptaculousHelper for helpers which work
    # with the Scriptaculous controls and visual effects library.
    #
    # See JavaScriptGenerator for information on updating multiple elements
    # on the page in an Ajax response.
    module PrototypeHelper
      unless const_defined? :CALLBACKS
        CALLBACKS    = Set.new([ :uninitialized, :loading, :loaded,
                         :interactive, :complete, :failure, :success ] +
                         (100..599).to_a)
        AJAX_OPTIONS = Set.new([ :before, :after, :condition, :url,
                         :asynchronous, :method, :insertion, :position,
                         :form, :with, :update, :script ]).merge(CALLBACKS)
      end

      # Returns a link to a remote action defined by <tt>options[:url]</tt>
      # (using the url_for format) that's called in the background using
      # XMLHttpRequest. The result of that request can then be inserted into a
      # DOM object whose id can be specified with <tt>options[:update]</tt>.
      # Usually, the result would be a partial prepared by the controller with
      # either render_partial or render_partial_collection.
      #
      # Examples:
      #   link_to_remote "Delete this post", :update => "posts",
      #     :url => { :action => "destroy", :id => post.id }
      #   link_to_remote(image_tag("refresh"), :update => "emails",
      #     :url => { :action => "list_emails" })
      #
      # You can also specify a hash for <tt>options[:update]</tt> to allow for
      # easy redirection of output to an other DOM element if a server-side
      # error occurs:
      #
      # Example:
      #   link_to_remote "Delete this post",
      #     :url => { :action => "destroy", :id => post.id },
      #     :update => { :success => "posts", :failure => "error" }
      #
      # Optionally, you can use the <tt>options[:position]</tt> parameter to
      # influence how the target DOM element is updated. It must be one of
      # <tt>:before</tt>, <tt>:top</tt>, <tt>:bottom</tt>, or <tt>:after</tt>.
      #
      # By default, these remote requests are processed asynchronous during
      # which various JavaScript callbacks can be triggered (for progress
      # indicators and the likes). All callbacks get access to the
      # <tt>request</tt> object, which holds the underlying XMLHttpRequest.
      #
      # To access the server response, use <tt>request.responseText</tt>, to
      # find out the HTTP status, use <tt>request.status</tt>.
      #
      # Example:
      #   link_to_remote word,
      #     :url => { :action => "undo", :n => word_counter },
      #     :complete => "undoRequestCompleted(request)"
      #
      # The callbacks that may be specified are (in order):
      #
      # <tt>:loading</tt>::       Called when the remote document is being
      #                           loaded with data by the browser.
      # <tt>:loaded</tt>::        Called when the browser has finished loading
      #                           the remote document.
      # <tt>:interactive</tt>::   Called when the user can interact with the
      #                           remote document, even though it has not
      #                           finished loading.
      # <tt>:success</tt>::       Called when the XMLHttpRequest is completed,
      #                           and the HTTP status code is in the 2XX range.
      # <tt>:failure</tt>::       Called when the XMLHttpRequest is completed,
      #                           and the HTTP status code is not in the 2XX
      #                           range.
      # <tt>:complete</tt>::      Called when the XMLHttpRequest is complete
      #                           (fires after success/failure if they are
      #                           present).
      #
      # You can further refine <tt>:success</tt> and <tt>:failure</tt> by
      # adding additional callbacks for specific status codes.
      #
      # Example:
      #   link_to_remote word,
      #     :url => { :action => "action" },
      #     404 => "alert('Not found...? Wrong URL...?')",
      #     :failure => "alert('HTTP Error ' + request.status + '!')"
      #
      # A status code callback overrides the success/failure handlers if
      # present.
      #
      # If you for some reason or another need synchronous processing (that'll
      # block the browser while the request is happening), you can specify
      # <tt>options[:type] = :synchronous</tt>.
      #
      # You can customize further browser side call logic by passing in
      # JavaScript code snippets via some optional parameters. In their order
      # of use these are:
      #
      # <tt>:confirm</tt>::      Adds confirmation dialog.
      # <tt>:condition</tt>::    Perform remote request conditionally
      #                          by this expression. Use this to
      #                          describe browser-side conditions when
      #                          request should not be initiated.
      # <tt>:before</tt>::       Called before request is initiated.
      # <tt>:after</tt>::        Called immediately after request was
      #                          initiated and before <tt>:loading</tt>.
      # <tt>:submit</tt>::       Specifies the DOM element ID that's used
      #                          as the parent of the form elements. By
      #                          default this is the current form, but
      #                          it could just as well be the ID of a
      #                          table row or any other DOM element.
      def link_to_remote(name, options = {}, html_options = {})
        link_to_function(name, remote_function(options), html_options)
      end

      # Periodically calls the specified url (<tt>options[:url]</tt>) every
      # <tt>options[:frequency]</tt> seconds (default is 10). Usually used to
      # update a specified div (<tt>options[:update]</tt>) with the results
      # of the remote call. The options for specifying the target with :url
      # and defining callbacks is the same as link_to_remote.
      def periodically_call_remote(options = {})
         frequency = options[:frequency] || 10 # every ten seconds by default
         code = "new PeriodicalExecuter(function() {#{remote_function(options)}}, #{frequency})"
         javascript_tag(code)
      end

      # Returns a form tag that will submit using XMLHttpRequest in the
      # background instead of the regular reloading POST arrangement. Even
      # though it's using JavaScript to serialize the form elements, the form
      # submission will work just like a regular submission as viewed by the
      # receiving side (all elements available in <tt>params</tt>). The options for
      # specifying the target with :url and defining callbacks is the same as
      # link_to_remote.
      #
      # A "fall-through" target for browsers that doesn't do JavaScript can be
      # specified with the :action/:method options on :html.
      #
      # Example:
      #   form_remote_tag :html => { :action =>
      #     url_for(:controller => "some", :action => "place") }
      #
      # The Hash passed to the :html key is equivalent to the options (2nd)
      # argument in the FormTagHelper.form_tag method.
      #
      # By default the fall-through action is the same as the one specified in
      # the :url (and the default method is :post).
      def form_remote_tag(options = {})
        options[:form] = true

        options[:html] ||= {}
        options[:html][:onsubmit] = "#{remote_function(options)}; return false;"
        options[:html][:action] = options[:html][:action] || url_for(options[:url])
        options[:html][:method] = options[:html][:method] || "post"

        tag("form", options[:html], true)
      end

      # Works like form_remote_tag, but uses form_for semantics.
      def remote_form_for(object_name, *args, &proc)
        options = args.last.is_a?(Hash) ? args.pop : {}
        concat(form_remote_tag(options), proc.binding)
        fields_for(object_name, *(args << options), &proc)
        concat('</form>', proc.binding)
      end
      alias_method :form_remote_for, :remote_form_for

      # Returns a button input tag that will submit form using XMLHttpRequest
      # in the background instead of regular reloading POST arrangement.
      # <tt>options</tt> argument is the same as in <tt>form_remote_tag</tt>.
      def submit_to_remote(name, value, options = {})
        options[:with] ||= 'Form.serialize(this.form)'

        options[:html] ||= {}
        options[:html][:type] = 'button'
        options[:html][:onclick] = "#{remote_function(options)}; return false;"
        options[:html][:name] = name
        options[:html][:value] = value

        tag("input", options[:html], false)
      end

      # Returns a JavaScript function (or expression) that'll update a DOM
      # element according to the options passed.
      #
      # * <tt>:content</tt>: The content to use for updating. Can be left out
      #   if using block, see example.
      # * <tt>:action</tt>: Valid options are :update (assumed by default),
      #   :empty, :remove
      # * <tt>:position</tt> If the :action is :update, you can optionally
      #   specify one of the following positions: :before, :top, :bottom,
      #   :after.
      #
      # Examples:
      #   <%= javascript_tag(update_element_function("products",
      #     :position => :bottom, :content => "
New product!
")) %>
      #
      #   <% replacement_function = update_element_function("products") do %>
      #
Product 1

      #
Product 2

      #   <% end %>
      #   <%= javascript_tag(replacement_function) %>
      #
      # This method can also be used in combination with remote method call
      # where the result is evaluated afterwards to cause multiple updates on
      # a page. Example:
      #
      #   # Calling view
      #   <%= form_remote_tag :url => { :action => "buy" },
      #     :complete => evaluate_remote_response %>
      #   all the inputs here...
      #
      #   # Controller action
      #   def buy
      #     @product = Product.find(1)
      #   end
      #
      #   # Returning view
      #   <%= update_element_function(
      #         "cart", :action => :update, :position => :bottom,
      #         :content => "
New Product: #{@product.name}
")) %>
      #   <% update_element_function("status", :binding => binding) do %>
      #     You've bought a new product!
      #   <% end %>
      #
      # Notice how the second call doesn't need to be in an ERb output block
      # since it uses a block and passes in the binding to render directly.
      # This trick will however only work in ERb (not Builder or other
      # template forms).
      #
      # See also JavaScriptGenerator and update_page.
      def update_element_function(element_id, options = {}, &block)
        content = escape_javascript(options[:content] || '')
        content = escape_javascript(capture(&block)) if block

        javascript_function = case (options[:action] || :update)
          when :update
            if options[:position]
              "new Insertion.#{options[:position].to_s.camelize}('#{element_id}','#{content}')"
            else
              "$('#{element_id}').innerHTML = '#{content}'"
            end

          when :empty
            "$('#{element_id}').innerHTML = ''"

          when :remove
            "Element.remove('#{element_id}')"

          else
            raise ArgumentError, "Invalid action, choose one of :update, :remove, :empty"
        end

        javascript_function << ";\n"
        options[:binding] ? concat(javascript_function, options[:binding]) : javascript_function
      end

      # Returns 'eval(request.responseText)' which is the JavaScript function
      # that form_remote_tag can call in :complete to evaluate a multiple
      # update return document using update_element_function calls.
      def evaluate_remote_response
        "eval(request.responseText)"
      end

      # Returns the JavaScript needed for a remote function.
      # Takes the same arguments as link_to_remote.
      #
      # Example:
      #   <select id="options" onchange="<%= remote_function(:update => "options",
      #       :url => { :action => :update_options }) %>">
      #     <option value="0">Hello</option>
      #     <option value="1">World</option>
      #   </select>
      def remote_function(options)
        javascript_options = options_for_ajax(options)

        update = ''
        if options[:update] and options[:update].is_a?Hash
          update  = []
          update << "success:'#{options[:update][:success]}'" if options[:update][:success]
          update << "failure:'#{options[:update][:failure]}'" if options[:update][:failure]
          update  = '{' + update.join(',') + '}'
        elsif options[:update]
          update << "'#{options[:update]}'"
        end

        function = update.empty? ?
          "new Ajax.Request(" :
          "new Ajax.Updater(#{update}, "

        url_options = options[:url]
        url_options = url_options.merge(:escape => false) if url_options.is_a? Hash
        function << "'#{url_for(url_options)}'"
        function << ", #{javascript_options})"

        function = "#{options[:before]}; #{function}" if options[:before]
        function = "#{function}; #{options[:after]}"  if options[:after]
        function = "if (#{options[:condition]}) { #{function}; }" if options[:condition]
        function = "if (confirm('#{escape_javascript(options[:confirm])}')) { #{function}; }" if options[:confirm]

        return function
      end

      # Observes the field with the DOM ID specified by +field_id+ and makes
      # an Ajax call when its contents have changed.
      #
      # Required +options+ are either of:
      # <tt>:url</tt>::       +url_for+-style options for the action to call
      #                       when the field has changed.
      # <tt>:function</tt>::  Instead of making a remote call to a URL, you
      #                       can specify a function to be called instead.
      #
      # Additional options are:
      # <tt>:frequency</tt>:: The frequency (in seconds) at which changes to
      #                       this field will be detected. Not setting this
      #                       option at all or to a value equal to or less than
      #                       zero will use event based observation instead of
      #                       time based observation.
      # <tt>:update</tt>::    Specifies the DOM ID of the element whose
      #                       innerHTML should be updated with the
      #                       XMLHttpRequest response text.
      # <tt>:with</tt>::      A JavaScript expression specifying the
      #                       parameters for the XMLHttpRequest. This defaults
      #                       to 'value', which in the evaluated context
      #                       refers to the new field value. If you specify a
      #                       string without a "=", it'll be extended to mean
      #                       the form key that the value should be assigned to.
      #                       So :with => "term" gives "'term'=value". If a "=" is
      #                       present, no extension will happen.
      # <tt>:on</tt>::        Specifies which event handler to observe. By default,
      #                       it's set to "changed" for text fields and areas and
      #                       "click" for radio buttons and checkboxes. With this,
      #                       you can specify it instead to be "blur" or "focus" or
      #                       any other event.
      #
      # Additionally, you may specify any of the options documented in
      # link_to_remote.
      def observe_field(field_id, options = {})
        if options[:frequency] && options[:frequency] > 0
          build_observer('Form.Element.Observer', field_id, options)
        else
          build_observer('Form.Element.EventObserver', field_id, options)
        end
      end

      # Like +observe_field+, but operates on an entire form identified by the
      # DOM ID +form_id+. +options+ are the same as +observe_field+, except
      # the default value of the <tt>:with</tt> option evaluates to the
      # serialized (request string) value of the form.
      def observe_form(form_id, options = {})
        if options[:frequency]
          build_observer('Form.Observer', form_id, options)
        else
          build_observer('Form.EventObserver', form_id, options)
        end
      end

      # All the methods were moved to GeneratorMethods so that
      # #include_helpers_from_context has nothing to overwrite.
      class JavaScriptGenerator #:nodoc:
        def initialize(context, &block) #:nodoc:
          @context, @lines = context, []
          include_helpers_from_context
          @context.instance_exec(self, &block)
        end

        private
          def include_helpers_from_context
            @context.extended_by.each do |mod|
              extend mod unless mod.name =~ /^ActionView::Helpers/
            end
            extend GeneratorMethods
          end

        # JavaScriptGenerator generates blocks of JavaScript code that allow you
        # to change the content and presentation of multiple DOM elements.  Use
        # this in your Ajax response bodies, either in a


text:
The latest API to check version is operatingSystemVersion method of [NSProcessInfo](https://developer.apple.com/reference/foundation/nsprocessinfo).

## Usage

```objc
// complete form
if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){.majorVersion = 9, .minorVersion = 1, .patchVersion = 0}]) {
    NSLog(@"> iOS 9.1");
}

// compact form
if ([NSProcessInfo.processInfo isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){9,1,0}]) {
    NSLog(@"> iOS 9.1");
}
```

## Example

```objc
LAContext *laContext = [[LAContext alloc] init];
bool available;
NSError *error;

if ([NSProcessInfo.processInfo isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){9,0,0}]) {
    available = [laContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthentication error:&error];
} else {
    available = [laContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error];
}
```