text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

#nullable disable

using System;
using System.Drawing;
using System.Runtime.InteropServices;

namespace osu.Framework.Platform.Windows.Native
{
    internal static class Input
    {
        [DllImport("user32.dll")]
        public static extern bool RegisterRawInputDevices(
            [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)]
            RawInputDevice[] pRawInputDevices,
            int uiNumDevices,
            int cbSize);

        [DllImport("user32.dll")]
        public static extern int GetRawInputData(IntPtr hRawInput, RawInputCommand uiCommand, out RawInputData pData, ref int pcbSize, int cbSizeHeader);

        internal static Rectangle VirtualScreenRect => new Rectangle(
            GetSystemMetrics(SM_XVIRTUALSCREEN),
            GetSystemMetrics(SM_YVIRTUALSCREEN),
            GetSystemMetrics(SM_CXVIRTUALSCREEN),
            GetSystemMetrics(SM_CYVIRTUALSCREEN));

        internal const int WM_INPUT = 0x00FF;

        [DllImport("user32.dll")]
        public static extern int GetSystemMetrics(int nIndex);

        internal static Rectangle GetVirtualScreenRect() => new Rectangle(
            GetSystemMetrics(SM_XVIRTUALSCREEN),
            GetSystemMetrics(SM_YVIRTUALSCREEN),
            GetSystemMetrics(SM_CXVIRTUALSCREEN),
            GetSystemMetrics(SM_CYVIRTUALSCREEN)
        );

        public const int SM_XVIRTUALSCREEN = 76;
        public const int SM_YVIRTUALSCREEN = 77;
        public const int SM_CXVIRTUALSCREEN = 78;
        public const int SM_CYVIRTUALSCREEN = 79;

        public const long MI_WP_SIGNATURE = 0xFF515700;
        public const long MI_WP_SIGNATURE_MASK = 0xFFFFFF00;

        ///
        /// Flag distinguishing touch input from mouse input in <see cref="WM_INPUT"/> events.
        ///
        /// <remarks>
        /// https://docs.microsoft.com/en-us/windows/win32/tablet/system-events-and-mouse-messages
        /// <para>Additionally, the eighth bit, masked by 0x80, is used to differentiate touch input from pen input (0 = pen, 1 = touch).</para>
        /// </remarks>
        private const long touch_flag = 0x80;

        ///
        /// https://docs.microsoft.com/en-us/windows/win32/tablet/system-events-and-mouse-messages
        ///
        /// <param name="dw"><see cref="GetMessageExtraInfo"/> for the current <see cref="WM_INPUT"/> event.</param>
        /// <returns><c>true</c> if this <see cref="WM_INPUT"/> event is from a finger touch, <c>false</c> if it's from mouse or pen input.</returns>
        public static bool IsTouchEvent(long dw) => (dw & MI_WP_SIGNATURE_MASK) == MI_WP_SIGNATURE && HasTouchFlag(dw);

        /// <param name="extraInformation"><see cref="RawMouse.ExtraInformation"/> or <see cref="GetMessageExtraInfo"/></param>
        /// <returns>Whether <paramref name="extraInformation"/> has the <see cref="touch_flag"/> set.</returns>
        public static bool HasTouchFlag(long extraInformation) => (extraInformation & touch_flag) == touch_flag;

        [DllImport("user32.dll", SetLastError = false)]
        public static extern long GetMessageExtraInfo();
    }

    ///
    /// Value type for raw input.
    ///
    public struct RawInputData
    {
        /// Header for the data.
        public RawInputHeader Header;

        /// Mouse raw input data.
        public RawMouse Mouse;

        // This struct is a lot larger but the remaining elements have been omitted until required (Keyboard / HID / Touch).
    }

    ///
    /// Contains information about the state of the mouse.
    ///
    public struct RawMouse
    {
        ///
        /// The mouse state.
        ///
        public RawMouseFlags Flags;

        ///
        /// Flags for the event.
        ///
        public RawMouseButtons ButtonFlags;

        ///
        /// If the mouse wheel is moved, this will contain the delta amount.
        ///
        public short ButtonData;

        ///
        /// Raw button data.
        ///
        public uint RawButtons;

        ///
        /// The motion in the X direction. This is signed relative motion or
        /// absolute motion, depending on the value of usFlags.
        ///
        public int LastX;

        ///
        /// The motion in the Y direction. This is signed relative motion or absolute motion,
        /// depending on the value of usFlags.
        ///
        public int LastY;

        ///
        /// The device-specific additional information for the event.
        ///
        public uint ExtraInformation;
    }

    ///
    /// Enumeration containing the flags for raw mouse data.
    ///
    [Flags]
    public enum RawMouseFlags : ushort
    {
        /// Relative to the last position.
        MoveRelative = 0,

        /// Absolute positioning.
        MoveAbsolute = 1,

        /// Coordinate data is mapped to a virtual desktop.
        VirtualDesktop = 2,

        /// Attributes for the mouse have changed.
        AttributesChanged = 4,

        /// WM_MOUSEMOVE and WM_INPUT don't coalesce
        MoveNoCoalesce = 8,
    }

    ///
    /// Enumeration containing the button data for raw mouse input.
    ///
    public enum RawMouseButtons : ushort
    {
        /// No button.
        None = 0,

        /// Left (button 1) down.
        LeftDown = 0x0001,

        /// Left (button 1) up.
        LeftUp = 0x0002,

        /// Right (button 2) down.
        RightDown = 0x0004,

        /// Right (button 2) up.
        RightUp = 0x0008,

        /// Middle (button 3) down.
        MiddleDown = 0x0010,

        /// Middle (button 3) up.
        MiddleUp = 0x0020,

        /// Button 4 down.
        Button4Down = 0x0040,

        /// Button 4 up.
        Button4Up = 0x0080,

        /// Button 5 down.
        Button5Down = 0x0100,

        /// Button 5 up.
        Button5Up = 0x0200,

        /// Mouse wheel moved.
        MouseWheel = 0x0400
    }

    ///
    /// Enumeration contanining the command types to issue.
    ///
    public enum RawInputCommand
    {
        ///
        /// Get input data.
        ///
        Input = 0x10000003,

        ///
        /// Get header data.
        ///
        Header = 0x10000005
    }

    ///
    /// Enumeration containing the type device the raw input is coming from.
    ///
    public enum RawInputType
    {
        ///
        /// Mouse input.
        ///
        Mouse = 0,

        ///
        /// Keyboard input.
        ///
        Keyboard = 1,

        ///
        /// Another device that is not the keyboard or the mouse.
        ///
        HID = 2
    }

#pragma warning disable IDE1006 // Naming style

    ///
    /// Value type for a raw input header.
    ///
    [StructLayout(LayoutKind.Sequential)]
    public struct RawInputHeader
    {
        /// Type of device the input is coming from.
        public RawInputType Type;

        /// Size of the packet of data.
        public int Size;

        /// Handle to the device sending the data.
        public IntPtr Device;

        /// wParam from the window message.
        public IntPtr wParam;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct RawInputDevice
    {
        /// Top level collection Usage page for the raw input device.
        public HIDUsagePage UsagePage;

        /// Top level collection Usage for the raw input device.
        public HIDUsage Usage;

        /// Mode flag that specifies how to interpret the information provided by UsagePage and Usage.
        public RawInputDeviceFlags Flags;

        /// Handle to the target device. If NULL, it follows the keyboard focus.
        public IntPtr WindowHandle;
    }

#pragma warning restore IDE1006

    /// Enumeration containing flags for a raw input device.
    public enum RawInputDeviceFlags
    {
        /// No flags.
        None = 0,

        /// If set, this removes the top level collection from the inclusion list. This tells the operating system to stop reading from a device which matches the top level collection.
        Remove = 0x00000001,

        /// If set, this specifies the top level collections to exclude when reading a complete usage page. This flag only affects a TLC whose usage page is already specified with PageOnly.
        Exclude = 0x00000010,

        /// If set, this specifies all devices whose top level collection is from the specified usUsagePage. Note that Usage must be zero. To exclude a particular top level collection, use Exclude.
        PageOnly = 0x00000020,

        /// If set, this prevents any devices specified by UsagePage or Usage from generating legacy messages. This is only for the mouse and keyboard.
        NoLegacy = 0x00000030,

        /// If set, this enables the caller to receive the input even when the caller is not in the foreground. Note that WindowHandle must be specified.
        InputSink = 0x00000100,

        /// If set, the mouse button click does not activate the other window.
        CaptureMouse = 0x00000200,

        /// If set, the application-defined keyboard device hotkeys are not handled. However, the system hotkeys; for example, ALT+TAB and CTRL+ALT+DEL, are still handled. By default, all keyboard hotkeys are handled. NoHotKeys can be specified even if NoLegacy is not specified and WindowHandle is NULL.
        NoHotKeys = 0x00000200,

        /// If set, application keys are handled.  NoLegacy must be specified.  Keyboard only.
        AppKeys = 0x00000400
    }

    public enum HIDUsage : ushort
    {
        Pointer = 0x01,
        Mouse = 0x02,
        Joystick = 0x04,
        Gamepad = 0x05,
        Keyboard = 0x06,
        Keypad = 0x07,
        SystemControl = 0x80,
    }

    public enum HIDUsagePage : ushort
    {
        Undefined = 0x00,
        Generic = 0x01,
        Simulation = 0x02,
        VR = 0x03,
        Sport = 0x04,
        Game = 0x05,
        Keyboard = 0x07,
        LED = 0x08,
        Button = 0x09,
        Ordinal = 0x0A,
        Telephony = 0x0B,
        Consumer = 0x0C,
        Digitizer = 0x0D,
        PID = 0x0F,
        Unicode = 0x10,
        AlphaNumeric = 0x14,
        Medical = 0x40,
        MonitorPage0 = 0x80,
        MonitorPage1 = 0x81,
        MonitorPage2 = 0x82,
        MonitorPage3 = 0x83,
        PowerPage0 = 0x84,
        PowerPage1 = 0x85,
        PowerPage2 = 0x86,
        PowerPage3 = 0x87,
        BarCode = 0x8C,
        Scale = 0x8D,
        MSR = 0x8E
    }
}


text:
/* eslint-disable import/no-extraneous-dependencies, import/no-unresolved, import/extensions */

import './App.story'

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Acme\DemoBundle\Service;

use Acme\DemoBundle\Model\Order;

/**
 * @author zuo
 */
class TotalPriceCounter
{
    /**
     * @var DiscountSpecificationInterface[]
     */
    private $discounts;

    public function __construct()
    {
        $this->discounts = array();
    }

    public function addDiscountSpecification(DiscountSpecificationIterface $discount)
    {
        $this->discounts[] = $discount;
    }

    /**
     * Count total price of order
     *
     * @param  Order  $order
     * @return double
     */
    public function count(Order $order)
    {
        foreach ($this->discounts as $discount) {
            if ($discount->isSatisfiedBy($order)) {
                $discount->apply($order);
            }
        }

        $this->countTotalPrice($order);

        return $order->total;
    }

    private function countTotalPrice(Order $order)
    {
        $totalPrice = 0;

        foreach ($order->products as $product) {
            $totalPrice += $product->price;
        }

        $order->total = $totalPrice;
    }
}


text:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="false">
        <shape android:shape="oval">
            <solid android:color="#8c9eff"/>
        </shape>
    </item>
    <item android:state_pressed="true">
        <shape android:shape="oval">
            <solid android:color="#566097"/>
        </shape>
    </item>
</selector>


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

<title>DSAParams (Java Platform SE 8 )</title>
<meta name="date" content="2014-12-17">
<meta name="keywords" content="java.security.interfaces.DSAParams interface">
<meta name="keywords" content="getP()">
<meta name="keywords" content="getQ()">
<meta name="keywords" content="getG()">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

compact1, compact2, compact3

java.security.interfaces

Interface DSAParams

All Known Implementing Classes:

DSAParameterSpec

public interface DSAParams

Interface to a DSA-specific set of key parameters, which defines a
 DSA key family. DSA (Digital Signature Algorithm) is defined
 in NIST's FIPS-186.

See Also:

DSAKey,
Key,
Signature

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

BigInteger
getG()

Returns the base, g.

BigInteger
getP()

Returns the prime, p.

BigInteger
getQ()

Returns the subprime, q.

Method Detail

getP

BigInteger getP()

Returns the prime, p.

Returns:

the prime, p.

getQ

BigInteger getQ()

Returns the subprime, q.

Returns:

the subprime, q.

getG

BigInteger getG()

Returns the base, g.

Returns:

the base, g.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
#ifndef _LINUX_SUNRPC_STATS_H
#define _LINUX_SUNRPC_STATS_H

#include <linux/proc_fs.h>

struct rpc_stat {
	const struct rpc_program *program;

	unsigned int		netcnt,
				netudpcnt,
				nettcpcnt,
				nettcpconn,
				netreconn;
	unsigned int		rpccnt,
				rpcretrans,
				rpcauthrefresh,
				rpcgarbage;
};

struct svc_stat {
	struct svc_program *	program;

	unsigned int		netcnt,
				netudpcnt,
				nettcpcnt,
				nettcpconn;
	unsigned int		rpccnt,
				rpcbadfmt,
				rpcbadauth,
				rpcbadclnt;
};

struct net;
#ifdef CONFIG_PROC_FS
int			rpc_proc_init(struct net *);
void			rpc_proc_exit(struct net *);
#else
static inline int rpc_proc_init(struct net *net)
{
	return 0;
}

static inline void rpc_proc_exit(struct net *net)
{
}
#endif

#ifdef MODULE
void			rpc_modcount(struct inode *, int);
#endif

#ifdef CONFIG_PROC_FS
struct proc_dir_entry *	rpc_proc_register(struct net *,struct rpc_stat *);
void			rpc_proc_unregister(struct net *,const char *);
void			rpc_proc_zero(const struct rpc_program *);
struct proc_dir_entry *	svc_proc_register(struct net *, struct svc_stat *,
					  const struct file_operations *);
void			svc_proc_unregister(struct net *, const char *);

void			svc_seq_show(struct seq_file *,
				     const struct svc_stat *);
#else

static inline struct proc_dir_entry *rpc_proc_register(struct net *net, struct rpc_stat *s) { return NULL; }
static inline void rpc_proc_unregister(struct net *net, const char *p) {}
static inline void rpc_proc_zero(const struct rpc_program *p) {}

static inline struct proc_dir_entry *svc_proc_register(struct net *net, struct svc_stat *s,
						       const struct file_operations *f) { return NULL; }
static inline void svc_proc_unregister(struct net *net, const char *p) {}

static inline void svc_seq_show(struct seq_file *seq,
				const struct svc_stat *st) {}
#endif

#endif /* _LINUX_SUNRPC_STATS_H */


text:
<?php

namespace PH7;

defined('PH7') or exit('Restricted access');

// Default contents value
$sHtml = '';

/*** Begin Contents ***/

$sHtml .= t('Done!');

/*** End Contents ***/

// Output!
return $sHtml;


text:
package com.lularoe.erinfetz.imagecapture;

import java.util.*;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources.Theme;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Typeface;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

/**
 * Created by erinf_000 on 5/4/2017.
 */

public class FontManager {
    private static final String TAG = FontManager.class.getSimpleName();
    private static FontManager INSTANCE;
    private static final Map<String, Typeface> mCache = new HashMap<String, Typeface>();
    private final Context mContext;

    public static boolean isLayoutEditorInterfaceCompatible(View target) {
        //Since API M, we can previsualize font in Layout Editor !
        if (target.isInEditMode()) {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }

    public static FontManager getInstance(Context context) {
        if (INSTANCE == null) {
            INSTANCE = new FontManager(context);
        }
        return INSTANCE;
    }

    public static final String MAVEN_PRO_LIGHT = "MavenProLight-300.otf";
    public static final String MUSEO_SANS_500 = "MuseoSans-500.otf";
    public static final String STEELFISH_REG = "steelfish rg.ttf";

    private FontManager(Context context) {
        mContext = context;
    }
    public Typeface getTypeface(String name) {
        return getTypeface(name, Typeface.NORMAL);
    }
    public Typeface getTypeface(String name, int style) {
        synchronized (mCache) {
            if (!mCache.containsKey(name)) {
                Typeface t = Typeface.createFromAsset(mContext.getAssets(),
                        String.format("fonts/%s", name));

                mCache.put(name, t);
                return Typeface.create(t, style);
            } else {
                Typeface t = mCache.get(name);
                return Typeface.create(t, style);
            }
        }
    }
    public boolean setTypeface(TextView target, String fontName) {
        return setTypeface(target, fontName, Typeface.NORMAL);
    }
    public boolean setTextStyle(TextView target, int textStyle) {
        ExtraFontData data = getFontData(target);
        data.style = textStyle;
        if (data.font == null) {
            // Default Android font
            target.setTypeface(target.getTypeface(), textStyle);
            return true;
        } else {
            // Custom font
            return setTypeface(target, data.font, textStyle);
        }
    }
    public boolean setTypeface(TextView target, String fontName, int textStyle) {
        Typeface tf = null;
        try {
            tf = getTypeface(fontName, textStyle);

            // If the font was retrieved successfully, store it in the data.
            ExtraFontData data = getFontData(target);
            data.font = fontName;
            data.style = textStyle;

        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "Could not get typeface " + fontName + " with style " + textStyle);
            return false;
        }

        target.setTypeface(tf);
        return true;
    }

    public static void applyFont(TextView target, AttributeSet attrs, int defStyle, Context context) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) {
            if (target == null || !isLayoutEditorInterfaceCompatible(target))
                return;
        } else {

            if (target == null) {
                return;
            }
        }

        ExtraFontData data = getFontData(target);

        // First get the font attribute from the textAppearance:
        Theme theme = target.getContext().getTheme();
        // Get the text appearance that's currently in use
        TypedArray a = theme.obtainStyledAttributes(attrs,
                new int[]{android.R.attr.textAppearance}, defStyle, 0);
        int textAppearanceStyle = -1;
        try {
            textAppearanceStyle = a.getResourceId(0, -1);
        } finally {
            a.recycle();
        }
        // Get the font and style defined in the text appearance
        TypedArray appearance = null;
        if (textAppearanceStyle != -1)
            appearance = theme.obtainStyledAttributes(textAppearanceStyle,
                    R.styleable.Fonts);
        getAttributes(appearance, data);

        // Then get the font attribute from the FontTextView itself:
        a = theme.obtainStyledAttributes(attrs, R.styleable.Fonts, defStyle, 0);
        getAttributes(a, data);

        // Now we have the font, apply it
        if (data.font != null) {
            getInstance(context).setTypeface(target, data.font, data.style);
        }

    }

    /**
     * Fetches the font attributes from the given typed array and overrides all
     * properties in the given data holder that are present in the typed array.
     *
     * @param a    A TypedArray from which the attributes will be fetched. It will
     *             be recycled if not null.
     * @param data The data holder in which all read properties are stored.
     */
    private static void getAttributes(final TypedArray a, final ExtraFontData data) {
        if (a == null)
            return;
        try {
            // Iterate over all attributes in 'Android-style'
            // (similar to the implementation of the TextView constructor)
            int n = a.getIndexCount();
            for (int i = 0; i < n; i++) {
                int attr = a.getIndex(i);
                if (attr == R.styleable.Fonts_typeface) {
                    data.font = a.getString(attr);
                } else if (attr == R.styleable.Fonts_android_textStyle) {
                    data.style = a.getInt(attr, Typeface.NORMAL);
                } else if (attr == R.styleable.Fonts__BorderWidth) {
                    data.borderWidth = a.getDimensionPixelSize(attr, 0);
                } else if (attr == R.styleable.Fonts__BorderColor) {
                    data.borderColor = a.getColor(attr, Color.BLACK);
                }
            }
        } finally {
            a.recycle();
        }
    }

    public static void onDrawHelper(Canvas canvas, TextView target, DrawCallback drawCallback) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) {
            if (target.isInEditMode())
                return;
        }
        final ExtraFontData data = getFontData(target, false);
        if (data == null)
            return;

        if (data.borderWidth > 0) {
            final Paint paint = target.getPaint();

            // setup stroke
            final Style oldStyle = paint.getStyle();
            final ColorStateList oldTextColors = target.getTextColors();
            final float oldStrokeWidth = paint.getStrokeWidth();

            target.setTextColor(data.borderColor);
            paint.setStyle(Style.STROKE);
            paint.setStrokeWidth(data.borderWidth);
            callDrawCallback(drawCallback, canvas);

            target.setTextColor(oldTextColors);
            paint.setStyle(oldStyle);
            paint.setStrokeWidth(oldStrokeWidth);
        }
    }

    /**
     * Calls the draw callback with the given canvas. Use this method instead of
     * calling it yourself, as lint is fooled by the method name 'onDraw' and
     * thinks we are intervening with the render cycle. With this method, we can
     * isolate the suppress lint annotation to the only warning we want to
     * suppress.
     *
     * @param drawCallback
     * @param canvas
     */
    @SuppressLint("WrongCall")
    private static void callDrawCallback(DrawCallback drawCallback, Canvas canvas) {
        drawCallback.onDraw(canvas);
    }

    /**
     * A data holder in which properties are stored that are not part of the
     * default text view attributes, but which are applicable to all custom Font
     * widgets. By storing this data holder in the corresponding view instance,
     * we can apply the properties at any time with a shared static method.
     *
     * @author Jelle Fresen <jelle@innovattic.com>
     */
    public static class ExtraFontData {
        public String font;
        public int style;
        public int borderWidth;
        public int borderColor;

        public ExtraFontData(TextView target) {
            // By default, the font is not changed
            font = null;
            // By default, we apply a regular typeface
            style = Typeface.NORMAL;
            // By default, we don't add a border around the text
            borderWidth = 0;
            // By default, *if* there is a border, it will be black
            borderColor = Color.BLACK;
            // Store the data in the TextView
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.DONUT) {
                target.setTag(R.id._FontsExtraData, this);
            }
        }
    }

    public static ExtraFontData getFontData(TextView target) {
        return getFontData(target, true);
    }

    public static ExtraFontData getFontData(TextView target, boolean createIfMissing) {
        ExtraFontData data = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.DONUT) {
            data = (ExtraFontData) target.getTag(R.id._FontsExtraData);
        }
        if (data == null && createIfMissing) {
            data = new ExtraFontData(target);
        }
        return data;
    }

    public interface DrawCallback {
        public void onDraw(Canvas canvas);
    }
}


text:
import React from 'react'
import { ps } from './utils'

function k (l: number) {
  const p1 = l / 32
  const p2 = l / 16
  const weight = l / 8
  const leftBottomPoint = { x: p2, y: l - p1 }
  const topLeftPoint = { x: p2, y: p1 }
  const topSubLeftPoint = { x: p2 + weight, y: p1 }
  const leftMiddlePoint = { x: p2 + weight, y: l / 2 }
  const r = l - p2 - 16
  const blodWeight = Math.pow(2, 0.5) * weight
  const topSubRightPoint = { x: r - blodWeight, y: p1 }
  const topRightPoint = { x: r, y: p1 }
  const rightMiddlePoint = { x: p2 + weight + blodWeight, y:l / 2 }
  const rightBottomPoint = { x: topRightPoint.x, y: l - p1 }
  const rightSubBottomPoint = { x: topSubRightPoint.x, y: l - p1 }
  const bottomMiddlePoint = { x: p2 + weight + blodWeight / 2, y: l / 2 + blodWeight / 2 }
  const bottomLeftTopPoint = { x: p2 + weight, y: l / 2 + blodWeight }
  const bottomLeftPoint = { x: p2 + weight, y: l - p1 }

  return `M${ps(leftBottomPoint)} L${ps(topLeftPoint)} L${ps(topSubLeftPoint)}
  L${ps(leftMiddlePoint)} L${ps(topSubRightPoint)} L${ps(topRightPoint)}
  L${ps(rightMiddlePoint)} L${ps(rightBottomPoint)} L${ps(rightSubBottomPoint)}
  L${ps(bottomMiddlePoint)} L${ps(bottomLeftTopPoint)} L${ps(bottomLeftPoint)} Z`
}

export default () => (
  <svg version='1.1'
    id='k'
    width='128' height='128'
    viewBox='0 0 128 128'
    xmlns='http://www.w3.org/2000/svg'
    stroke='skyblue'
    fill='none'
    ref={(svg) => {
      svg.querySelector('path').setAttribute('d', k(128))
    }}
  >
    <path id='K' d='' />
  </svg>
)


text:
define(function (require) {
    'use strict';

    var srcdoc = 'This is mip iframe!';
    var src = 'https://www.mipengine.org/article/instant-pageview.html';

    describe('mip iframe', function () {
        it('build', function (){
            var ele = document.createElement('mip-iframe');
            ele.setAttribute('id', 'ifr-build');
            ele.setAttribute('src', src);
            ele.setAttribute('width', 400);
            ele.setAttribute('height', 300);
            ele.setAttribute('srcdoc', srcdoc);
            document.body.appendChild(ele);

            var rele = document.querySelector('#ifr-build iframe');
            var reg = new RegExp(window.btoa(srcdoc));
            expect(reg.test(window.btoa(srcdoc))).to.be.true;
        });

        it('no rect', function (){
            var ele = document.createElement('mip-iframe');
            ele.setAttribute('src', src);
            ele.setAttribute('srcdoc', srcdoc);
            document.body.appendChild(ele);

            var rele = document.querySelector('#ifr-build iframe');
            var reg = new RegExp(window.btoa(srcdoc));
            expect(reg.test(window.btoa(srcdoc))).to.be.true;
        });
    });
});


text:
package templates

//go:generate packr

import (
	"bufio"
	"bytes"
	"io"
	"text/template"

	"github.com/gobuffalo/packr"
)

// GetAsset reads an asset from "disk" into a string
func GetAsset(assetName string, options ...AssetOption) (string, error) {
	box := packr.NewBox("./assets")

	asset, err := box.MustString(assetName)
	if err != nil {
		return "", err
	}

	for _, option := range options {
		if asset, err = option(assetName, asset); err != nil {
			return "", err
		}
	}

	return asset, nil
}

// ExecuteTemplate executes the data parameter on a text/template
func ExecuteTemplate(data interface{}) AssetOption {
	return func(assetName string, asset string) (string, error) {

		tmpl, err := template.New(assetName).Parse(asset)
		if err != nil {
			return asset, err
		}

		buf := new(bytes.Buffer)
		bufWriter := bufio.NewWriter(buf)

		err = tmpl.Execute(bufWriter, data)
		if err != nil {
			return asset, err
		}

		bufWriter.Flush()

		templateBodyBytes := new(bytes.Buffer)
		_, err = templateBodyBytes.ReadFrom(buf)
		if err != nil {
			return asset, err
		}

		return templateBodyBytes.String(), nil
	}
}

// DecorateTemplate uses an ExtensionImpl to inject data into an extension
func DecorateTemplate(extMgr StackTemplateDecorator,
	stackName string) AssetOption {
	return func(assetName string, asset string) (string, error) {
		assetBuf := bytes.NewBufferString(asset)
		newBuf, err := extMgr.DecorateStackTemplate(assetName, stackName, assetBuf)
		if err != nil {
			return "", err
		}
		templateBodyBytes := new(bytes.Buffer)
		if _, err := templateBodyBytes.ReadFrom(newBuf); err != nil {
			return "", err
		}
		return templateBodyBytes.String(), nil
	}
}

// AssetOption describes the method signature for manipulating loaded assets
type AssetOption func(string, string) (string, error)

// StackTemplateDecorator is a stub for decorate template struct to avoid circular dependencies
type StackTemplateDecorator interface {
	DecorateStackTemplate(assetName string, stackName string, templateBody io.Reader) (io.Reader, error)
}


text:
    bundle install
    bundle exec jekyll serve

## Publish to Github Pages

    JEKYLL_ENV=production bundle exec rake site:publish

## Thanks

This blog was forked from https://github.com/kippt/jekyll-incorporated. Originally built for
[sendtoinc.com](https://sendtoinc.com), your workspace for sharing and organizing knowledge.
Original template built by:

**Karri Saarinen**

+ [http://twitter.com/karrisaarinen](http://twitter.com/karrisaarinen)
+ [http://github.com/ksaa](http://github.com/ksaa)

**Jori Lallo**

+ [http://twitter.com/jorilallo](http://twitter.com/jorilallo)
+ [http://github.com/jorde](http://github.com/jorilallo)


text:
/*
Package to provides helpers to ease working with pointer values of marshalled structures.
*/
package to

// String returns a string value for the passed string pointer. It returns the empty string if the
// pointer is nil.
func String(s *string) string {
	if s != nil {
		return *s
	}
	return ""
}

// StringPtr returns a pointer to the passed string.
func StringPtr(s string) *string {
	return &s
}

// StringMap returns a map of strings built from the map of string pointers. The empty string is
// used for nil pointers.
func StringMap(msp map[string]*string) map[string]string {
	ms := make(map[string]string, len(msp))
	for k, sp := range msp {
		if sp != nil {
			ms[k] = *sp
		} else {
			ms[k] = ""
		}
	}
	return ms
}

// StringMapPtr returns a map of string pointers built from the passed map of strings.
func StringMapPtr(ms map[string]string) map[string]*string {
	msp := make(map[string]*string, len(ms))
	for k, s := range ms {
		msp[k] = StringPtr(s)
	}
	return msp
}

// Bool returns a bool value for the passed bool pointer. It returns false if the pointer is nil.
func Bool(b *bool) bool {
	if b != nil {
		return *b
	}
	return false
}

// BoolPtr returns a pointer to the passed bool.
func BoolPtr(b bool) *bool {
	return &b
}

// Int returns an int value for the passed int pointer. It returns 0 if the pointer is nil.
func Int(i *int) int {
	if i != nil {
		return *i
	}
	return 0
}

// IntPtr returns a pointer to the passed int.
func IntPtr(i int) *int {
	return &i
}

// Int32 returns an int value for the passed int pointer. It returns 0 if the pointer is nil.
func Int32(i *int32) int32 {
	if i != nil {
		return *i
	}
	return 0
}

// Int32Ptr returns a pointer to the passed int32.
func Int32Ptr(i int32) *int32 {
	return &i
}

// Int64 returns an int value for the passed int pointer. It returns 0 if the pointer is nil.
func Int64(i *int64) int64 {
	if i != nil {
		return *i
	}
	return 0
}

// Int64Ptr returns a pointer to the passed int64.
func Int64Ptr(i int64) *int64 {
	return &i
}

// Float32 returns an int value for the passed int pointer. It returns 0.0 if the pointer is nil.
func Float32(i *float32) float32 {
	if i != nil {
		return *i
	}
	return 0.0
}

// Float32Ptr returns a pointer to the passed float32.
func Float32Ptr(i float32) *float32 {
	return &i
}

// Float64 returns an int value for the passed int pointer. It returns 0.0 if the pointer is nil.
func Float64(i *float64) float64 {
	if i != nil {
		return *i
	}
	return 0.0
}

// Float64Ptr returns a pointer to the passed float64.
func Float64Ptr(i float64) *float64 {
	return &i
}


text:
package com.thoughtworks.go.domain.materials;

import com.thoughtworks.go.util.command.CommandLine;
import com.thoughtworks.go.util.command.ConsoleResult;
import com.thoughtworks.go.util.command.ProcessOutputStreamConsumer;

/**
 * @understands: SCMCommand
 */
public abstract class SCMCommand {
    protected String materialFingerprint;

    public SCMCommand(String materialFingerprint) {
        this.materialFingerprint = materialFingerprint;
    }

    protected int run(CommandLine commandLine, ProcessOutputStreamConsumer outputStreamConsumer, String... input) {
        return commandLine.run(outputStreamConsumer, materialFingerprint, input);
    }

    public ConsoleResult runOrBomb(CommandLine commandLine, boolean failOnNonZeroReturn, String... input) {
        return commandLine.runOrBomb(failOnNonZeroReturn, materialFingerprint, input);
    }

    public ConsoleResult runOrBomb(CommandLine commandLine, String... input) {
        return commandLine.runOrBomb(materialFingerprint, input);
    }
}


text:
require 'set'
module Construqt
    class Graph

      class Visited
        def initialize(key)
          @key = key
          # @sessions = sessions
        end
        def used(session)
          session[@key]
        end
        def set_used(session)
          session[@key] = true
        end
      end

      class Link
        include Comparable
        attr_reader :param, :link
        def initialize(link, param)
          @link = link;
          @param = param;
        end
      end

      class Links
        def initialize
          @links = {}
        end
        def add(link)
          @links[link.link.ident] ||= link
        end
        def empty?
          @links.empty?
        end
        def each(&block)
          @links.values.each(&block)
        end
        def find(&block)
          @links.values.find(&block)
        end
        def select(&block)
          @links.values.select(&block)
        end
        def map(&block)
          @links.values.map(&block)
        end
      end

      class Node
        attr_reader :ref, :children, :parents, :param, :graph
        def initialize(graph, ref)
          throw "Ref should not be a Node" if ref.kind_of?(Node)
          @ref = ref
          @graph = graph
          @param = graph.create_link_param(ref, ref)
          @children = Links.new
          @parents = Links.new
        end

        def inspect
          "#<#{self.class.name} ref=#{@ref.ident} param=#{@param.inspect} children=#{@children.map{|i| i.link.ident}.join(",")} parents=#{@parents.map{|i| i.link.ident}.join(",")}>"
        end

        def ident
          @ref.ident
        end

        def join_as_child(oth)
          left, right = @graph.create_link_pair(self, oth)
          self.children.add right
          oth.parents.add left
          [self, oth]
        end
      end

      attr_reader :nodes
      def initialize
        @nodes = {}
        # @linkparams = []
      end

      def create_link_param(left, right)
        key = [left.ident,right.ident].sort.join("<=>")
        ret = Visited.new(key)
        # @linkparams.push ret
        ret
      end

      def create_link_pair(left, right)
        lp = create_link_param(left, right)
        [Link.new(left, lp), Link.new(right, lp)]
      end

      def node_from_ref(ref)
        @nodes[ref.ident] ||= Node.new(self, ref)
      end

      def find_start(session)
        ret = @nodes.values.find do |node|
          !node.param.used(session) &&
          node.parents.empty? && (
            node.children.empty? ||
            node.children.find{|i| !i.param.used(session)}
          )
        end
        # puts "find_start=>#{!ret || ret.ident}"
        ret
      end

      def resolved(session, base)
        if !base.children.empty?
          return !base.param.used(session)
        end
        #return false if !base.param.used(session)
        #puts "end node #{base.ident} [#{base.parents.map{|i| "#{(i.param.used(session)&&"*")||""}:#{i.link.ident}"}.join(",")}]"
        !base.parents.find{|i| !i.param.used(session)}
      end

      def walk(session, stop, base, level, seq, &block)
        #throw "illegal graph" if level < 0
        # if !base.children.empty?
          base.parents.each do |parent|
            next if parent.link == stop
            # next if parent.link
            next if parent.param.used(session)
            parent.param.set_used(session)
            # puts "#{level}-#{stop.ident}==#{parent.link.ident}-parent-enter"
            seq = walk(session, base, parent.link, level-1, seq, &block)
            # puts "#{level}-#{stop.ident}==#{parent.link.ident}-parent-leave"
          end
        if resolved(session, base) #base.param.used(session)
          base.param.set_used(session)
          block.call(base, seq, level)
          seq = seq+1
        end
        # else
        #   if !base.parents.find{|i| !i.param.used(session)}
        #     base.param.set_used(session)
        #     block.call(base, level)
        #   end
        # end
        # puts "#{level}-leave"
        base.children.each do |child|
          next if child.link == stop
          next if child.param.used(session)
          child.param.set_used(session)
          # puts "#{level}-#{stop.ident}==#{child.link.ident}-child-enter"
          seq = walk(session, child.link, child.link, level+1, seq, &block)
          # puts "#{level}-#{stop.ident}==#{child.link.ident}-child-leave"
        end
        seq
      end

      def run_session(&block)
          #session = @session += 1
          block.call({})
          #@sessions.delete(session)
      end

      def dump
        run_session do |session|
          # should be while
          while (base = find_start(session))
            # binding.pry
            walk(session, base, base, 0, 0) do |node, seq, level|
              puts "****#{seq}:#{level}-#{Util.indent("#{(node.children.empty?&&"*")||""}#{node.ident}", 2*seq)}"
            end
          end
        end
      end

      def self.build_host_graph_from_hosts(hosts)
        graph = Graph.new
        hosts.each do |host|
          my = graph.node_from_ref(host)
          #puts "#{host.ident} mother=#{host.mother&&host.mother.ident}"
          if my.ref.mother
            pnode = graph.node_from_ref(my.ref.mother)
            pnode.join_as_child(my)
          end
        end
        graph
      end

      def self.build_interface_graph_from_host(host)
        graph = Graph.new
        host.interfaces.values.each do |iface|
          my = graph.node_from_ref(iface)
          iface.children && iface.children.each do |ifs|
            inode = graph.node_from_ref(ifs)
            my.join_as_child(inode)
          end

          iface.parents && iface.parents.each do |ifs|
            pnode = graph.node_from_ref(ifs)
            pnode.join_as_child(my)
            # binding.pry
          end
        end
        graph.run_session do |session|
          while (base = graph.find_start(session))
            graph.walk(session, base, base, 0, 0) do |node, seq, level|
              return nil if level < 0
            end
          end
        end
        graph
      end

      def flat
        ret = []
        run_session do |session|
          # should be while
          while (base = find_start(session))
            flat = []
            ret.push flat
            walk(session, base, base, 0, 0) do |node, level|
              flat.push(node)
              # puts "****#{level}-#{Util.indent(node.ident, 2*level)}"
            end
          end
        end
        ret
      end

    end
end


text:
<?php

namespace Markup\NeedleBundle\Collator;

/**
 * An interface for a collator (sorter).
 **/
interface CollatorInterface
{
    /**
     * Compare two values on a linear scale.
     *
     * @param mixed $value1
     * @param mixed $value2
     *
     * @return int Returns 1 if first operand is greater than second, 0 if they are equal, -1 if first operand less than second.
     **/
    public function compare($value1, $value2);
}


text:
<?php

require __DIR__ . '/../../vendor/autoload.php';

// create app
$app = new \Hahns\Hahns();

require '_server/json-get.php';
require '_server/json-get-serviceholder.php';
require '_server/json-post.php';
require '_server/json-put.php';
require '_server/json-patch.php';
require '_server/json-delete.php';
require '_server/header.php';
require '_server/redirect.php';
require '_server/parameters.php';
require '_server/text-get.php';
require '_server/html-get.php';
require '_server/events.php';
require '_server/not-found.php';
require '_server/error.php';
require '_server/named-routes.php';
require '_server/any.php';

$app->on(\Hahns\Hahns::EVENT_NOT_FOUND, function () {
    echo '1';
});

// run app
$app->run();


text:
#pragma once

#include <memory>
#include <string>
#include <vector>

#include "mcrouter/proxy.h"
#include "mcrouter/routes/BigValueRouteIf.h"
#include "mcrouter/routes/McOpList.h"
#include "mcrouter/routes/McrouterRouteHandle.h"
#include "mcrouter/routes/RootRoute.h"
#include "mcrouter/routes/RouteSelectorMap.h"

namespace facebook { namespace memcache { namespace mcrouter {

McrouterRouteHandlePtr makeBigValueRoute(McrouterRouteHandlePtr ch,
                                         BigValueRouteOptions options);

/**
 * This is the top-most level of Mcrouter's RouteHandle tree.
 */
class ProxyRoute {
 private:
  ProxyMcReply dispatchMcMsgHelper(
    McMsgRef&& msg,
    std::shared_ptr<GenericProxyRequestContext> ctx,
    McOpList::Item<0>) const {

    throw std::runtime_error("dispatch for requested op not implemented");
  }

  template <int op_id>
  ProxyMcReply dispatchMcMsgHelper(
    McMsgRef&& msg,
    std::shared_ptr<GenericProxyRequestContext> ctx,
    McOpList::Item<op_id>) const {

    if (msg->op == McOpList::Item<op_id>::op::mc_op) {
      return route(ProxyMcRequest(std::move(ctx), std::move(msg)),
                   typename McOpList::Item<op_id>::op());
    }

    return dispatchMcMsgHelper(std::move(msg), std::move(ctx),
                               McOpList::Item<op_id-1>());
  }

 public:
  static std::string routeName() { return "proxy"; }

  ProxyRoute(proxy_t* proxy, const RouteSelectorMap& routeSelectors)
      : proxy_(proxy) {
    root_ = std::make_shared<McrouterRouteHandle<RootRoute>>(
      proxy_, routeSelectors);
    if (proxy_->opts.big_value_split_threshold != 0) {
      BigValueRouteOptions options(proxy_->opts.big_value_split_threshold);
      root_ = makeBigValueRoute(std::move(root_), std::move(options));
    }
  }

  ProxyMcReply dispatchMcMsg(
    McMsgRef&& msg,
    std::shared_ptr<GenericProxyRequestContext> ctx) const {

    return dispatchMcMsgHelper(std::move(msg), std::move(ctx),
                               McOpList::LastItem());
  }

  template <class Operation, class Request>
  std::vector<McrouterRouteHandlePtr> couldRouteTo(
    const Request& req, Operation) const {

    return { root_ };
  }

  template <class Operation, class Request>
  typename ReplyType<Operation, Request>::type route(
    const Request& req, Operation) const {
    return root_->route(req, Operation());
  }

 private:
  proxy_t* proxy_;
  McrouterRouteHandlePtr root_;
};

}}}  // facebook::memcache::mcrouter


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Dichapetalum chiapasense Standl.

### Remarks
null


text:
package com.openbiz.exception;

public class DataFormatInvalidException extends Exception {

	private static final long serialVersionUID = 6437155278566428690L;

}


text:
When it comes to query languages, SQL is the mostly widely recognized standard. The majority of developers have experience and are comfortable with SQL. For this reason Orient DB uses SQL as it's query language and adds some extensions to enable graph functionality. There are a few differences between the standard SQL syntax and that supported by OrientDB, but for the most part, it should feel very natural. The differences are covered in the [OrientDB SQL dialect](#orientdb-sql-dialect) section of this page.

Many SQL commands share the [WHERE condition](SQL-Where.md). Keywords and class names in OrientDB SQL are case insensitive. Field names and values are case sensitive. In the following examples keywords are in uppercase but this is not strictly required.

If you are not yet familiar with SQL, we suggest you to get the course on [KhanAcademy](http://cs-blog.khanacademy.org/2015/05/just-released-full-introductory-sql.html).

For example, if you have a class `MyClass` with a field named `id`, then the following SQL statements are equivalent:

```sql
SELECT FROM MyClass WHERE id = 1
select from myclass where id = 1
```

The following is NOT equivalent.  Notice that the field name 'ID' is not the same as 'id'.

```sql
SELECT FROM MyClass WHERE ID = 1
```

## Automatic usage of indexes

OrientDB allows you to execute queries against any field, indexed or not-indexed. The SQL engine automatically recognizes if any indexes can be used to speed up execution. You can also query any indexes directly by using `INDEX:<index-name>` as a target. Example:

```sql
SELECT FROM INDEX:myIndex WHERE key = 'Jay'
```

## Extra resources
- [SQL expression syntax](SQL-Where.md)
 - [Where clause](SQL-Where.md)
 - [Operators](SQL-Where.md#operators)
 - [Functions](SQL-Where.md#functions)
- [Pagination](Pagination.md)
- [Pivoting-With-Query](Pivoting-With-Query.md)
- [SQL batch](SQL-batch.md)

## OrientDB SQL dialect

OrientDB supports SQL as a query language with some differences compared with SQL. Orient Technologies decided to avoid creating Yet-Another-Query-Language. Instead we started from familiar SQL with extensions to work with graphs. We prefer to focus on standards.

If you want learn SQL, there are many online courses such as:
- [Online course Introduction to Databases by Jennifer Widom from Stanford university](https://www.coursera.org/course/db)
- [Introduction to SQL at W3 Schools](http://www.w3schools.com/sql/sql_intro.asp)
- [SQLCourse.com](http://www.sqlcourse2.com/intro2.html)
- [YouTube channel Basic SQL Training by Joey Blue](http://www.youtube.com/playlist?list=PLD20298E653A970F8)

To know more, look to [OrientDB SQL Syntax](SQL-Syntax.md).

Or order any book like [these](http://www.amazon.com/s/ref=nb_sb_noss/189-0251150-4407173?url=search-alias%3Daps&field-keywords=sql)

## JOINs
The most important difference between OrientDB and a Relational Database is that relationships are represented by `LINKS` instead of JOINs.

For this reason, the classic JOIN syntax is not supported. OrientDB uses the "dot (`.`) notation" to navigate `LINKS`. Example 1 : In SQL you might create a join such as:
```sql
SELECT *
FROM Employee A, City B
WHERE A.city = B.id
AND B.name = 'Rome'
```
In OrientDB an equivalent operation would be:
```sql
SELECT * FROM Employee WHERE city.name = 'Rome'
```
This is much more straight forward and powerful! If you use multiple JOINs, the OrientDB SQL equivalent will be an even larger benefit. Example 2:  In SQL you might create a join such as:
```sql
SELECT *
FROM Employee A, City B, Country C,
WHERE A.city = B.id
AND B.country = C.id
AND C.name = 'Italy'
```
In OrientDB an equivalent operation would be:
```sql
SELECT * FROM Employee WHERE city.country.name = 'Italy'
```

## Projections
In SQL projections are mandatory and you can use the star character `*` to include all of the fields. With OrientDB this type of projection is optional. Example: In SQL to select all of the columns of Customer you would write:
```sql
SELECT * FROM Customer
```
In OrientDB the `*` is optional:
```sql
SELECT FROM Customer
```

## DISTINCT
In SQL, `DISTINCT` is a keyword but in OrientDB it is a function, so if your query is:
```sql
SELECT DISTINCT name FROM City
```
In OrientDB you would write:
```sql
SELECT DISTINCT(name) FROM City
```

## HAVING

OrientDB does not support the `HAVING` keyword, but with a nested query it's easy to obtain the same result. Example in SQL:
```SQL
SELECT city, sum(salary) AS salary
FROM Employee
GROUP BY city
HAVING salary > 1000
```

This groups all of the salaries by city and extracts the result of aggregates with the total salary greater than 1,000 dollars. In OrientDB the `HAVING` conditions go in a select statement in the predicate:

```SQL
SELECT FROM ( SELECT city, SUM(salary) AS salary FROM Employee GROUP BY city ) WHERE salary > 1000
```

## Select from multiple targets

OrientDB allows only one class (classes are equivalent to tables in this discussion) as opposed to SQL, which allows for many tables as the target.  If you want to select from 2 classes, you have to execute 2 sub queries and join them with the `UNIONALL` function:
```sql
SELECT FROM E, V
```
In OrientDB, you can accomplish this with a few variable definitions and by using the `expand` function to the union:
```sql
SELECT EXPAND( $c ) LET $a = ( SELECT FROM E ), $b = ( SELECT FROM V ), $c = UNIONALL( $a, $b )
```

## Query metadata
OrientDB provides the `metadata:` target to retrieve information about OrientDB's metadata:
- `schema`, to get classes and properties
- `indexmanager`, to get information about indexes

### Query the schema

Get all the configured classes:
```
select expand(classes) from metadata:schema

----+-----------+---------+----------------+----------+--------+--------+----------+----------+------------+----------
#   |name       |shortName|defaultClusterId|strictMode|abstract|overSize|clusterIds|properties|customFields|superClass
----+-----------+---------+----------------+----------+--------+--------+----------+----------+------------+----------
0   |UserGroup  |null     |13              |false     |false   |0.0     |[1]       |[2]       |null        |V
1   |WallPost   |null     |15              |false     |false   |0.0     |[1]       |[4]       |null        |V
2   |Owner      |null     |12              |false     |false   |0.0     |[1]       |[1]       |null        |E
3   |OTriggered |null     |-1              |false     |true    |0.0     |[1]       |[0]       |null        |null
4   |E          |E        |10              |false     |false   |0.0     |[1]       |[0]       |null        |null
5   |OUser      |null     |5               |false     |false   |0.0     |[1]       |[4]       |null        |OIdentity
6   |OSchedule  |null     |7               |false     |false   |0.0     |[1]       |[7]       |null        |null
7   |ORestricted|null     |-1              |false     |true    |0.0     |[1]       |[4]       |null        |null
8   |AssignedTo |null     |11              |false     |false   |0.0     |[1]       |[1]       |null        |E
9   |V          |null     |9               |false     |false   |2.0     |[1]       |[0]       |null        |null
10  |OFunction  |null     |6               |false     |false   |0.0     |[1]       |[5]       |null        |null
11  |ORole      |null     |4               |false     |false   |0.0     |[1]       |[4]       |null        |OIdentity
12  |ORIDs      |null     |8               |false     |false   |0.0     |[1]       |[0]       |null        |null
13  |OIdentity  |null     |-1              |false     |true    |0.0     |[1]       |[0]       |null        |null
14  |User       |null     |14              |false     |false   |0.0     |[1]       |[2]       |null        |V
----+-----------+---------+----------------+----------+--------+--------+----------+----------+------------+----------
```

Get all the configured properties for the class OUser:

```

select expand(properties) from (
   select expand(classes) from metadata:schema
) where name = 'OUser'

----+--------+----+---------+--------+-------+----+----+------+------------+-----------
#   |name    |type|mandatory|readonly|notNull|min |max |regexp|customFields|linkedClass
----+--------+----+---------+--------+-------+----+----+------+------------+-----------
0   |status  |7   |true     |false   |true   |null|null|null  |null        |null
1   |roles   |15  |false    |false   |false  |null|null|null  |null        |ORole
2   |password|7   |true     |false   |true   |null|null|null  |null        |null
3   |name    |7   |true     |false   |true   |null|null|null  |null        |null
----+--------+----+---------+--------+-------+----+----+------+------------+-----------
```

### Query the available indexes

Get all the configured indexes:

```
select expand(indexes) from metadata:indexmanager

----+------+------+--------+---------+---------+------------------------------------+------------------------------------------------------
#   |@RID  |mapRid|clusters|type     |name     |indexDefinition                     |indexDefinitionClass
----+------+------+--------+---------+---------+------------------------------------+------------------------------------------------------
0   |#-1:-1|#2:0  |[0]     |DICTIO...|dictio...|{keyTypes:[1]}                      |com.orientechnologies.orient.core.index.OSimpleKeyI...
1   |#-1:-1|#1:1  |[1]     |UNIQUE   |OUser....|{className:OUser,field:name,keyTy...|com.orientechnologies.orient.core.index.OPropertyIn...
2   |#-1:-1|#1:0  |[1]     |UNIQUE   |ORole....|{className:ORole,field:name,keyTy...|com.orientechnologies.orient.core.index.OPropertyIn...
----+------+------+--------+---------+---------+------------------------------------+-----------------------------------------
```


text:
#ifndef IDBKeyRangeData_h
#define IDBKeyRangeData_h

#if ENABLE(INDEXED_DATABASE)

#include "IDBKeyData.h"
#include "IDBKeyRange.h"

namespace WebCore {

class IDBKey;

struct IDBKeyRangeData {
    IDBKeyRangeData()
        : isNull(true)
        , lowerOpen(false)
        , upperOpen(false)
    {
    }

    static IDBKeyRangeData allKeys()
    {
        IDBKeyRangeData result;
        result.isNull = false;
        result.lowerKey = IDBKeyData::minimum();
        result.upperKey = IDBKeyData::maximum();
        return result;
    }

    IDBKeyRangeData(IDBKey*);
    IDBKeyRangeData(const IDBKeyData&);

    IDBKeyRangeData(IDBKeyRange* keyRange)
        : isNull(!keyRange)
        , lowerOpen(false)
        , upperOpen(false)
    {
        if (isNull)
            return;

        lowerKey = keyRange->lower();
        upperKey = keyRange->upper();
        lowerOpen = keyRange->lowerOpen();
        upperOpen = keyRange->upperOpen();
    }

    IDBKeyRangeData isolatedCopy() const;

    WEBCORE_EXPORT RefPtr<IDBKeyRange> maybeCreateIDBKeyRange() const;

    WEBCORE_EXPORT bool isExactlyOneKey() const;
    bool containsKey(const IDBKeyData&) const;
    bool isValid() const;

    template<class Encoder> void encode(Encoder&) const;
    template<class Decoder> static bool decode(Decoder&, IDBKeyRangeData&);

    bool isNull;

    IDBKeyData lowerKey;
    IDBKeyData upperKey;

    bool lowerOpen;
    bool upperOpen;

#if !LOG_DISABLED
    String loggingString() const;
#endif
};

template<class Encoder>
void IDBKeyRangeData::encode(Encoder& encoder) const
{
    encoder << isNull;
    if (isNull)
        return;

    encoder << upperKey << lowerKey << upperOpen << lowerOpen;
}

template<class Decoder>
bool IDBKeyRangeData::decode(Decoder& decoder, IDBKeyRangeData& keyRange)
{
    if (!decoder.decode(keyRange.isNull))
        return false;

    if (keyRange.isNull)
        return true;

    if (!decoder.decode(keyRange.upperKey))
        return false;

    if (!decoder.decode(keyRange.lowerKey))
        return false;

    if (!decoder.decode(keyRange.upperOpen))
        return false;

    if (!decoder.decode(keyRange.lowerOpen))
        return false;

    return true;
}

} // namespace WebCore

#endif // ENABLE(INDEXED_DATABASE)
#endif // IDBKeyRangeData_h


text:
<?php
$form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
    'id' => 'customer-custom-field-assignment-table-form',
    // Please note: When you enable ajax validation, make sure the corresponding
    // controller action is handling ajax validation correctly.
    // There is a call to performAjaxValidation() commented in generated controller code.
    // See class documentation of CActiveForm for details on this.
    'enableAjaxValidation' => false,
        // 'htmlOptions'=>array('enctype'=>'multipart/form-data'),
        ));
?>

        <?php
        $this->widget('bootstrap.widgets.TbAlert', array(
            'block' => false, // display a larger alert block?
            'fade' => true, // use transitions?
            'closeText' => '×', // close link text - if set to false, no close link is displayed
            'alerts' => array(// configurations per alert type
                'success' => array('block' => true, 'fade' => true, 'closeText' => '×', 'class' => 'alert alert-danger'), //success, info, warning, error or danger
                'info' => array('block' => true, 'fade' => true, 'closeText' => '×', 'class' => 'alert alert-danger'), //success, info, warning, error or danger
                'warning' => array('block' => true, 'fade' => true, 'closeText' => '×', 'class' => 'alert alert-danger'), //success, info, warning, error or danger
                'error' => array('block' => true, 'fade' => true, 'closeText' => '×', 'class' => 'alert alert-danger'), //success, info, warning, error or danger
                'danger' => array('block' => true, 'fade' => true, 'closeText' => '×', 'class' => 'alert alert-danger'), //success, info, warning, error or danger
            ),
        ));
        ?>

Fields with * are required.

        <?php echo $form->errorSummary($model); ?>

<input style="display:none" class="span5" value="<?php echo Yii::app()->user->id; ?>" name="CustomerCustomFieldAssignmentTable[user_id]" id="CustomerCustomFieldAssignmentTable_user_id" type="text">

    <?php echo $form->labelEx($model, 'customer_custom_field_id', array('class' => 'col-sm-3 control-label')); ?>

        <?php
        $LoB = Profile::model()->findAllByAttributes(array('user_id' => Yii::app()->user->id));
        $list = CHtml::listData(CustomerCustomField::model()->findAllByAttributes(array('lob_id' => $LoB)), 'id', 'field_name');
        echo $form->dropDownList($model, 'customer_custom_field_id', $list);
        ?>

    <?php
    $this->widget('bootstrap.widgets.TbButton', array(
        'buttonType' => 'submit',
        'type' => 'primary',
        'label' => $model->isNewRecord ? 'Create' : 'Save',
    ));
    ?>
    <a href="<?php echo Yii::app()->request->getBaseUrl(); ?>/index.php/customerCustomFieldAssignmentTable_Parent" class="btn btn-default" >Cancel

<?php $this->endWidget(); ?>
<?php
/**
  $form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
  'id' => 'customer-custom-field-assignment-table-form',
  // Please note: When you enable ajax validation, make sure the corresponding
  // controller action is handling ajax validation correctly.
  // There is a call to performAjaxValidation() commented in generated controller code.
  // See class documentation of CActiveForm for details on this.
  'enableAjaxValidation' => false,
  // 'htmlOptions'=>array('enctype'=>'multipart/form-data'),
  ));
  ?>

Fields with * are required.

  <?php echo $form->errorSummary($model); ?>

  <?php
  $LoB = Profile::model()->findAllByAttributes(array('user_id' => Yii::app()->user->id));
  $list = CHtml::listData(CustomerCustomField::model()->findAllByAttributes(array('lob_id' => $LoB)), 'id', 'field_name');
  echo $form->dropDownList($model, 'customer_custom_field_id', $list);
  ?>
  <input style="display:none" class="span5" value="<?php echo Yii::app()->user->id; ?>" name="CustomerCustomFieldAssignmentTable[user_id]" id="CustomerCustomFieldAssignmentTable_user_id" type="text">

  <?php
  $this->widget('bootstrap.widgets.TbButton', array(
  'buttonType' => 'submit',
  'type' => 'primary',
  'label' => $model->isNewRecord ? 'Create' : 'Save',
  ));
  ?>

  <?php $this->endWidget(); ?>
 *
 */
?>


text:
using System;
using UIKit;

namespace Xamarin.iOS.Experiments
{
	public static class UIColorExtensions
	{
		///
		/// Converts the HEX color value to UIColor.
		/// Usage example:
		/// var color = UIColor.Clear.FromHex(0xD12229);
		///
		/// <returns>The <see cref="UIColor"/> value.</returns>
		/// <param name="color">Color.</param>
		/// <param name="hexValue">Color HEX value.</param>
		public static UIColor FromHex(this UIColor color, int hexValue)
		{
			// UIColor from Hex in Monotouch
			// http://stackoverflow.com/questions/10310917/uicolor-from-hex-in-monotouch
			return UIColor.FromRGB(
				(((float)((hexValue & 0xFF0000) >> 16)) / 255.0f),
				(((float)((hexValue & 0xFF00) >> 8)) / 255.0f),
				(((float)(hexValue & 0xFF)) / 255.0f)
			);
		}
	}
}


text:
package br.copacabana;

public class SearchCriteria {
	private String city;
	private String neighbor;
	private String zip;
	private String freeform;
	private String openStatus;

	public String getNeighbor() {
		return neighbor;
	}

	public void setNeighbor(String neighbor) {
		this.neighbor = neighbor;
	}

	public String getZip() {
		return zip;
	}

	public void setZip(String zip) {
		this.zip = zip;
	}

	public String getFreeform() {
		return freeform;
	}

	public void setFreeform(String freeform) {
		this.freeform = freeform;
	}

	public String getOpenStatus() {
		return openStatus;
	}

	public void setOpenStatus(String openStatus) {
		this.openStatus = openStatus;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

}


text:
<?xml version = "1.0" encoding = "UTF-8"?>
<INPUT>
<MEDALS>
    <MEDAL Id="1" MEDAL_THRESHOLD="45000" TYPE="Gold"/>
    <MEDAL Id="2" MEDAL_THRESHOLD="70000" TYPE="Silver"/>
    <MEDAL Id="3" MEDAL_THRESHOLD="95000" TYPE="Bronze"/>
</MEDALS>
<SpeedSettings Min="0" Max="150" Default="18"/>
<PenaltySettings TimeLost="15" SpeedLost="0.1"/>
<PROBLEM_SET>
	<PROBLEM_SUBSET>
		<TARGET TYPE="Fraction">
			<ContentSettings denominator="2" numerator="6"/>
		</TARGET>
		<QUESTION INDEX="1">
			<Content TYPE="Fraction">
				<ContentSettings denominator="2" numerator="14"/>
			</Content>
			<Answer VALUE="0"/>
		</QUESTION>
		<QUESTION INDEX="2">
			<Content TYPE="Fraction">
				<ContentSettings denominator="2" numerator="18"/>
			</Content>
			<Answer VALUE="0"/>
		</QUESTION>
		<QUESTION INDEX="3">
			<Content TYPE="Fraction">
				<ContentSettings denominator="2" numerator="18"/>
			</Content>
			<Answer VALUE="0"/>
		</QUESTION>
		<QUESTION INDEX="4">
			<Content TYPE="Fraction">
				<ContentSettings denominator="2" numerator="16"/>
			</Content>
			<Answer VALUE="0"/>
		</QUESTION>
		<QUESTION INDEX="5">
			<Content TYPE="Fraction">
				<ContentSettings denominator="2" numerator="13"/>
			</Content>
			<Answer VALUE="0"/>
		</QUESTION>
	</PROBLEM_SUBSET>
	<PROBLEM_SUBSET>
		<TARGET TYPE="Fraction">
			<ContentSettings denominator="5" numerator="19"/>
		</TARGET>
		<QUESTION INDEX="6">
			<Content TYPE="Fraction">
				<ContentSettings denominator="12" numerator="19"/>
			</Content>
			<Answer VALUE="1"/>
		</QUESTION>
		<QUESTION INDEX="7">
			<Content TYPE="Fraction">
				<ContentSettings denominator="8" numerator="19"/>
			</Content>
			<Answer VALUE="1"/>
		</QUESTION>
		<QUESTION INDEX="8">
			<Content TYPE="Fraction">
				<ContentSettings denominator="3" numerator="19"/>
			</Content>
			<Answer VALUE="1"/>
		</QUESTION>
		<QUESTION INDEX="9">
			<Content TYPE="Fraction">
				<ContentSettings denominator="4" numerator="19"/>
			</Content>
			<Answer VALUE="1"/>
		</QUESTION>
		<QUESTION INDEX="10">
			<Content TYPE="Fraction">
				<ContentSettings denominator="3" numerator="19"/>
			</Content>
			<Answer VALUE="1"/>
		</QUESTION>
	</PROBLEM_SUBSET>
	<PROBLEM_SUBSET>
		<TARGET TYPE="Fraction">
			<ContentSettings denominator="3" numerator="1"/>
		</TARGET>
		<QUESTION INDEX="11">
			<Content TYPE="Fraction">
				<ContentSettings denominator="8" numerator="28"/>
			</Content>
			<Answer VALUE="0"/>
		</QUESTION>
		<QUESTION INDEX="12">
			<Content TYPE="Fraction">
				<ContentSettings denominator="8" numerator="21"/>
			</Content>
			<Answer VALUE="0"/>
		</QUESTION>
		<QUESTION INDEX="13">
			<Content TYPE="Fraction">
				<ContentSettings denominator="12" numerator="36"/>
			</Content>
			<Answer VALUE="0"/>
		</QUESTION>
		<QUESTION INDEX="14">
			<Content TYPE="Fraction">
				<ContentSettings denominator="5" numerator="10"/>
			</Content>
			<Answer VALUE="0"/>
		</QUESTION>
		<QUESTION INDEX="15">
			<Content TYPE="Fraction">
				<ContentSettings denominator="12" numerator="24"/>
			</Content>
			<Answer VALUE="0"/>
		</QUESTION>
	</PROBLEM_SUBSET>
	<PROBLEM_SUBSET>
		<TARGET TYPE="Fraction">
			<ContentSettings denominator="12" numerator="32"/>
		</TARGET>
		<QUESTION INDEX="16">
			<Content TYPE="Fraction">
				<ContentSettings denominator="12" numerator="19"/>
			</Content>
			<Answer VALUE="1"/>
		</QUESTION>
		<QUESTION INDEX="17">
			<Content TYPE="Fraction">
				<ContentSettings denominator="3" numerator="20"/>
			</Content>
			<Answer VALUE="0"/>
		</QUESTION>
		<QUESTION INDEX="18">
			<Content TYPE="Fraction">
				<ContentSettings denominator="12" numerator="12"/>
			</Content>
			<Answer VALUE="1"/>
		</QUESTION>
		<QUESTION INDEX="19">
			<Content TYPE="Fraction">
				<ContentSettings denominator="10" numerator="18"/>
			</Content>
			<Answer VALUE="1"/>
		</QUESTION>
		<QUESTION INDEX="20">
			<Content TYPE="Fraction">
				<ContentSettings denominator="3" numerator="29"/>
			</Content>
			<Answer VALUE="0"/>
		</QUESTION>
	</PROBLEM_SUBSET>
</PROBLEM_SET>
</INPUT>


text:
package BtreeSuggestron;

public class Controller {
}


text:
#import "ORKVisualConsentStepViewController.h"
#import "ORKVisualConsentStep.h"
#import "ORKResult.h"
#import "ORKSignatureView.h"
#import "ORKHelpers.h"
#import "ORKObserver.h"
#import <MessageUI/MessageUI.h>
#import "ORKSkin.h"
#import "ORKTaskViewController_Internal.h"
#import "ORKStepViewController_Internal.h"
#import "ORKConsentSceneViewController.h"
#import "ORKConsentSceneViewController_Internal.h"
#import "ORKConsentSection_Internal.h"
#import "ORKConsentDocument.h"
#import <QuartzCore/QuartzCore.h>
#import "ORKVisualConsentTransitionAnimator.h"
#import "ORKEAGLMoviePlayerView.h"
#import "UIBarButtonItem+ORKBarButtonItem.h"
#import "ORKContinueButton.h"
#import "ORKAccessibility.h"
#import "ORKTintedImageView.h"
#import "ORKTintedImageView_Internal.h"

@interface ORKVisualConsentStepViewController () <UIPageViewControllerDelegate, ORKScrollViewObserverDelegate> {
    BOOL _hasAppeared;
    ORKStepViewControllerNavigationDirection _navigationDirection;

    ORKVisualConsentTransitionAnimator *_animator;

    NSArray *_visualSections;

    ORKScrollViewObserver *_scrollViewObserver;
}

@property (nonatomic, strong) UIPageViewController *pageViewController;

@property (nonatomic, strong) NSMutableDictionary *viewControllers;

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic) NSUInteger currentPage;

@property (nonatomic, strong) ORKContinueButton *continueActionButton;

- (ORKConsentSceneViewController *)viewControllerForIndex:(NSUInteger)index;
- (NSUInteger)currentIndex;
- (NSUInteger)indexOfViewController:(UIViewController *)viewController;

@end

@interface ORKAnimationPlaceholderView : UIView

@property (nonatomic, strong) ORKEAGLMoviePlayerView *playerView;

- (void)scrollToTopAnimated:(BOOL)animated completion:(void (^)(BOOL finished))completion;

@end

@implementation ORKAnimationPlaceholderView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _playerView = [ORKEAGLMoviePlayerView new];
        _playerView.hidden = YES;
        [self addSubview:_playerView];
    }
    return self;
}

- (void)willMoveToWindow:(UIWindow *)newWindow {
    [super willMoveToWindow:newWindow];

    CGRect frame = self.frame;
    frame.size.height = ORKGetMetricForWindow(ORKScreenMetricIllustrationHeight, newWindow);
    self.frame = frame;
}

- (void)layoutSubviews {
    [super layoutSubviews];

    _playerView.frame = self.bounds;
}

- (CGPoint)defaultFrameOrigin {
    return (CGPoint){0, ORKGetMetricForWindow(ORKScreenMetricTopToIllustration, self.superview.window)};
}

- (void)scrollToTopAnimated:(BOOL)animated completion:(void (^)(BOOL finished))completion {
    CGRect targetFrame = self.frame;
    targetFrame.origin = [self defaultFrameOrigin];
    if (animated) {
        [UIView animateWithDuration:ORKScrollToTopAnimationDuration
                         animations:^{
            self.frame = targetFrame;
        }  completion:completion];
    } else {
        self.frame = targetFrame;
        if (completion) {
            completion(YES);
        }
    }
}

@end

@implementation ORKVisualConsentStepViewController

- (void)dealloc {
    [[ORKTintedImageCache sharedCache] removeAllObjects];
}

- (void)stepDidChange {
    [super stepDidChange];
    {
        NSMutableArray *visualSections = [NSMutableArray new];

        NSArray *sections = self.visualConsentStep.consentDocument.sections;
        for (ORKConsentSection *scene in sections) {
            if (scene.type != ORKConsentSectionTypeOnlyInDocument) {
                [visualSections addObject:scene];
            }
        }
        _visualSections = [visualSections copy];
    }

    if (self.step && [self pageCount] == 0) {
        @throw [NSException exceptionWithName:NSGenericException reason:@"Visual consent step has no visible scenes" userInfo:nil];
    }

    _viewControllers = nil;

    [self showViewController:[self viewControllerForIndex:0] forward:YES animated:NO];
}

- (ORKEAGLMoviePlayerView *)animationPlayerView {
    return [(ORKAnimationPlaceholderView *)_animationView playerView];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    CGRect viewBounds = self.view.bounds;

    self.view.backgroundColor = ORKColor(ORKBackgroundColorKey);

    // Prepare pageViewController
    _pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll
                                                          navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal
                                                                        options:nil];
    //_pageViewController.dataSource = self;
    _pageViewController.delegate = self;

    [self scrollView].bounces = NO;

    if ([_pageViewController respondsToSelector:@selector(edgesForExtendedLayout)]) {
        _pageViewController.edgesForExtendedLayout = UIRectEdgeNone;
    }

    _pageViewController.view.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    _pageViewController.view.frame = viewBounds;
    [self.view addSubview:_pageViewController.view];
    [self addChildViewController:_pageViewController];
    [_pageViewController didMoveToParentViewController:self];

    self.animationView = [[ORKAnimationPlaceholderView alloc] initWithFrame:
                          (CGRect){{0, 0}, {viewBounds.size.width, ORKGetMetricForWindow(ORKScreenMetricIllustrationHeight, self.view.window)}}];
    _animationView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleBottomMargin;
    _animationView.backgroundColor = [UIColor clearColor];
    _animationView.userInteractionEnabled = NO;
    [self.view addSubview:_animationView];

    [self updatePageIndex];
}

- (ORKVisualConsentStep *)visualConsentStep {
    assert(!self.step || [self.step isKindOfClass:[ORKVisualConsentStep class]]);
    return (ORKVisualConsentStep *)self.step;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (_pageViewController.viewControllers.count == 0) {

        _hasAppeared = YES;

        // Add first viewController
        NSUInteger idx = 0;
        if (_navigationDirection == ORKStepViewControllerNavigationDirectionReverse) {
            idx = [self pageCount]-1;
        }

        [self showViewController:[self viewControllerForIndex:idx] forward:YES animated:NO];
    }
    [self updatePageIndex];
}

- (void)willNavigateDirection:(ORKStepViewControllerNavigationDirection)direction {
    _navigationDirection = direction;
}

- (UIBarButtonItem *)goToPreviousPageButton {
    UIBarButtonItem *button = [UIBarButtonItem ork_backBarButtonItemWithTarget:self action:@selector(goToPreviousPage)];
    button.accessibilityLabel = ORKLocalizedString(@"AX_BUTTON_BACK", nil);
    return button;
}

- (void)ork_setBackButtonItem:(UIBarButtonItem *)backButton {
    [super ork_setBackButtonItem:backButton];
}

- (void)updateNavLeftBarButtonItem {
    if ([self currentIndex] == 0) {
        [super updateNavLeftBarButtonItem];
    } else {
        self.navigationItem.leftBarButtonItem = [self goToPreviousPageButton];
    }
}

- (void)updateBackButton {
    if (!_hasAppeared) {
        return;
    }

    [self updateNavLeftBarButtonItem];
}

#pragma mark - actions

- (IBAction)goToPreviousPage {
    [self showViewController:[self viewControllerForIndex:[self currentIndex]-1] forward:NO animated:YES preloadNextConsentSectionImage:NO];
    UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil);
}

- (IBAction)next {
    ORKConsentSceneViewController *currentConsentSceneViewController = [self viewControllerForIndex:[self currentIndex]];
    [(ORKAnimationPlaceholderView *)_animationView scrollToTopAnimated:YES completion:nil];
    [currentConsentSceneViewController scrollToTopAnimated:YES completion:^(BOOL finished) {
        if (finished) {
            [self showNextViewController];
        }
    }];
}

- (void)showNextViewController {
    CGRect animationViewFrame = _animationView.frame;
    animationViewFrame.origin = [ORKDynamicCast(_animationView, ORKAnimationPlaceholderView) defaultFrameOrigin];
    _animationView.frame = animationViewFrame;
    ORKConsentSceneViewController *nextConsentSceneViewController = [self viewControllerForIndex:[self currentIndex] + 1];
    [(ORKAnimationPlaceholderView *)_animationView scrollToTopAnimated:NO completion:nil];
    [nextConsentSceneViewController scrollToTopAnimated:NO completion:^(BOOL finished) {
        // 'finished' is always YES when not animated
        [self showViewController:nextConsentSceneViewController forward:YES animated:YES];
        ORKAccessibilityPostNotificationAfterDelay(UIAccessibilityScreenChangedNotification, nil, 0.5);
    }];
}

#pragma mark - internal

- (UIScrollView *)scrollView {
    if (_scrollView == nil) {
        for (UIView *view in self.pageViewController.view.subviews) {
            if ([view isKindOfClass:[UIScrollView class]]) {
                _scrollView = (UIScrollView *)view;
                break;
            }
        }
    }
    return _scrollView;
}

- (void)updatePageIndex {
    NSUInteger currentIndex = [self currentIndex];
    if (currentIndex == NSNotFound) {
        return;
    }

    _currentPage = currentIndex;

    [self updateBackButton];

    ORKConsentSection *currentSection = (ORKConsentSection *)_visualSections[currentIndex];
    if (currentSection.type == ORKConsentSectionTypeOverview) {
        _animationView.isAccessibilityElement = NO;
    } else {
        _animationView.isAccessibilityElement = YES;
        _animationView.accessibilityLabel = [NSString stringWithFormat:ORKLocalizedString(@"AX_IMAGE_ILLUSTRATION", nil), currentSection.title];
        _animationView.accessibilityTraits |= UIAccessibilityTraitImage;
    }
}

- (void)setScrollEnabled:(BOOL)enabled {
    [[self scrollView] setScrollEnabled:enabled];
}

- (NSArray *)visualSections {
    return _visualSections;
}

- (NSUInteger)pageCount {
    return _visualSections.count;
}

- (UIImageView *)findHairlineImageViewUnder:(UIView *)view {
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}

- (void)doShowViewController:(ORKConsentSceneViewController *)viewController
                   direction:(UIPageViewControllerNavigationDirection)direction
                    animated:(BOOL)animated
                  completion:(void (^)(BOOL finished))completion {
    UIView *pageViewControllerView = self.pageViewController.view;
    pageViewControllerView.userInteractionEnabled = NO;

    if (!viewController || !self.pageViewController) {
        if (completion) {
            completion(NO);
        }
        return;
    }

    __weak typeof(self) weakSelf = self;
    [self.pageViewController setViewControllers:@[viewController] direction:direction animated:animated completion:^(BOOL finished) {
        __strong typeof(self) strongSelf = weakSelf;
        pageViewControllerView.userInteractionEnabled = YES;
        [strongSelf updatePageIndex];

        if (completion != NULL) {
            completion(finished);
        }
    }];
}

- (void)doAnimateFromViewController:(ORKConsentSceneViewController *)fromViewController
                       toController:(ORKConsentSceneViewController *)toViewController
                          direction:(UIPageViewControllerNavigationDirection)direction
                                url:(NSURL *)url
            animateBeforeTransition:(BOOL)animateBeforeTransition
            transitionBeforeAnimate:(BOOL)transitionBeforeAnimate
                         completion:(void (^)(BOOL finished))completion {

    NSAssert(url, @"url cannot be nil");
    NSAssert(!(animateBeforeTransition && transitionBeforeAnimate), @"Both flags cannot be set");

    __weak typeof(self) weakSelf = self;
    void (^finishAndNilAnimator)(ORKVisualConsentTransitionAnimator *animator) = ^(ORKVisualConsentTransitionAnimator *animator) {
        __strong typeof(self) strongSelf = weakSelf;
        [animator finish];
        if (strongSelf && strongSelf->_animator == animator) {
            // Do not show images and hide animationPlayerView if it's not the current animator
            fromViewController.imageHidden = NO;
            toViewController.imageHidden = NO;
            [strongSelf animationPlayerView].hidden = YES;
            strongSelf->_animator = nil;
        }
    };

    ORKVisualConsentTransitionAnimator *animator = [[ORKVisualConsentTransitionAnimator alloc] initWithVisualConsentStepViewController:self movieURL:url];
    _animator = animator;

    __block BOOL transitionFinished = NO;
    __block BOOL animatorFinished = NO;

    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // The semaphore waits for both 'animateTransitionWithDirection:loadHandler:completionHandler:' and
        // 'doShowViewController:direction:animated:completion:' methods to complete (both of these methods
        // signal the semaphore on completion). It doesn't matter which of the two finishes first.
        // Defensive 5-second timeout in case the animator doesn't complete.
        BOOL semaphoreATimedOut = dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 5));
        BOOL semaphoreBTimedOut = dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 5));

        if (semaphoreATimedOut || semaphoreBTimedOut) {
            ORK_Log_Debug(@"[Semaphore timed out] semaphoreATimedOut: %d, semaphoreBTimedOut: %d, transitionFinished: %d, animatorFinished: %d", semaphoreATimedOut, semaphoreBTimedOut, transitionFinished, animatorFinished);
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            BOOL animationAndTransitionFinished = (transitionFinished && animatorFinished);

            if (!animatorFinished) {
                finishAndNilAnimator(animator);
            }

            if (completion) {
                completion(animationAndTransitionFinished);
            }
        });
    });

    if (!animateBeforeTransition && !transitionBeforeAnimate) {
        [_animator animateTransitionWithDirection:direction
                                      loadHandler:^(ORKVisualConsentTransitionAnimator *animator, UIPageViewControllerNavigationDirection direction) {

                                          fromViewController.imageHidden = YES;
                                          toViewController.imageHidden = YES;

                                          __strong typeof(self) strongSelf = weakSelf;
                                          [strongSelf doShowViewController:toViewController
                                                                 direction:direction
                                                                  animated:YES
                                                                completion:^(BOOL finished) {

                                                                    transitionFinished = finished;
                                                                    dispatch_semaphore_signal(semaphore);
                                                                }];
                                      }
                                completionHandler:^(ORKVisualConsentTransitionAnimator *animator, UIPageViewControllerNavigationDirection direction) {

                                    animatorFinished = YES;
                                    finishAndNilAnimator(animator);
                                    dispatch_semaphore_signal(semaphore);
                                }];

    } else if (animateBeforeTransition && !transitionBeforeAnimate) {
        [_animator animateTransitionWithDirection:direction
                                      loadHandler:^(ORKVisualConsentTransitionAnimator *animator, UIPageViewControllerNavigationDirection direction) {

                                          fromViewController.imageHidden = YES;
                                      }
                                completionHandler:^(ORKVisualConsentTransitionAnimator *animator, UIPageViewControllerNavigationDirection direction) {

                                    animatorFinished = YES;
                                    finishAndNilAnimator(animator);

                                    __strong typeof(self) strongSelf = weakSelf;
                                    [strongSelf doShowViewController:toViewController
                                                           direction:direction
                                                            animated:YES
                                                          completion:^(BOOL finished) {

                                                              transitionFinished = finished;
                                                              dispatch_semaphore_signal(semaphore);
                                                          }];

                                    dispatch_semaphore_signal(semaphore);
                                }];

    } else if (!animateBeforeTransition && transitionBeforeAnimate) {
        toViewController.imageHidden = YES;
        [self doShowViewController:toViewController
                         direction:direction
                          animated:YES
                        completion:^(BOOL finished) {

                            transitionFinished = finished;

                            [_animator animateTransitionWithDirection:direction
                                                          loadHandler:nil
                                                    completionHandler:^(ORKVisualConsentTransitionAnimator *animator, UIPageViewControllerNavigationDirection direction) {

                                                        animatorFinished = YES;
                                                        finishAndNilAnimator(animator);
                                                        dispatch_semaphore_signal(semaphore);
                                                    }];

                            dispatch_semaphore_signal(semaphore);
                        }];
    }
}

- (void)observedScrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == _scrollViewObserver.target) {
        CGRect animationViewFrame = _animationView.frame;
        CGPoint scrollViewBoundsOrigin = scrollView.bounds.origin;
        CGPoint defaultFrameOrigin = [ORKDynamicCast(_animationView, ORKAnimationPlaceholderView) defaultFrameOrigin];
        animationViewFrame.origin = (CGPoint){defaultFrameOrigin.x - scrollViewBoundsOrigin.x, defaultFrameOrigin.y - scrollViewBoundsOrigin.y};
        _animationView.frame = animationViewFrame;
    }
}

- (ORKConsentSection *)consentSectionForIndex:(NSUInteger)index {
    ORKConsentSection *consentSection = nil;
    NSArray *visualSections = [self visualSections];
    if (index < visualSections.count) {
        consentSection = visualSections[index];
    }
    return consentSection;
}

- (void)showViewController:(ORKConsentSceneViewController *)viewController forward:(BOOL)forward animated:(BOOL)animated {
    [self showViewController:viewController forward:forward animated:animated preloadNextConsentSectionImage:YES];
}

- (void)showViewController:(ORKConsentSceneViewController *)viewController forward:(BOOL)forward animated:(BOOL)animated preloadNextConsentSectionImage:(BOOL)preloadNextViewController {
    [self showViewController:viewController
                     forward:forward
                    animated:animated
                  completion:^(BOOL finished) {
                      if (preloadNextViewController) {
                          ORKConsentSection *nextConsentSection = [self consentSectionForIndex:[self currentIndex] + 1];
                          ORKTintedImageView *currentSceneImageView = viewController.sceneView.imageView;
                          [[ORKTintedImageCache sharedCache] cacheImage:nextConsentSection.image
                                                              tintColor:currentSceneImageView.tintColor
                                                                  scale:currentSceneImageView.window.screen.scale];
                      }
                  }];
}

- (void)showViewController:(ORKConsentSceneViewController *)viewController
                   forward:(BOOL)forward
                  animated:(BOOL)animated
                completion:(void (^)(BOOL finished))completion {
    if (!viewController) {
        if (completion) {
            completion(NO);
        }
        return;
    }
    // Stop old hairline scroll view observer and start new one
    _scrollViewObserver = [[ORKScrollViewObserver alloc] initWithTargetView:viewController.scrollView delegate:self];
    [self.taskViewController setRegisteredScrollView:viewController.scrollView];

    ORKConsentSceneViewController *fromViewController = nil;
    NSUInteger currentIndex = [self currentIndex];
    if (currentIndex == NSNotFound) {
        animated = NO;
    } else {
        fromViewController = _viewControllers[@(currentIndex)];
    }

    // Cancel any previous video animation
    fromViewController.imageHidden = NO;
    viewController.imageHidden = NO;
    if (_animator) {
        [self animationPlayerView].hidden = YES;
        [_animator finish];
        _animator = nil;
    }

    UIPageViewControllerNavigationDirection direction = forward ? UIPageViewControllerNavigationDirectionForward : UIPageViewControllerNavigationDirectionReverse;

    ORKAdjustPageViewControllerNavigationDirectionForRTL(&direction);

    if (!animated) {
        // No animation at all
        viewController.imageHidden = NO;
        [self doShowViewController:viewController direction:direction animated:animated completion:completion];
    } else {
        NSUInteger toIndex = [self indexOfViewController:viewController];

        NSURL *url = nil;
        BOOL animateBeforeTransition = NO;
        BOOL transitionBeforeAnimate = NO;

        ORKConsentSectionType currentSection = [(ORKConsentSection *)_visualSections[currentIndex] type];
        ORKConsentSectionType destinationSection = (toIndex != NSNotFound) ? [(ORKConsentSection *)_visualSections[toIndex] type] : ORKConsentSectionTypeCustom;

        // Only use video animation when going forward
        if (toIndex > currentIndex) {

            // Use the custom animation URL, if there is one for the destination index.
            if (toIndex != NSNotFound && toIndex < _visualSections.count) {
                url = [ORKDynamicCast(_visualSections[toIndex], ORKConsentSection) customAnimationURL];
            }
            BOOL isCustomURL = (url != nil);

            // If there's no custom URL, use an animation only if transitioning in the expected order.
            // Exception for datagathering, which does an arrival animation AFTER.
            if (!isCustomURL) {
                if (destinationSection == ORKConsentSectionTypeDataGathering) {
                    transitionBeforeAnimate = YES;
                    url = ORKMovieURLForConsentSectionType(ORKConsentSectionTypeOverview);
                } else if ((destinationSection - currentSection) == 1) {
                    url = ORKMovieURLForConsentSectionType(currentSection);
                }
            }
        }

        if (!url) {
            // No video animation URL, just a regular push transition animation.
            [self doShowViewController:viewController direction:direction animated:animated completion:completion];
        } else {
            [self doAnimateFromViewController:fromViewController
                                 toController:viewController
                                    direction:direction
                                          url:url
                      animateBeforeTransition:animateBeforeTransition
                      transitionBeforeAnimate:transitionBeforeAnimate
                                   completion:completion];
        }
    }
}

- (ORKConsentSceneViewController *)viewControllerForIndex:(NSUInteger)index {
    if (_viewControllers == nil) {
        _viewControllers = [NSMutableDictionary new];
    }

    ORKConsentSceneViewController *consentViewController = nil;

    if (_viewControllers[@(index)]) {
        consentViewController = _viewControllers[@(index)];
    } else if (index >= [self pageCount]) {
        consentViewController = nil;
    } else {
        ORKConsentSceneViewController *sceneViewController = [[ORKConsentSceneViewController alloc] initWithSection:[self visualSections][index]];
        consentViewController = sceneViewController;

        if (index == [self pageCount]-1) {
            sceneViewController.continueButtonItem = self.continueButtonItem;
        } else {
            NSString *buttonTitle = ORKLocalizedString(@"BUTTON_NEXT", nil);
            if (sceneViewController.section.type == ORKConsentSectionTypeOverview) {
                buttonTitle = ORKLocalizedString(@"BUTTON_GET_STARTED", nil);
            }

            sceneViewController.continueButtonItem = [[UIBarButtonItem alloc] initWithTitle:buttonTitle style:UIBarButtonItemStylePlain target:self action:@selector(next)];
        }
    }

    if (consentViewController) {
        _viewControllers[@(index)] = consentViewController;
    }

    return consentViewController;
}

- (NSUInteger)indexOfViewController:(UIViewController *)viewController {
    if (!viewController) {
        return NSNotFound;
    }

    NSUInteger index = NSNotFound;
    for (NSNumber *key in _viewControllers) {
        if (_viewControllers[key] == viewController) {
            index = key.unsignedIntegerValue;
            break;
        }
    }
    return index;
}

- (NSUInteger)currentIndex {
    return [self indexOfViewController:_pageViewController.viewControllers.firstObject];
}

#pragma mark - UIPageViewControllerDataSource

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
    NSUInteger index = [self indexOfViewController:viewController];
    if (index == NSNotFound) {
        return nil;
    }

    return [self viewControllerForIndex:index - 1];
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
    NSUInteger index = [self indexOfViewController:viewController];
    if (index == NSNotFound) {
        return nil;
    }

    return [self viewControllerForIndex:index + 1];
}

#pragma mark - UIPageViewControllerDelegate

- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished
   previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed {
    if (finished && completed) {
        [self updatePageIndex];
    }
}

static NSString *const _ORKCurrentPageRestoreKey = @"currentPage";
static NSString *const _ORKHasAppearedRestoreKey = @"hasAppeared";
static NSString *const _ORKInitialBackButtonRestoreKey = @"initialBackButton";

- (void)encodeRestorableStateWithCoder:(NSCoder *)coder {
    [super encodeRestorableStateWithCoder:coder];

    [coder encodeInteger:_currentPage forKey:_ORKCurrentPageRestoreKey];
    [coder encodeBool:_hasAppeared forKey:_ORKHasAppearedRestoreKey];
}

- (void)decodeRestorableStateWithCoder:(NSCoder *)coder {
    [super decodeRestorableStateWithCoder:coder];

    self.currentPage = [coder decodeIntegerForKey:_ORKCurrentPageRestoreKey];
    _hasAppeared = [coder decodeBoolForKey:_ORKHasAppearedRestoreKey];

    _viewControllers = nil;
    [self showViewController:[self viewControllerForIndex:_currentPage] forward:YES animated:NO];
}

@end