text:
package sun.awt.X11;

import sun.misc.Unsafe;

import sun.util.logging.PlatformLogger;

import java.awt.AWTKeyStroke;
import java.awt.event.InputEvent;

/**
 * Common class for all XEmbed protocol participating classes.
 * Contains constant definitions and helper routines.
 */
public class XEmbedHelper {
    private static final PlatformLogger xembedLog = PlatformLogger.getLogger("sun.awt.X11.xembed");
    final static Unsafe unsafe = Unsafe.getUnsafe();

    final static int XEMBED_VERSION = 0,
        XEMBED_MAPPED = (1 << 0);
/* XEMBED messages */
    final static int XEMBED_EMBEDDED_NOTIFY     =       0;
    final static int XEMBED_WINDOW_ACTIVATE  =  1;
    final static int XEMBED_WINDOW_DEACTIVATE =         2;
    final static int XEMBED_REQUEST_FOCUS               =3;
    final static int XEMBED_FOCUS_IN    =       4;
    final static int XEMBED_FOCUS_OUT   =       5;
    final static int XEMBED_FOCUS_NEXT  =       6;
    final static int XEMBED_FOCUS_PREV  =       7;
/* 8-9 were used for XEMBED_GRAB_KEY/XEMBED_UNGRAB_KEY */
    final static int XEMBED_GRAB_KEY = 8;
    final static int XEMBED_UNGRAB_KEY = 9;
    final static int XEMBED_MODALITY_ON         =       10;
    final static int XEMBED_MODALITY_OFF        =       11;
    final static int XEMBED_REGISTER_ACCELERATOR =    12;
    final static int XEMBED_UNREGISTER_ACCELERATOR=   13;
    final static int XEMBED_ACTIVATE_ACCELERATOR  =   14;

    final static int NON_STANDARD_XEMBED_GTK_GRAB_KEY = 108;
    final static int NON_STANDARD_XEMBED_GTK_UNGRAB_KEY = 109;

//     A detail code is required for XEMBED_FOCUS_IN. The following values are valid:
/* Details for  XEMBED_FOCUS_IN: */
    final static int XEMBED_FOCUS_CURRENT       =       0;
    final static int XEMBED_FOCUS_FIRST         =       1;
    final static int XEMBED_FOCUS_LAST  =       2;

// Modifiers bits
    final static int XEMBED_MODIFIER_SHIFT   = (1 << 0);
    final static int XEMBED_MODIFIER_CONTROL = (1 << 1);
    final static int XEMBED_MODIFIER_ALT     = (1 << 2);
    final static int XEMBED_MODIFIER_SUPER   = (1 << 3);
    final static int XEMBED_MODIFIER_HYPER   = (1 << 4);

    static XAtom XEmbedInfo;
    static XAtom XEmbed;

    XEmbedHelper() {
        if (XEmbed == null) {
            XEmbed = XAtom.get("_XEMBED");
            if (xembedLog.isLoggable(PlatformLogger.FINER)) xembedLog.finer("Created atom " + XEmbed.toString());
        }
        if (XEmbedInfo == null) {
            XEmbedInfo = XAtom.get("_XEMBED_INFO");
            if (xembedLog.isLoggable(PlatformLogger.FINER)) xembedLog.finer("Created atom " + XEmbedInfo.toString());
        }
    }

    void sendMessage(long window, int message) {
        sendMessage(window, message, 0, 0, 0);
    }
    void sendMessage(long window, int message, long detail, long data1, long data2) {
        XClientMessageEvent msg = new XClientMessageEvent();
        msg.set_type((int)XConstants.ClientMessage);
        msg.set_window(window);
        msg.set_message_type(XEmbed.getAtom());
        msg.set_format(32);
        msg.set_data(0, XToolkit.getCurrentServerTime());
        msg.set_data(1, message);
        msg.set_data(2, detail);
        msg.set_data(3, data1);
        msg.set_data(4, data2);
        XToolkit.awtLock();
        try {
            if (xembedLog.isLoggable(PlatformLogger.FINE)) xembedLog.fine("Sending " + XEmbedMessageToString(msg));
            XlibWrapper.XSendEvent(XToolkit.getDisplay(), window, false, XConstants.NoEventMask, msg.pData);
        }
        finally {
            XToolkit.awtUnlock();
        }
        msg.dispose();
    }

    static String msgidToString(int msg_id) {
        switch (msg_id) {
          case XEMBED_EMBEDDED_NOTIFY:
              return "XEMBED_EMBEDDED_NOTIFY";
          case XEMBED_WINDOW_ACTIVATE:
              return "XEMBED_WINDOW_ACTIVATE";
          case XEMBED_WINDOW_DEACTIVATE:
              return "XEMBED_WINDOW_DEACTIVATE";
          case XEMBED_FOCUS_IN:
              return "XEMBED_FOCUS_IN";
          case XEMBED_FOCUS_OUT:
              return "XEMBED_FOCUS_OUT";
          case XEMBED_REQUEST_FOCUS:
              return "XEMBED_REQUEST_FOCUS";
          case XEMBED_FOCUS_NEXT:
              return "XEMBED_FOCUS_NEXT";
          case XEMBED_FOCUS_PREV:
              return "XEMBED_FOCUS_PREV";
          case XEMBED_MODALITY_ON:
              return "XEMBED_MODALITY_ON";
          case XEMBED_MODALITY_OFF:
              return "XEMBED_MODALITY_OFF";
          case XEMBED_REGISTER_ACCELERATOR:
              return "XEMBED_REGISTER_ACCELERATOR";
          case XEMBED_UNREGISTER_ACCELERATOR:
              return "XEMBED_UNREGISTER_ACCELERATOR";
          case XEMBED_ACTIVATE_ACCELERATOR:
              return "XEMBED_ACTIVATE_ACCELERATOR";
          case XEMBED_GRAB_KEY:
              return "XEMBED_GRAB_KEY";
          case XEMBED_UNGRAB_KEY:
              return "XEMBED_UNGRAB_KEY";
          case NON_STANDARD_XEMBED_GTK_UNGRAB_KEY:
              return "NON_STANDARD_XEMBED_GTK_UNGRAB_KEY";
          case NON_STANDARD_XEMBED_GTK_GRAB_KEY:
              return "NON_STANDARD_XEMBED_GTK_GRAB_KEY";
          case XConstants.KeyPress | XEmbedServerTester.SYSTEM_EVENT_MASK:
              return "KeyPress";
          case XConstants.MapNotify | XEmbedServerTester.SYSTEM_EVENT_MASK:
              return "MapNotify";
          case XConstants.PropertyNotify | XEmbedServerTester.SYSTEM_EVENT_MASK:
              return "PropertyNotify";
          default:
              return "unknown XEMBED id " + msg_id;
        }
    }

    static String focusIdToString(int focus_id) {
        switch(focus_id) {
          case XEMBED_FOCUS_CURRENT:
              return "XEMBED_FOCUS_CURRENT";
          case XEMBED_FOCUS_FIRST:
              return "XEMBED_FOCUS_FIRST";
          case XEMBED_FOCUS_LAST:
              return "XEMBED_FOCUS_LAST";
          default:
              return "unknown focus id " + focus_id;
        }
    }

    static String XEmbedMessageToString(XClientMessageEvent msg) {
        return ("XEmbed message to " + Long.toHexString(msg.get_window()) + ": " + msgidToString((int)msg.get_data(1)) +
                ", detail: " + msg.get_data(2) +
                ", data:[" + msg.get_data(3) + "," + msg.get_data(4) + "]");

    }

    /**
     * Converts XEMBED modifiers mask into AWT InputEvent mask
     */
    int getModifiers(int state) {
        int mods = 0;
        if ((state & XEMBED_MODIFIER_SHIFT) != 0) {
            mods |= InputEvent.SHIFT_DOWN_MASK;
        }
        if ((state & XEMBED_MODIFIER_CONTROL) != 0) {
            mods |= InputEvent.CTRL_DOWN_MASK;
        }
        if ((state & XEMBED_MODIFIER_ALT) != 0) {
            mods |= InputEvent.ALT_DOWN_MASK;
        }
        // FIXME: What is super/hyper?
        // FIXME: Experiments show that SUPER is ALT. So what is Alt then?
        if ((state & XEMBED_MODIFIER_SUPER) != 0) {
            mods |= InputEvent.ALT_DOWN_MASK;
        }
//         if ((state & XEMBED_MODIFIER_HYPER) != 0) {
//             mods |= InputEvent.DOWN_MASK;
//         }
        return mods;
    }

    // Shouldn't be called on Toolkit thread.
    AWTKeyStroke getKeyStrokeForKeySym(long keysym, long state) {
        XBaseWindow.checkSecurity();

        int keycode;

        XToolkit.awtLock();
        try {
            XKeysym.Keysym2JavaKeycode kc = XKeysym.getJavaKeycode( keysym );
            if(kc == null) {
                keycode = java.awt.event.KeyEvent.VK_UNDEFINED;
            }else{
                keycode = kc.getJavaKeycode();
            }
        } finally {
            XToolkit.awtUnlock();
        }

        int modifiers = getModifiers((int)state);
        return AWTKeyStroke.getAWTKeyStroke(keycode, modifiers);
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AllEntitlementsResponse>
    <entitledResultSetDTO>
        <advanceResult>true</advanceResult>
        <entitledAttributesDTOs>
            <allActions>false</allActions>
            <allResources>false</allResources>
            <attributeDTOs>
                <attributeDataType>http://www.w3.org/2001/XMLSchema#string</attributeDataType>
                <attributeId>urn:oasis:names:tc:xacml:1.0:resource:resource-id</attributeId>
                <attributeValue>http://127.0.0.1/service/very_secure/</attributeValue>
                <category>urn:oasis:names:tc:xacml:3.0:attribute-category:resource</category>
            </attributeDTOs>
            <attributeDTOs>
                <attributeDataType>http://www.w3.org/2001/XMLSchema#string</attributeDataType>
                <attributeId>urn:oasis:names:tc:xacml:1.0:action:action-id</attributeId>
                <attributeValue>read</attributeValue>
                <category>urn:oasis:names:tc:xacml:3.0:attribute-category:action</category>
            </attributeDTOs>
        </entitledAttributesDTOs>
    </entitledResultSetDTO>
</AllEntitlementsResponse>

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8" ?>
<shader compiler="shaderweaver" name="terrain" lights="6">

  <alias name="ambient" file="/shader-snippets/lighting/ambient-simple.xml" />
  <alias name="apply_alpha" file="/shader-snippets/surface//alpha-premult.xml" />
  <alias name="lighting" file="/shader-snippets/lighting/lighting-ppl.xml" />

  <technique priority="500" minlights="1">
    <!-- 1 pass, 6 lights -->
    <pass>
      <?if (vars."pass number".int == 0) && (vars."pass do_ambient") ?>
      <!-- First pass: blend with alpha -->
      <mixmode>
        <blendop src="one" dst="srcalpha_inv" />
        <alphatest>disable</alphatest>
      </mixmode>
      <?else?>
      <!-- Later pass: blend with add -->
      <mixmode>
        <blendop src="one" dst="one" />
        <alphatest>disable</alphatest>
      </mixmode>
      <?endif?>

      <combiner plugin="crystalspace.graphics3d.shader.combiner.glcg" />

      <snippet id="shared" file="/shader-snippets/terrain/terrain-shared.xml" />

      <parameter id="lightOffset" type="int">0</parameter>
      <parameter id="maxLights" type="int">6</parameter>
      <parameter id="minLights" type="int">1</parameter>
      <connection from="lightOffset" to="shared" />
      <connection from="maxLights" to="shared" />
      <connection from="minLights" to="shared" />

    </pass>
  </technique>

  <!-- No lights (ie ambient only) technique -->
    <?if (vars."pass number".int == 0) && (vars."pass do_ambient") ?>
    <technique priority="50">
      <tag>per_pixel_lighting</tag>
      <pass>
        <!-- First(only) pass: blend with alpha -->
        <mixmode>
  	<blendop src="one" dst="srcalpha_inv" />
  	<alphatest>disable</alphatest>
        </mixmode>

        <combiner plugin="crystalspace.graphics3d.shader.combiner.glcg" />

        <snippet id="shared" file="/shader-snippets/terrain/terrain-shared.xml" />

        <parameter id="lightOffset" type="int">0</parameter>
	<parameter id="maxLights" type="int">0</parameter>
	<parameter id="minLights" type="int">0</parameter>
	<connection from="lightOffset" to="shared" />
	<connection from="maxLights" to="shared" />
        <connection from="minLights" to="shared" />
      </pass>
    </technique>
  <?endif?>

</shader>


text:
.login-open .icon{font-size:30px;}
.login-open  a{color:#FFF;}
.login-open  a:hover{filter:alpha(opacity=50);-moz-opacity:0.5; opacity:0.5;}

.login-form .form-group{overflow:hidden;border-bottom:thin solid #eee;padding:0 10px;}
.login-form .form-group .input{border:none;box-shadow:none;padding:0 10px 0 40px;height:40px;text-indent:0;}
.login-form .form-group .icon{height:40px;line-height:40px;}

.reg-form .text-input{border:none;width:100%;}
.reg-form  label{color:#999;}

.text-input {border:none;width:100%;}
.text-select{border:none;width:100%;background:#fff!important;}
.text-area{width:100%;border:none;resize:none;padding:10px;}.fabu-form .row{padding:10px;border-bottom:thin solid #eee;}
.fabu-form .row .x3{color:#999;}
.fabu-form .text-input{border:none;width:100%;}
.fabu-form .text-select{border:none;width:100%;background:#fff!important;}
.fabu-form .text-area{width:100%;border:thin solid #eee;resize:none;}
#picker{display:inline-block;line-height:1.428571429;vertical-align:middle;margin:0 12px 0 0;}
#picker .webuploader-pick{padding:6px 12px;display: block;}
.uploader .thumbnail{width:25%;max-height:100px;}
.uploader .thumbnail img{width:95%;height:100px;background:url("../image/tieba/loading.png") center no-repeat;}
.uploader-list{width:100%;overflow:hidden;background:#fff;}
.file-item{float:left;position:relative;background:#fff;margin-top:10px;}
.upload-state-done:after{content:"\f00c";font-family:FontAwesome;font-style:normal;font-weight:normal;line-height:1;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing:grayscale;font-size:16px;position: absolute;bottom: 0;right:10%;color:#4cae4c;z-index:99;}
/*切换TAB*/
.tab-bar{text-align:center;padding:10px 0;background:#fafafa;border-bottom:thin solid #eee;}
.tab-bar a{background:#fff;padding:8px 20px;}
.tab-bar a:focus{border:none;border: 1px solid #EEE;}
.tab-bar a.active{background:#E9553B;}


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

import com.google.devtools.build.lib.events.Event;

/**
 * A loaded package that can verify whether it is still up to date.
 */
interface LoadedPackage {
  /**
   * Returns the actual loaded {@link Package} object.
   */
  Package getPackage();

  /**
   * Returns true iff the entry is still valid.
   *
   * <p>An entry is valid when the package it denotes has not been moved, deleted, or changed. This
   * requires disk I/O to fetch metadata and re-evaluate globs.
   */
  boolean isValid() throws InterruptedException;

  /**
   * Returns true iff the the contents of the package are guaranteed not to have changed after
   * between {@link #isValid()} calls and syncs of the associated package loader.
   */
  boolean contentsCouldNotHaveChanged();

  /**
   * Returns the set of events (sorted by the order they were reported) that occurred during the
   * loading of the package.
   */
  Iterable<Event> getEvents();
}


text:
<?php

namespace Donquixote\Cellbrush\Axis;

class Range extends SimpleRange {

  /**
   * @var Axis
   */
  private $axis;

  /**
   * @var string
   */
  private $name;

  /**
   * @param int $iMin
   * @param int $iSup
   * @param string $name
   * @param Axis $axis
   */
  function __construct($iMin, $iSup, $name, Axis $axis) {
    parent::__construct($iMin, $iSup);
    $this->name = $name;
    $this->axis = $axis;
  }

  /**
   * @return static
   */
  public function getNext() {
    $nextName = $this->axis->nameGetNextName($this->name);
    return isset($nextName)
      ? $this->axis->subtreeRange($nextName)
      : null;
  }
}


text:
import subprocess
import json
import argparse
import os
import logging
import sys

from ci_tools.environment_exclusions import is_ignored_package, VERIFYTYPES_OPT_OUT

logging.getLogger().setLevel(logging.INFO)

def install_editable(setup_path):
    commands = [sys.executable, "-m", "pip", "install", "-e", setup_path]
    subprocess.check_call(commands)

def install_latest_release(package_name):
    from pypi_tools.pypi import PyPIClient

    client = PyPIClient()

    try:
        latest_version = str(client.get_ordered_versions(package_name)[-1])
    except (IndexError, KeyError):
        logging.info(f"No released packages for {package_name} on PyPi yet.")
        latest_version = None

    if latest_version:
        packages = [f"{package_name}=={latest_version}"]
        commands = [
            sys.executable,
            "-m",
            "pip",
            "install",
        ]

        commands.extend(packages)
        subprocess.check_call(commands)
    return latest_version

def get_type_complete_score(commands, check_pytyped=False):
    try:
        response = subprocess.run(
            commands,
            check=True,
            capture_output=True,
        )
    except subprocess.CalledProcessError as e:
        if e.returncode != 1:
            logging.info(
                f"Running verifytypes failed: {e.stderr}. See https://aka.ms/python/typing-guide for information."
            )
            exit(1)

        report = json.loads(e.output)
        if check_pytyped:
            pytyped_present = report["typeCompleteness"].get("pyTypedPath", None)
            if not pytyped_present:
                print(
                    f"No py.typed file was found. See aka.ms/python/typing-guide for information."
                )
                exit(1)
        return report["typeCompleteness"]["completenessScore"]

    # library scores 100%
    report = json.loads(response.stdout)
    return report["typeCompleteness"]["completenessScore"]

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Run pyright verifytypes against target folder. "
    )

    parser.add_argument(
        "-t",
        "--target",
        dest="target_package",
        help="The target package directory on disk. The target module passed to run pyright will be <target_package>/azure.",
        required=True,
    )

    args = parser.parse_args()
    package_name = os.path.basename(os.path.abspath(args.target_package))
    module = package_name.replace("-", ".")
    setup_path = os.path.abspath(args.target_package)

    if package_name in VERIFYTYPES_OPT_OUT or is_ignored_package(package_name):
        logging.info(
            f"{package_name} opts-out of verifytypes check. See https://aka.ms/python/typing-guide for information."
        )
        exit(0)

    commands = [
        sys.executable,
        "-m",
        "pyright",
        "--verifytypes",
        module,
        "--ignoreexternal",
        "--outputjson",
    ]

    # get type completeness score from latest release
    latest_version = install_latest_release(package_name)
    if latest_version:
        score_from_released = get_type_complete_score(commands)
    else:
        score_from_released = None

    # get type completeness score from current code
    install_editable(setup_path)
    score_from_current = get_type_complete_score(commands, check_pytyped=True)

    try:
        subprocess.check_call(commands[:-1])
    except subprocess.CalledProcessError:
        pass  # we don't fail on verifytypes, only if type completeness score worsens from last release

    if score_from_released is not None:
        score_from_released_rounded = round(score_from_released * 100, 1)
        score_from_current_rounded = round(score_from_current * 100, 1)
        print("\n-----Type completeness score comparison-----\n")
        print(f"Previous release ({latest_version}): {score_from_released_rounded}%")
        if score_from_current_rounded < score_from_released_rounded:
            print(
                f"\nERROR: The type completeness score of {package_name} has decreased since the last release. "
                f"See the above output for areas to improve. See https://aka.ms/python/typing-guide for information."
            )
            exit(1)


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

Configuring Calico
==================

This page describes how to configure Calico. We first describe the
configuration of the core Calico component - Felix -
because this is needed, and configured similarly, regardless of the
surrounding environment (OpenStack, Docker, or whatever). Then,
depending on that surrounding environment, there will be some further
configuration of that environment needed, to tell it to talk to the
Calico components.

Currently we have detailed environment configuration only for OpenStack.
Work on other environments is in progress, and this page will be
extended as that happens.

This page aims to be a complete Calico configuration reference, and
hence to describe all the possible fields, files etc. For a more
task-based approach, when installing Calico with OpenStack on Ubuntu or
Red Hat, please see :doc:`ubuntu-opens-install` or
:doc:`redhat-opens-install`.

Calico components
-----------------

The core Calico component is Felix. (Please see :doc:`architecture`
for the Calico architecture.)

Felix (/etc/calico/felix.cfg)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Felix runs on each compute host, and is configured by an ini-style
config file at ``/etc/calico/felix.cfg``.

The settings that can be specified in this file all have sensible
defaults, so may not require explicit editing.

+-----------------------+------------------------+-------------------------------------------------------------------------------------------+
| Setting               | Default                | Meaning                                                                                |
+=======================+========================+===========================================================================================+
| global.EtcdAddr       | localhost:4001         | The location of the etcd node or proxy that Felix should connect to.                      |
+-----------------------+------------------------+-------------------------------------------------------------------------------------------+
| global.FelixHostname  | socket.gethostname()   | The hostname Felix reports to the plugin. Should be used if the hostname Felix            |
|                       |                        | autodetects is incorrect or does not match what the plugin will expect.                   |
+-----------------------+------------------------+-------------------------------------------------------------------------------------------+

OpenStack environment configuration
-----------------------------------

When running Calico with OpenStack, you also need to configure various
OpenStack components, as follows.

Nova (/etc/nova/nova.conf)
^^^^^^^^^^^^^^^^^^^^^^^^^^

Calico uses the Nova metadata service to provide metadata to VMs,
without any proxying by Neutron. To make that work:

-  An instance of the Nova metadata API must run on every compute node.

-  ``/etc/nova/nova.conf`` must not set
   ``service_neutron_metadata_proxy`` or ``service_metadata_proxy`` to
   ``True``. (The default ``False`` value is correct for a Calico
   cluster.)

Neutron server (/etc/neutron/neutron.conf)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

In ``/etc/neutron/neutron.conf`` you need the following settings to
configure the Neutron service.

+------------------------------+----------------------------------------+-------------------------------------------+
| Setting                      | Value                                  | Meaning                                   |
+==============================+========================================+===========================================+
| core\_plugin                 | neutron.plugins.ml2.plugin.Ml2Plugin   | Use ML2 plugin                            |
+------------------------------+----------------------------------------+-------------------------------------------+
| api\_workers                 | 0                                      | Don't use worker threads                  |
+------------------------------+----------------------------------------+-------------------------------------------+
| rpc\_workers                 | 0                                      | Don't use worker threads                  |
+------------------------------+----------------------------------------+-------------------------------------------+
| dhcp\_agents\_per\_network   | 9999                                   | Allow unlimited DHCP agents per network   |
+------------------------------+----------------------------------------+-------------------------------------------+

Optionally -- depending on how you want the Calico mechanism driver to
connect to the Etcd cluster -- you can also set the following options
in the ``[calico]`` section of ``/etc/neutron/neutron.conf``.

+-----------------+-------------------+-------------------------------------------+
| Setting         | Default Value     | Meaning                                   |
+=================+===================+===========================================+
| etcd\_host      | localhost         | The hostname or IP of the etcd node/proxy |
+-----------------+-------------------+-------------------------------------------+
| etcd\_port      | 4001              | The port to use for the etcd node/proxy   |
+-----------------+-------------------+-------------------------------------------+

ML2 (.../ml2\_conf.ini)
^^^^^^^^^^^^^^^^^^^^^^^

In ``/etc/neutron/plugins/ml2/ml2_conf.ini`` you need the following
settings to configure the ML2 plugin.

+--------------------------+---------------+-------------------------------------+
| Setting                  | Value         | Meaning                             |
+==========================+===============+=====================================+
| mechanism\_drivers       | calico        | Use Calico                          |
+--------------------------+---------------+-------------------------------------+
| type\_drivers            | local, flat   | Allow 'local' and 'flat' networks   |
+--------------------------+---------------+-------------------------------------+
| tenant\_network\_types   | local, flat   | Allow 'local' and 'flat' networks   |
+--------------------------+---------------+-------------------------------------+

DHCP agent (.../dhcp\_agent.ini)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

In ``/etc/neutron/dhcp_agent.ini`` you need the following settings to
configure the Neutron DHCP agent.

+---------------------+-------------------------+--------------------------------------------------------------------------------------------------------+
| Setting             | Value                   | Meaning                                                                                |
+=====================+=========================+========================================================================================================+
| interface\_driver   | RoutedInterfaceDriver   | Use Calico's modified DHCP agent support for TAP interfaces that are routed instead of being bridged   |
+---------------------+-------------------------+--------------------------------------------------------------------------------------------------------+


text:
package org.jrbsoft.statistic.protocol.jmx.connecting;

import javax.management.MBeanServer;

class EmbeddedMBeanServerClientImpl implements IMBeanControllerClient {

	private MBeanServer _mbeanServer;

	EmbeddedMBeanServerClientImpl(final MBeanServer server) {
		_mbeanServer = server;
	}

	@Override
	public MBeanServer getMBeanServer() {
		return _mbeanServer;
	}

}


text:
package org.jkiss.dbeaver.model.sql.commands;

import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.model.sql.SQLControlCommand;
import org.jkiss.dbeaver.model.sql.SQLControlCommandHandler;
import org.jkiss.dbeaver.model.sql.SQLScriptContext;

/**
 * Control command handler
 */
public class SQLCommandUnset implements SQLControlCommandHandler {

    @Override
    public boolean handleCommand(SQLControlCommand command, SQLScriptContext scriptContext) throws DBException {
        String varName = command.getParameter();
        scriptContext.removeVariable(varName);

        return true;
    }

}


text:
<?php
/**
 * This file is part of the Catalyst Swoole Foundation.
 *
 * (c)2017 Matthias Kaschubowski and the Catalyst Collective
 *
 * This code is licensed under the MIT license,
 * a copy of the license is stored at the project root.
 */

namespace Catalyst\Swoole\Servants;

use Catalyst\Servant\RepositoryServant;

/**
 * Class FactoryServant
 *
 * @package Catalyst\Swoole\Servants
 */
class FactoryServant extends RepositoryServant
{
    /**
     * returns the reflection of the provided closure.
     *
     * @param \Closure $closure
     * @return \ReflectionFunction
     */
    public function reflect(\Closure $closure): \ReflectionFunction
    {
        return new \ReflectionFunction($closure);
    }
}


text:
<html dir="ltr" lang="cs">
<head>
  <meta charset="utf-8">
  <title>Blockly Puzzle</title>
  <link rel="stylesheet" type="text/css" href="style.css">
  <script type="text/javascript" src="../_soy/soyutils.js"></script>
  <script type="text/javascript" src="cs.js"></script>
  <script type="text/javascript" src="../../blockly_compressed.js"></script>
  <script type="text/javascript" src="../../language/en/_messages.js"></script>
</head>
<body>
  <script type="text/javascript" src="puzzle.js"></script>
</body>
</html>


text:
package test.listeners.issue2061;

import org.testng.ISuite;
import org.testng.ISuiteListener;

public class DynamicSuiteListener implements ISuiteListener {

  @Override
  public void onStart(ISuite suite) {
    suite.addListener(new DynamicTestListener());
  }
}


text:
#ifndef _GDIPLUSPATH_H
#define _GDIPLUSPATH_H

class GraphicsPath : public GdiplusBase
{
public:
    friend class Graphics;
    friend class Region;
    friend class PathGradientBrush;
    friend class GraphicsPathIterator;
    friend class CustomLineCap;

    GraphicsPath(IN FillMode fillMode = FillModeAlternate)
    {
        nativePath = NULL;
        lastResult = DllExports::GdipCreatePath(fillMode, &nativePath);
    }

    GraphicsPath(IN const PointF* points,
                 IN const BYTE* types,
                 IN INT count,
                 IN FillMode fillMode = FillModeAlternate)
    {
        nativePath = NULL;
        lastResult = DllExports::GdipCreatePath2(points,
                                                 types,
                                                 count,
                                                 fillMode,
                                                 &nativePath);
    }

    GraphicsPath(IN const Point* points,
                 IN const BYTE* types,
                 IN INT count,
                 IN FillMode fillMode = FillModeAlternate)
    {
        nativePath = NULL;
        lastResult = DllExports::GdipCreatePath2I(points,
                                                  types,
                                                  count,
                                                  fillMode,
                                                  &nativePath);
    }

    ~GraphicsPath()
    {
        DllExports::GdipDeletePath(nativePath);
    }

    GraphicsPath* Clone() const
    {
        GpPath *clonepath = NULL;

        SetStatus(DllExports::GdipClonePath(nativePath, &clonepath));

        return new GraphicsPath(clonepath);
    }

    // Reset the path object to empty (and fill mode to FillModeAlternate)

    Status Reset()
    {
        return SetStatus(DllExports::GdipResetPath(nativePath));
    }

    FillMode GetFillMode() const
    {
        FillMode fillmode = FillModeAlternate;

        SetStatus(DllExports::GdipGetPathFillMode(nativePath, &fillmode));

        return fillmode;
    }

    Status SetFillMode(IN FillMode fillmode)
    {
        return SetStatus(DllExports::GdipSetPathFillMode(nativePath,
                                                         fillmode));
    }

    Status GetPathData(OUT PathData* pathData) const
    {
        if (pathData == NULL)
        {
            return SetStatus(InvalidParameter);
        }

        INT count = GetPointCount();

        if ((count <= 0) || (pathData->Count>0 && pathData->Count<count))
        {
            pathData->Count = 0;
            if (pathData->Points)
            {
                delete pathData->Points;
                pathData->Points = NULL;
            }

            if (pathData->Types)
            {
                delete pathData->Types;
                pathData->Types = NULL;
            }

            if (count <= 0)
            {
                return lastResult;
            }
        }

        if (pathData->Count == 0)
        {
            pathData->Points = new PointF[count];
            if (pathData->Points == NULL)
            {
                return SetStatus(OutOfMemory);

            }
            pathData->Types = new byte[count];
            if (pathData->Types == NULL)
            {
                delete pathData->Points;
                pathData->Points = NULL;

                return SetStatus(OutOfMemory);
            }
            pathData->Count = count;
        }

        return SetStatus(DllExports::GdipGetPathData(nativePath, pathData));
    }

    Status StartFigure()
    {
        return SetStatus(DllExports::GdipStartPathFigure(nativePath));
    }

    Status CloseFigure()
    {
        return SetStatus(DllExports::GdipClosePathFigure(nativePath));
    }

    Status CloseAllFigures()
    {
        return SetStatus(DllExports::GdipClosePathFigures(nativePath));
    }

    Status SetMarker()
    {
        return SetStatus(DllExports::GdipSetPathMarker(nativePath));
    }

    Status ClearMarkers()
    {
        return SetStatus(DllExports::GdipClearPathMarkers(nativePath));
    }

    Status Reverse()
    {
        return SetStatus(DllExports::GdipReversePath(nativePath));
    }

    Status GetLastPoint(OUT PointF* lastPoint) const
    {
        return SetStatus(DllExports::GdipGetPathLastPoint(nativePath,
                                                          lastPoint));
    }

    Status AddLine(IN const PointF& pt1,
                   IN const PointF& pt2)
    {
        return AddLine(pt1.X, pt1.Y, pt2.X, pt2.Y);
    }

    Status AddLine(IN REAL x1,
                   IN REAL y1,
                   IN REAL x2,
                   IN REAL y2)
    {
        return SetStatus(DllExports::GdipAddPathLine(nativePath, x1, y1,
                                                     x2, y2));
    }

    Status AddLines(IN const PointF* points,
                    IN INT count)
    {
        return SetStatus(DllExports::GdipAddPathLine2(nativePath, points,
                                                      count));
    }

    Status AddLine(IN const Point& pt1,
                   IN const Point& pt2)
    {
        return AddLine(pt1.X,
                       pt1.Y,
                       pt2.X,
                       pt2.Y);
    }

    Status AddLine(IN INT x1,
                   IN INT y1,
                   IN INT x2,
                   IN INT y2)
    {
        return SetStatus(DllExports::GdipAddPathLineI(nativePath,
                                                     x1,
                                                     y1,
                                                     x2,
                                                     y2));
    }

    Status AddLines(IN const Point* points,
                    IN INT count)
    {
        return SetStatus(DllExports::GdipAddPathLine2I(nativePath,
                                                       points,
                                                       count));
    }

    Status AddArc(IN const RectF& rect,
                  IN REAL startAngle,
                  IN REAL sweepAngle)
    {
        return AddArc(rect.X, rect.Y, rect.Width, rect.Height,
                      startAngle, sweepAngle);
    }

    Status AddArc(IN REAL x,
                  IN REAL y,
                  IN REAL width,
                  IN REAL height,
                  IN REAL startAngle,
                  IN REAL sweepAngle)
    {
        return SetStatus(DllExports::GdipAddPathArc(nativePath, x, y, width,
                                                    height, startAngle,
                                                    sweepAngle));
    }

    Status AddArc(IN const Rect& rect,
                  IN REAL startAngle,
                  IN REAL sweepAngle)
    {
        return AddArc(rect.X, rect.Y, rect.Width, rect.Height,
                      startAngle, sweepAngle);
    }

    Status AddArc(IN INT x,
                  IN INT y,
                  IN INT width,
                  IN INT height,
                  IN REAL startAngle,
                  IN REAL sweepAngle)
    {
        return SetStatus(DllExports::GdipAddPathArcI(nativePath,
                                                    x,
                                                    y,
                                                    width,
                                                    height,
                                                    startAngle,
                                                    sweepAngle));
    }

    Status AddBezier(IN const PointF& pt1,
                     IN const PointF& pt2,
                     IN const PointF& pt3,
                     IN const PointF& pt4)
    {
        return AddBezier(pt1.X, pt1.Y, pt2.X, pt2.Y, pt3.X, pt3.Y, pt4.X,
                         pt4.Y);
    }

    Status AddBezier(IN REAL x1,
                     IN REAL y1,
                     IN REAL x2,
                     IN REAL y2,
                     IN REAL x3,
                     IN REAL y3,
                     IN REAL x4,
                     IN REAL y4)
    {
        return SetStatus(DllExports::GdipAddPathBezier(nativePath, x1, y1, x2,
                                                       y2, x3, y3, x4, y4));
    }

    Status AddBeziers(IN const PointF* points,
                      IN INT count)
    {
        return SetStatus(DllExports::GdipAddPathBeziers(nativePath, points,
                                                        count));
    }

    Status AddBezier(IN const Point& pt1,
                     IN const Point& pt2,
                     IN const Point& pt3,
                     IN const Point& pt4)
    {
       return AddBezier(pt1.X, pt1.Y, pt2.X, pt2.Y, pt3.X, pt3.Y, pt4.X,
                        pt4.Y);
    }

    Status AddBezier(IN INT x1,
                     IN INT y1,
                     IN INT x2,
                     IN INT y2,
                     IN INT x3,
                     IN INT y3,
                     IN INT x4,
                     IN INT y4)
    {
       return SetStatus(DllExports::GdipAddPathBezierI(nativePath,
                                                      x1,
                                                      y1,
                                                      x2,
                                                      y2,
                                                      x3,
                                                      y3,
                                                      x4,
                                                      y4));
    }

    Status AddBeziers(IN const Point* points,
                      IN INT count)
    {
       return SetStatus(DllExports::GdipAddPathBeziersI(nativePath,
                                                        points,
                                                        count));
    }

    Status AddCurve(IN const PointF* points,
                    IN INT count)
    {
        return SetStatus(DllExports::GdipAddPathCurve(nativePath,
                                                      points,
                                                      count));
    }

    Status AddCurve(IN const PointF* points,
                    IN INT count,
                    IN REAL tension)
    {
        return SetStatus(DllExports::GdipAddPathCurve2(nativePath,
                                                       points,
                                                       count,
                                                       tension));
    }

    Status AddCurve(IN const PointF* points,
                    IN INT count,
                    IN INT offset,
                    IN INT numberOfSegments,
                    IN REAL tension)
    {
        return SetStatus(DllExports::GdipAddPathCurve3(nativePath,
                                                       points,
                                                       count,
                                                       offset,
                                                       numberOfSegments,
                                                       tension));
    }

    Status AddCurve(IN const Point* points,
                    IN INT count)
    {
       return SetStatus(DllExports::GdipAddPathCurveI(nativePath,
                                                     points,
                                                     count));
    }

    Status AddCurve(IN const Point* points,
                    IN INT count,
                    IN REAL tension)
    {
       return SetStatus(DllExports::GdipAddPathCurve2I(nativePath,
                                                      points,
                                                      count,
                                                      tension));
    }

    Status AddCurve(IN const Point* points,
                    IN INT count,
                    IN INT offset,
                    IN INT numberOfSegments,
                    IN REAL tension)
    {
       return SetStatus(DllExports::GdipAddPathCurve3I(nativePath,
                                                      points,
                                                      count,
                                                      offset,
                                                      numberOfSegments,
                                                      tension));
    }

    Status AddClosedCurve(IN const PointF* points,
                          IN INT count)
    {
        return SetStatus(DllExports::GdipAddPathClosedCurve(nativePath,
                                                            points,
                                                            count));
    }

    Status AddClosedCurve(IN const PointF* points,
                          IN INT count,
                          IN REAL tension)
    {
        return SetStatus(DllExports::GdipAddPathClosedCurve2(nativePath,
                                                             points,
                                                             count,
                                                             tension));
    }

    Status AddClosedCurve(IN const Point* points,
                          IN INT count)
    {
       return SetStatus(DllExports::GdipAddPathClosedCurveI(nativePath,
                                                            points,
                                                            count));
    }

    Status AddClosedCurve(IN const Point* points,
                          IN INT count,
                          IN REAL tension)
    {
       return SetStatus(DllExports::GdipAddPathClosedCurve2I(nativePath,
                                                             points,
                                                             count,
                                                             tension));
    }

    Status AddRectangle(IN const RectF& rect)
    {
        return SetStatus(DllExports::GdipAddPathRectangle(nativePath,
                                                          rect.X,
                                                          rect.Y,
                                                          rect.Width,
                                                          rect.Height));
    }

    Status AddRectangles(IN const RectF* rects,
                         IN INT count)
    {
        return SetStatus(DllExports::GdipAddPathRectangles(nativePath,
                                                           rects,
                                                           count));
    }

    Status AddRectangle(IN const Rect& rect)
    {
        return SetStatus(DllExports::GdipAddPathRectangleI(nativePath,
                                                          rect.X,
                                                          rect.Y,
                                                          rect.Width,
                                                          rect.Height));
    }

    Status AddRectangles(IN const Rect* rects, INT count)
    {
        return SetStatus(DllExports::GdipAddPathRectanglesI(nativePath,
                                                           rects,
                                                           count));
    }

    Status AddEllipse(IN const RectF& rect)
    {
        return AddEllipse(rect.X, rect.Y, rect.Width, rect.Height);
    }

    Status AddEllipse(IN REAL x,
                      IN REAL y,
                      IN REAL width,
                      IN REAL height)
    {
        return SetStatus(DllExports::GdipAddPathEllipse(nativePath,
                                                        x,
                                                        y,
                                                        width,
                                                        height));
    }

    Status AddEllipse(IN const Rect& rect)
    {
        return AddEllipse(rect.X, rect.Y, rect.Width, rect.Height);
    }

    Status AddEllipse(IN INT x,
                      IN INT y,
                      IN INT width,
                      IN INT height)
    {
        return SetStatus(DllExports::GdipAddPathEllipseI(nativePath,
                                                        x,
                                                        y,
                                                        width,
                                                        height));
    }

    Status AddPie(IN const RectF& rect,
                  IN REAL startAngle,
                  IN REAL sweepAngle)
    {
        return AddPie(rect.X, rect.Y, rect.Width, rect.Height, startAngle,
                      sweepAngle);
    }

    Status AddPie(IN REAL x,
                  IN REAL y,
                  IN REAL width,
                  IN REAL height,
                  IN REAL startAngle,
                  IN REAL sweepAngle)
    {
        return SetStatus(DllExports::GdipAddPathPie(nativePath, x, y, width,
                                                    height, startAngle,
                                                    sweepAngle));
    }

    Status AddPie(IN const Rect& rect,
                  IN REAL startAngle,
                  IN REAL sweepAngle)
    {
        return AddPie(rect.X,
                      rect.Y,
                      rect.Width,
                      rect.Height,
                      startAngle,
                      sweepAngle);
    }

    Status AddPie(IN INT x,
                  IN INT y,
                  IN INT width,
                  IN INT height,
                  IN REAL startAngle,
                  IN REAL sweepAngle)
    {
        return SetStatus(DllExports::GdipAddPathPieI(nativePath,
                                                    x,
                                                    y,
                                                    width,
                                                    height,
                                                    startAngle,
                                                    sweepAngle));
    }

    Status AddPolygon(IN const PointF* points,
                      IN INT count)
    {
        return SetStatus(DllExports::GdipAddPathPolygon(nativePath, points,
                                                        count));
    }

    Status AddPolygon(IN const Point* points,
                      IN INT count)
    {
       return SetStatus(DllExports::GdipAddPathPolygonI(nativePath, points,
                                                        count));
    }

    Status AddPath(IN const GraphicsPath* addingPath,
                   IN BOOL connect)
    {
        GpPath* nativePath2 = NULL;
        if(addingPath)
            nativePath2 = addingPath->nativePath;

        return SetStatus(DllExports::GdipAddPathPath(nativePath, nativePath2,
                                                     connect));
    }

    Status AddString(
        IN const WCHAR         *string,
        IN INT                  length,
        IN const FontFamily    *family,
        IN INT                  style,
        IN REAL                 emSize,  // World units
        IN const PointF        &origin,
        IN const StringFormat  *format
    )
    {
        RectF rect(origin.X, origin.Y, 0.0f, 0.0f);

        return SetStatus(DllExports::GdipAddPathString(
            nativePath,
            string,
            length,
            family ? family->nativeFamily : NULL,
            style,
            emSize,
            &rect,
            format ? format->nativeFormat : NULL
        ));
    }

    Status AddString(
        IN const WCHAR         *string,
        IN INT                  length,
        IN const FontFamily    *family,
        IN INT                  style,
        IN REAL                 emSize,  // World units
        IN const RectF         &layoutRect,
        IN const StringFormat  *format
    )
    {
        return SetStatus(DllExports::GdipAddPathString(
            nativePath,
            string,
            length,
            family ? family->nativeFamily : NULL,
            style,
            emSize,
            &layoutRect,
            format ? format->nativeFormat : NULL
        ));
    }

    Status AddString(
        IN const WCHAR         *string,
        IN INT                  length,
        IN const FontFamily    *family,
        IN INT                  style,
        IN REAL                 emSize,  // World units
        IN const Point         &origin,
        IN const StringFormat  *format
    )
    {
        Rect rect(origin.X, origin.Y, 0, 0);

        return SetStatus(DllExports::GdipAddPathStringI(
            nativePath,
            string,
            length,
            family ? family->nativeFamily : NULL,
            style,
            emSize,
            &rect,
            format ? format->nativeFormat : NULL
        ));
    }

    Status AddString(
        IN const WCHAR         *string,
        IN INT                  length,
        IN const FontFamily    *family,
        IN INT                  style,
        IN REAL                 emSize,  // World units
        IN const Rect          &layoutRect,
        IN const StringFormat  *format
    )
    {
        return SetStatus(DllExports::GdipAddPathStringI(
            nativePath,
            string,
            length,
            family ? family->nativeFamily : NULL,
            style,
            emSize,
            &layoutRect,
            format ? format->nativeFormat : NULL
        ));
    }

    Status Transform(IN const Matrix* matrix)
    {
        if(matrix)
            return SetStatus(DllExports::GdipTransformPath(nativePath,
                                                      matrix->nativeMatrix));
        else
            return Ok;
    }

    // This is not always the tightest bounds.

    Status GetBounds(OUT RectF* bounds,
                     IN const Matrix* matrix = NULL,
                     IN const Pen* pen = NULL) const;

    Status GetBounds(OUT Rect* bounds,
                     IN const Matrix* matrix = NULL,
                     IN const Pen* pen = NULL) const;

    // Once flattened, the resultant path is made of line segments and
    // the original path information is lost.  When matrix is NULL the
    // identity matrix is assumed.

    Status Flatten(IN const Matrix* matrix = NULL,
                   IN REAL flatness = FlatnessDefault)
    {
        GpMatrix* nativeMatrix = NULL;
        if(matrix)
        {
            nativeMatrix = matrix->nativeMatrix;
        }

        return SetStatus(DllExports::GdipFlattenPath(
            nativePath,
            nativeMatrix,
            flatness
        ));
    }

    Status Widen(
        IN const Pen* pen,
        IN const Matrix* matrix = NULL,
        IN REAL flatness = FlatnessDefault
    )
    {
        GpMatrix* nativeMatrix = NULL;
        if(matrix)
            nativeMatrix = matrix->nativeMatrix;

        return SetStatus(DllExports::GdipWidenPath(
            nativePath,
            pen->nativePen,
            nativeMatrix,
            flatness
        ));
    }

    Status Outline(
        IN const Matrix *matrix = NULL,
        IN REAL flatness = FlatnessDefault
    )
    {
        GpMatrix* nativeMatrix = NULL;
        if(matrix)
        {
            nativeMatrix = matrix->nativeMatrix;
        }

        return SetStatus(DllExports::GdipWindingModeOutline(
            nativePath, nativeMatrix, flatness
        ));
    }

    // Once this is called, the resultant path is made of line segments and
    // the original path information is lost.  When matrix is NULL, the
    // identity matrix is assumed.

    Status Warp(IN const PointF* destPoints,
                IN INT count,
                IN const RectF& srcRect,
                IN const Matrix* matrix = NULL,
                IN WarpMode warpMode = WarpModePerspective,
                IN REAL flatness = FlatnessDefault)
    {
        GpMatrix* nativeMatrix = NULL;
        if(matrix)
            nativeMatrix = matrix->nativeMatrix;

        return SetStatus(DllExports::GdipWarpPath(
                                        nativePath,
                                        nativeMatrix,
                                        destPoints,
                                        count,
                                        srcRect.X,
                                        srcRect.Y,
                                        srcRect.Width,
                                        srcRect.Height,
                                        warpMode,
                                        flatness));
    }

    INT GetPointCount() const
    {
        INT count = 0;

        SetStatus(DllExports::GdipGetPointCount(nativePath, &count));

        return count;
    }

    Status GetPathTypes(OUT BYTE* types,
                        IN INT count) const
    {
        return SetStatus(DllExports::GdipGetPathTypes(nativePath, types,
                                                      count));
    }

    Status GetPathPoints(OUT PointF* points,
                         IN INT count) const
    {
        return SetStatus(DllExports::GdipGetPathPoints(nativePath, points,
                                                       count));
    }

    Status GetPathPoints(OUT Point* points,
                         IN INT count) const
    {
        return SetStatus(DllExports::GdipGetPathPointsI(nativePath, points,
                                                        count));
    }

    Status GetLastStatus() const
    {
        Status lastStatus = lastResult;
        lastResult = Ok;

        return lastStatus;
    }

    BOOL IsVisible(IN const PointF& point,
                   IN const Graphics* g = NULL) const
    {
        return IsVisible(point.X, point.Y, g);
    }

    BOOL IsVisible(IN REAL x,
                   IN REAL y,
                   IN const Graphics* g = NULL) const;

    BOOL IsVisible(IN const Point& point,
                   IN const Graphics* g = NULL) const
    {
        return IsVisible(point.X, point.Y, g);
    }

    BOOL IsVisible(IN INT x,
                   IN INT y,
                   IN const Graphics* g = NULL) const;

    BOOL IsOutlineVisible(IN const PointF& point,
                          IN const Pen* pen,
                          IN const Graphics* g = NULL) const
    {
        return IsOutlineVisible(point.X, point.Y, pen, g);
    }

    BOOL IsOutlineVisible(IN REAL x,
                          IN REAL y,
                          IN const Pen* pen,
                          IN const Graphics* g = NULL) const;

    BOOL IsOutlineVisible(IN const Point& point,
                          IN const Pen* pen,
                          IN const Graphics* g = NULL) const
    {
        return IsOutlineVisible(point.X, point.Y, pen, g);
    }

    BOOL IsOutlineVisible(IN INT x,
                          IN INT y,
                          IN const Pen* pen,
                          IN const Graphics* g = NULL) const;

protected:

    GraphicsPath(const GraphicsPath& path)
    {
        GpPath *clonepath = NULL;
        SetStatus(DllExports::GdipClonePath(path.nativePath, &clonepath));
        SetNativePath(clonepath);
    }

private:
    GraphicsPath& operator=(const GraphicsPath &);

protected:
    GraphicsPath(GpPath* nativePath)
    {
        lastResult = Ok;
        SetNativePath(nativePath);
    }

    VOID SetNativePath(GpPath *nativePath)
    {
        this->nativePath = nativePath;
    }

    Status SetStatus(Status status) const
    {
        if (status != Ok)
            return (lastResult = status);
        else
            return status;
    }

protected:
    GpPath* nativePath;
    mutable Status lastResult;
};

//--------------------------------------------------------------------------
// GraphisPathIterator class
//--------------------------------------------------------------------------

class GraphicsPathIterator : public GdiplusBase
{
public:

    GraphicsPathIterator(IN const GraphicsPath* path)
    {
        GpPath* nativePath = NULL;
        if(path)
            nativePath = path->nativePath;

        GpPathIterator *iter = NULL;
        lastResult = DllExports::GdipCreatePathIter(&iter, nativePath);
        SetNativeIterator(iter);
    }

    ~GraphicsPathIterator()
    {
        DllExports::GdipDeletePathIter(nativeIterator);
    }

    INT NextSubpath(OUT INT* startIndex,
                    OUT INT* endIndex,
                    OUT BOOL* isClosed)
    {
        INT resultCount;

        SetStatus(DllExports::GdipPathIterNextSubpath(nativeIterator,
            &resultCount, startIndex, endIndex, isClosed));

        return resultCount;
    }

    INT NextSubpath(OUT const GraphicsPath* path,
                    OUT BOOL* isClosed)
    {
        GpPath* nativePath = NULL;

        INT resultCount;

        if(path)
            nativePath= path->nativePath;

        SetStatus(DllExports::GdipPathIterNextSubpathPath(nativeIterator,
            &resultCount, nativePath, isClosed));

        return resultCount;
    }

    INT NextPathType(OUT BYTE* pathType,
                     OUT INT* startIndex,
                     OUT INT* endIndex)
    {
        INT resultCount;

        SetStatus(DllExports::GdipPathIterNextPathType(nativeIterator,
            &resultCount, pathType, startIndex, endIndex));

        return resultCount;
    }

    INT NextMarker(OUT INT* startIndex,
                   OUT INT* endIndex)
    {
        INT resultCount;

        SetStatus(DllExports::GdipPathIterNextMarker(nativeIterator,
            &resultCount, startIndex, endIndex));

        return resultCount;
    }

    INT NextMarker(OUT const GraphicsPath* path)
    {
        GpPath* nativePath = NULL;

        INT resultCount;

        if(path)
            nativePath= path->nativePath;

        SetStatus(DllExports::GdipPathIterNextMarkerPath(nativeIterator,
            &resultCount, nativePath));

        return resultCount;
    }

    INT GetCount() const
    {
        INT resultCount;

        SetStatus(DllExports::GdipPathIterGetCount(nativeIterator,
                                                   &resultCount));

        return resultCount;
    }

    INT GetSubpathCount() const
    {
        INT resultCount;

        SetStatus(DllExports::GdipPathIterGetSubpathCount(nativeIterator,
                                                          &resultCount));

        return resultCount;
    }

    BOOL HasCurve() const
    {
        BOOL hasCurve;

        SetStatus(DllExports::GdipPathIterHasCurve(nativeIterator, &hasCurve));

        return hasCurve;
    }

    VOID Rewind()
    {
        SetStatus(DllExports::GdipPathIterRewind(nativeIterator));
    }

    INT Enumerate(OUT PointF *points,
                  OUT BYTE *types,
                  IN INT count)
    {
        INT resultCount;

        SetStatus(DllExports::GdipPathIterEnumerate(nativeIterator,
            &resultCount, points, types, count));

        return resultCount;
    }

    INT CopyData(OUT PointF* points,
                 OUT BYTE* types,
                 IN INT startIndex,
                 IN INT endIndex)
    {
        INT resultCount;

        SetStatus(DllExports::GdipPathIterCopyData(nativeIterator,
            &resultCount, points, types, startIndex, endIndex));

        return resultCount;
    }

    Status GetLastStatus() const
    {
        Status lastStatus = lastResult;
        lastResult = Ok;

        return lastStatus;
    }

private:
    GraphicsPathIterator(const GraphicsPathIterator &);
    GraphicsPathIterator& operator=(const GraphicsPathIterator &);

protected:
    VOID SetNativeIterator(GpPathIterator *nativeIterator)
    {
        this->nativeIterator = nativeIterator;
    }

    Status SetStatus(Status status) const
    {
        if (status != Ok)
            return (lastResult = status);
        else
            return status;
    }

protected:
    GpPathIterator* nativeIterator;
    mutable Status lastResult;
};

//--------------------------------------------------------------------------
// Path Gradient Brush
//--------------------------------------------------------------------------

class PathGradientBrush : public Brush
{
public:
    friend class Pen;

    PathGradientBrush(
        IN const PointF* points,
        IN INT count,
        IN WrapMode wrapMode = WrapModeClamp)
    {
        GpPathGradient *brush = NULL;

        lastResult = DllExports::GdipCreatePathGradient(
                                        points, count,
                                        wrapMode, &brush);
        SetNativeBrush(brush);
    }

    PathGradientBrush(
        IN const Point* points,
        IN INT count,
        IN WrapMode wrapMode = WrapModeClamp)
    {
        GpPathGradient *brush = NULL;

        lastResult = DllExports::GdipCreatePathGradientI(
                                        points, count,
                                        wrapMode, &brush);

        SetNativeBrush(brush);
    }

    PathGradientBrush(
        IN const GraphicsPath* path
        )
    {
        GpPathGradient *brush = NULL;

        lastResult = DllExports::GdipCreatePathGradientFromPath(
                                        path->nativePath, &brush);
        SetNativeBrush(brush);
    }

    Status GetCenterColor(OUT Color* color) const
    {
        ARGB argb;

        if (color == NULL)
        {
            return SetStatus(InvalidParameter);
        }

        SetStatus(DllExports::GdipGetPathGradientCenterColor(
                       (GpPathGradient*) nativeBrush, &argb));

        color->SetValue(argb);

        return lastResult;
    }

    Status SetCenterColor(IN const Color& color)
    {
        SetStatus(DllExports::GdipSetPathGradientCenterColor(
                       (GpPathGradient*) nativeBrush,
                       color.GetValue()));

        return lastResult;
    }

    INT GetPointCount() const
    {
        INT count;

        SetStatus(DllExports::GdipGetPathGradientPointCount(
                       (GpPathGradient*) nativeBrush, &count));

        return count;
    }

    INT GetSurroundColorCount() const
    {
        INT count;

        SetStatus(DllExports::GdipGetPathGradientSurroundColorCount(
                       (GpPathGradient*) nativeBrush, &count));

        return count;
    }

    Status GetSurroundColors(OUT Color* colors,
                             IN OUT INT* count) const
    {
        if(colors == NULL || count == NULL)
        {
            return SetStatus(InvalidParameter);
        }

        INT count1;

        SetStatus(DllExports::GdipGetPathGradientSurroundColorCount(
                        (GpPathGradient*) nativeBrush, &count1));

        if(lastResult != Ok)
            return lastResult;

        if((*count < count1) || (count1 <= 0))
            return SetStatus(InsufficientBuffer);

        ARGB* argbs = (ARGB*) new ARGB[count1];
        if(argbs == NULL)
            return SetStatus(OutOfMemory);

        SetStatus(DllExports::GdipGetPathGradientSurroundColorsWithCount(
                    (GpPathGradient*)nativeBrush, argbs, &count1));

        if(lastResult == Ok)
        {
            for(INT i = 0; i < count1; i++)
            {
                colors[i].SetValue(argbs[i]);
            }
            *count = count1;
        }

        delete [] argbs;
        return lastResult;
    }

    Status SetSurroundColors(IN const Color* colors,
                             IN OUT INT* count)
    {
        if(colors == NULL || count == NULL)
        {
            return SetStatus(InvalidParameter);
        }

        INT count1 = GetPointCount();

        if((*count > count1) || (count1 <= 0))
            return SetStatus(InvalidParameter);

        count1 = *count;

        ARGB* argbs = (ARGB*) new ARGB[count1];
        if(argbs == NULL)
            return SetStatus(OutOfMemory);

        for(INT i = 0; i < count1; i++)
        {
            argbs[i] = colors[i].GetValue();
        }

        SetStatus(DllExports::GdipSetPathGradientSurroundColorsWithCount(
                    (GpPathGradient*)nativeBrush, argbs, &count1));

        if(lastResult == Ok)
            *count = count1;

        delete [] argbs;

        return lastResult;
    }

    Status GetGraphicsPath(OUT GraphicsPath* path) const
    {
        if(path == NULL)
            return SetStatus(InvalidParameter);

        return SetStatus(DllExports::GdipGetPathGradientPath(
                    (GpPathGradient*)nativeBrush, path->nativePath));
    }

    Status SetGraphicsPath(IN const GraphicsPath* path)
    {
        if(path == NULL)
            return SetStatus(InvalidParameter);

        return SetStatus(DllExports::GdipSetPathGradientPath(
                    (GpPathGradient*)nativeBrush, path->nativePath));
    }

    Status GetCenterPoint(OUT PointF* point) const
    {
        return SetStatus(DllExports::GdipGetPathGradientCenterPoint(
                                (GpPathGradient*)nativeBrush,
                                point));
    }

    Status GetCenterPoint(OUT Point* point) const
    {
        return SetStatus(DllExports::GdipGetPathGradientCenterPointI(
                                (GpPathGradient*)nativeBrush,
                                point));
    }

    Status SetCenterPoint(IN const PointF& point)
    {
        return SetStatus(DllExports::GdipSetPathGradientCenterPoint(
                                (GpPathGradient*)nativeBrush,
                                &point));
    }

    Status SetCenterPoint(IN const Point& point)
    {
        return SetStatus(DllExports::GdipSetPathGradientCenterPointI(
                                (GpPathGradient*)nativeBrush,
                                &point));
    }

    Status GetRectangle(OUT RectF* rect) const
    {
        return SetStatus(DllExports::GdipGetPathGradientRect(
                            (GpPathGradient*)nativeBrush, rect));
    }

    Status GetRectangle(OUT Rect* rect) const
    {
        return SetStatus(DllExports::GdipGetPathGradientRectI(
                            (GpPathGradient*)nativeBrush, rect));
    }

    Status SetGammaCorrection(IN BOOL useGammaCorrection)
    {
        return SetStatus(DllExports::GdipSetPathGradientGammaCorrection(
            (GpPathGradient*)nativeBrush, useGammaCorrection));
    }

    BOOL GetGammaCorrection() const
    {
        BOOL useGammaCorrection;

        SetStatus(DllExports::GdipGetPathGradientGammaCorrection(
            (GpPathGradient*)nativeBrush, &useGammaCorrection));

        return useGammaCorrection;
    }

    INT GetBlendCount() const
    {
       INT count = 0;

       SetStatus(DllExports::GdipGetPathGradientBlendCount(
                           (GpPathGradient*) nativeBrush, &count));

       return count;
    }

    Status GetBlend(OUT REAL* blendFactors,
                    OUT REAL* blendPositions,
                    IN INT count) const
    {
        return SetStatus(DllExports::GdipGetPathGradientBlend(
                            (GpPathGradient*)nativeBrush,
                            blendFactors, blendPositions, count));
    }

    Status SetBlend(IN const REAL* blendFactors,
                    IN const REAL* blendPositions,
                    IN INT count)
    {
        return SetStatus(DllExports::GdipSetPathGradientBlend(
                            (GpPathGradient*)nativeBrush,
                            blendFactors, blendPositions, count));
    }

    INT GetInterpolationColorCount() const
    {
       INT count = 0;

       SetStatus(DllExports::GdipGetPathGradientPresetBlendCount(
                        (GpPathGradient*) nativeBrush, &count));

       return count;
    }

    Status SetInterpolationColors(IN const Color* presetColors,
                                  IN const REAL* blendPositions,
                                  IN INT count)
    {
        if ((count <= 0) || !presetColors)
        {
            return SetStatus(InvalidParameter);
        }

        ARGB* argbs = (ARGB*) new ARGB[count];
        if(argbs)
        {
            for(INT i = 0; i < count; i++)
            {
                argbs[i] = presetColors[i].GetValue();
            }

            Status status = SetStatus(DllExports::
                               GdipSetPathGradientPresetBlend(
                                    (GpPathGradient*) nativeBrush,
                                    argbs,
                                    blendPositions,
                                    count));
            delete[] argbs;
            return status;
        }
        else
        {
            return SetStatus(OutOfMemory);
        }
    }

    Status GetInterpolationColors(OUT Color* presetColors,
                                  OUT REAL* blendPositions,
                                  IN INT count) const
    {
        if ((count <= 0) || !presetColors)
        {
            return SetStatus(InvalidParameter);
        }

        ARGB* argbs = (ARGB*) new ARGB[count];

        if (!argbs)
        {
            return SetStatus(OutOfMemory);
        }

        GpStatus status = SetStatus(DllExports::GdipGetPathGradientPresetBlend(
                                (GpPathGradient*)nativeBrush,
                                argbs,
                                blendPositions,
                                count));

        for(INT i = 0; i < count; i++)
        {
            presetColors[i] = Color(argbs[i]);
        }
        delete [] argbs;

        return status;
    }

    Status SetBlendBellShape(IN REAL focus,
                             IN REAL scale = 1.0)
    {
        return SetStatus(DllExports::GdipSetPathGradientSigmaBlend(
                            (GpPathGradient*)nativeBrush, focus, scale));
    }

    Status SetBlendTriangularShape(
        IN REAL focus,
        IN REAL scale = 1.0
    )
    {
        return SetStatus(DllExports::GdipSetPathGradientLinearBlend(
                            (GpPathGradient*)nativeBrush, focus, scale));
    }

    Status GetTransform(OUT Matrix *matrix) const
    {
        return SetStatus(DllExports::GdipGetPathGradientTransform(
                            (GpPathGradient*) nativeBrush,
                            matrix->nativeMatrix));
    }

    Status SetTransform(IN const Matrix* matrix)
    {
        return SetStatus(DllExports::GdipSetPathGradientTransform(
                            (GpPathGradient*) nativeBrush,
                            matrix->nativeMatrix));
    }

    Status ResetTransform()
    {
        return SetStatus(DllExports::GdipResetPathGradientTransform(
                            (GpPathGradient*)nativeBrush));
    }

    Status MultiplyTransform(IN const Matrix* matrix,
                             IN MatrixOrder order = MatrixOrderPrepend)
    {
        return SetStatus(DllExports::GdipMultiplyPathGradientTransform(
                            (GpPathGradient*)nativeBrush,
                            matrix->nativeMatrix,
                            order));
    }

    Status TranslateTransform(IN REAL dx,
                              IN REAL dy,
                              IN MatrixOrder order = MatrixOrderPrepend)
    {
        return SetStatus(DllExports::GdipTranslatePathGradientTransform(
                            (GpPathGradient*)nativeBrush,
                            dx, dy, order));
    }

    Status ScaleTransform(IN REAL sx,
                          IN REAL sy,
                          IN MatrixOrder order = MatrixOrderPrepend)
    {
        return SetStatus(DllExports::GdipScalePathGradientTransform(
                            (GpPathGradient*)nativeBrush,
                            sx, sy, order));
    }

    Status RotateTransform(IN REAL angle,
                           IN MatrixOrder order = MatrixOrderPrepend)
    {
        return SetStatus(DllExports::GdipRotatePathGradientTransform(
                            (GpPathGradient*)nativeBrush,
                            angle, order));
    }

    Status GetFocusScales(OUT REAL* xScale,
                          OUT REAL* yScale) const
    {
        return SetStatus(DllExports::GdipGetPathGradientFocusScales(
                            (GpPathGradient*) nativeBrush, xScale, yScale));
    }

    Status SetFocusScales(IN REAL xScale,
                          IN REAL yScale)
    {
        return SetStatus(DllExports::GdipSetPathGradientFocusScales(
                            (GpPathGradient*) nativeBrush, xScale, yScale));
    }

    WrapMode GetWrapMode() const
    {
        WrapMode wrapMode;

        SetStatus(DllExports::GdipGetPathGradientWrapMode(
                     (GpPathGradient*) nativeBrush, &wrapMode));

        return wrapMode;
    }

    Status SetWrapMode(IN WrapMode wrapMode)
    {
        return SetStatus(DllExports::GdipSetPathGradientWrapMode(
                            (GpPathGradient*) nativeBrush, wrapMode));
    }

private:
    PathGradientBrush(const PathGradientBrush &);
    PathGradientBrush& operator=(const PathGradientBrush &);

protected:

    PathGradientBrush()
    {
    }
};

#endif // !_GRAPHICSPATH_HPP


text:
<?php

namespace Mobytes\Landpage\Publication\Command;

use Laracasts\Commander\CommandHandler;
use Mobytes\Landpage\Publication\Repo\PublicationInterface;

/**
 * Class PublicationCommandHandler
 * @package Mobytes\Landpage\Publication\Command
 */
class PublicationCommandHandler implements CommandHandler
{
    /**
     * @autor eveR Vásquez
     * @link http://evervasquez.me
     * @var
     */
    private $repository;

    /**
     * PublicationCommandHandler constructor.
     * @param $repository
     */
    public function __construct(PublicationInterface $repository)
    {
        $this->repository = $repository;
    }

    /**
     * Handle the command
     *
     * @param $command
     * @return mixed
     */
    public function handle($command)
    {
        $attributes = (array) $command;
        $this->repository->save($attributes);
    }

}


text:
SolView
=======

Node.js Website Framework written in CoffeeScript.


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_pressed="true">
        <shape >
            <corners android:radius="2dp"/>
            <padding android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp"
                />
            <solid android:color="#a52a2a"/>
        </shape>
    </item>
    <item >
        <shape >
            <corners android:radius="2dp"/>
            <padding android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp"
                />
            <solid android:color="#d84a4b"/>
        </shape>

    </item>

</selector>


text:
namespace SquishIt.Framework.Invalidation
{
    public interface ICacheInvalidationStrategy
    {
        string GetOutputFileLocation(string outputFile, string hash);
        string GetOutputWebPath(string renderToPath, string hashKeyName, string hash);
    }
}


text:
var DTraceProvider;

function DTraceProviderStub() {}
DTraceProviderStub.prototype.addProbe = function() {
    return {
        'fire': function() { }
    };
};
DTraceProviderStub.prototype.enable = function() {};
DTraceProviderStub.prototype.fire = function() {};

var builds = ['Release', 'default', 'Debug'];

for (var i in builds) {
    try {
        var binding = require('./build/' + builds[i] + '/DTraceProviderBindings');
        DTraceProvider = binding.DTraceProvider;
        break;
    } catch (e) {
        // if the platform looks like it _should_ have DTrace
        // available, log a failure to load the bindings.
        if (process.platform == 'darwin' ||
            process.platform == 'solaris' ||
            process.platform == 'freebsd') {
            console.log(e);
        }
    }
}

if (!DTraceProvider) {
    DTraceProvider = DTraceProviderStub;
}

exports.DTraceProvider = DTraceProvider;
exports.createDTraceProvider = function(name, module) {
    if (arguments.length == 2)
        return (new DTraceProvider(name, module));
    return (new DTraceProvider(name));
};


text:
Karma runs on Node.js and is available as an NPM package. It can be installed through the Node Package Manager (npm) by running:

	npm install karma --save-dev

If you are already using Karma in your project, skip to **Configuring Karma for Turbo**.

If you do not already have Karma installed in your project, see **Installing Karma**.

#### Installing Karma

This section will outline the recommended Karma installation for Turbo. The instructions here closely mimic those recommended by the Karma project for general installations.

Start by installing Karma locally in your project's root directory:

	npm install karma --save-dev

If you are managing your packages through a **packages.json** file, add Karma to the `devDependencies` section.

```json
{
	"devDependencies": {
		"karma": ">=0.10"
	}
}
```

We highly recommend also installing the **karma-cli** package. Without it, you must type the full path to Karma (usually `"./node_modules/karma/bin/karma"` to run Karma. By doing a global install of **karma-cli**, you can simply type `karma` from any location and it will always run the local version.

**Note**: If you are using any testing frameworks, such as Jasmine or QUnit, these should also be installed at this time.

#### Configuring Karma for Turbo

After Karma is installed, it must be configured to use Turbo for browser launches.

First, install the **karma-webdriver-launcher** package through npm:

	npm install karma-webdriver-launcher

or by adding the **karma-webdriver-launcher** to your project's **package.json** file:

```json
{
	"devDependencies": {
		"karma": ">=0.10",
		"karma-webdriver-launcher": ">=0.2.0"
	}
}
```

In your project's root directory, open the **karma.conf.js** file. If it doesn't already exist, run the command `karma init karma.conf.js` in your project's root directory. Karma will ask a couple of questions about your particular configuration and generate a new config file based on your answers.

In your karma.conf.js file, add a **webDriverConfig** variable within the **module.exports** scope. This variable will specify the hostname and port of the Turbo hub.

```javascript
module.exports = function(karma) {
	var webDriverConfig = {
		hostname: "localhost",
		port: 4444
	}
}
```

In your configuration object, add a new option: **customLaunchers**. Beneath this option, add variables for each browser you want to test with.

```javascript
module.exports = function(karma) {
	var webDriverConfig = {
		hostname: "localhost",
		port: 4444
	}

	karma.set({
		...
		customLaunchers: {
			'Firefox30': {
				base: 'WebDriver',
				browserName: 'firefox',
				version: 30
			},
			'Chrome32': {
				base: 'WebDriver',
				browserName: 'chrome',
				version: 32
			}
		}
		...
	})
}
```

Finally, add each of these browsers to the **browsers** option in your configuration object.

```javascript
module.exports = function(karma) {
	var webDriverConfig = {
		hostname: "localhost",
		port: 4444
	}

	karma.set({
		...
		customLaunchers: {
			'Firefox30': {
				base: 'WebDriver',
				config: webDriverConfig,
				browserName: 'firefox',
				version: 30
			},
			'Chrome32': {
				base: 'WebDriver',
				config: webDriverConfig,
				browserName: 'chrome',
				version: 32
			}
		},
		...
		browsers: ['Firefox30','Chrome32']
	})
}
```

Note that each launcher object has a similar structure:

```javascript
'LAUNCHER-NAME': {
	base: 'WebDriver',
	config: 'webDriverConfig',
	browserName: 'NAME OF BROWSER',
	version: VERSION
}
```

When adding additional launchers to your test, follow this pattern -- always specifying "base" and "config" as **WebDriver** and **webDriverConfig**, respectively.

#### Run Your Karma Tests

When you are ready to test, run the command `karma start karma.conf.js` from your project's root directory.


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

package distsqlrun

import (
	"fmt"
	"io"
	"net"
	"sync"
	"testing"
	"time"

	"github.com/pkg/errors"
	"golang.org/x/net/context"

	"github.com/cockroachdb/cockroach/pkg/base"
	"github.com/cockroachdb/cockroach/pkg/rpc"
	"github.com/cockroachdb/cockroach/pkg/sql/parser"
	"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
	"github.com/cockroachdb/cockroach/pkg/testutils"
	"github.com/cockroachdb/cockroach/pkg/util"
	"github.com/cockroachdb/cockroach/pkg/util/hlc"
	"github.com/cockroachdb/cockroach/pkg/util/leaktest"
	"github.com/cockroachdb/cockroach/pkg/util/log"
	"github.com/cockroachdb/cockroach/pkg/util/netutil"
	"github.com/cockroachdb/cockroach/pkg/util/stop"
	"github.com/cockroachdb/cockroach/pkg/util/uuid"
)

func TestOutbox(t *testing.T) {
	defer leaktest.AfterTest(t)()

	// Create a mock server that the outbox will connect and push rows to.
	stopper := stop.NewStopper()
	defer stopper.Stop(context.TODO())
	mockServer, addr, err := startMockDistSQLServer(stopper)
	if err != nil {
		t.Fatal(err)
	}

	flowCtx := FlowCtx{
		evalCtx: parser.EvalContext{},
		rpcCtx:  newInsecureRPCContext(stopper),
	}
	flowID := FlowID{uuid.MakeV4()}
	streamID := StreamID(42)
	outbox := newOutbox(&flowCtx, addr.String(), flowID, streamID)
	var outboxWG sync.WaitGroup
	outboxWG.Add(1)
	// Start the outbox. This should cause the stream to connect, even though
	// we're not sending any rows.
	outbox.start(context.TODO(), &outboxWG)

	// Start a producer. It will send one row 0, then send rows -1 until a drain
	// request is observed, then send row 2 and some metadata.
	producerC := make(chan error)
	go func() {
		producerC <- func() error {
			row := sqlbase.EncDatumRow{
				sqlbase.DatumToEncDatum(
					sqlbase.ColumnType{Kind: sqlbase.ColumnType_INT},
					parser.NewDInt(parser.DInt(0))),
			}
			if consumerStatus := outbox.Push(row, ProducerMetadata{}); consumerStatus != NeedMoreRows {
				return errors.Errorf("expected status: %d, got: %d", NeedMoreRows, consumerStatus)
			}

			// Send rows until the drain request is observed.
			for {
				row = sqlbase.EncDatumRow{
					sqlbase.DatumToEncDatum(
						sqlbase.ColumnType{Kind: sqlbase.ColumnType_INT},
						parser.NewDInt(parser.DInt(-1))),
				}
				consumerStatus := outbox.Push(row, ProducerMetadata{})
				if consumerStatus == DrainRequested {
					break
				}
				if consumerStatus == ConsumerClosed {
					return errors.Errorf("consumer closed prematurely")
				}
			}

			// Now send another row that the outbox will discard.
			row = sqlbase.EncDatumRow{
				sqlbase.DatumToEncDatum(
					sqlbase.ColumnType{Kind: sqlbase.ColumnType_INT},
					parser.NewDInt(parser.DInt(2))),
			}
			if consumerStatus := outbox.Push(row, ProducerMetadata{}); consumerStatus != DrainRequested {
				return errors.Errorf("expected status: %d, got: %d", NeedMoreRows, consumerStatus)
			}

			// Send some metadata.
			outbox.Push(nil /* row */, ProducerMetadata{Err: errors.Errorf("meta 0")})
			outbox.Push(nil /* row */, ProducerMetadata{Err: errors.Errorf("meta 1")})
			// Send the termination signal.
			outbox.ProducerDone()

			return nil
		}()
	}()

	// Wait for the outbox to connect the stream.
	streamNotification := <-mockServer.inboundStreams
	serverStream := streamNotification.stream

	// Consume everything that the outbox sends on the stream.
	var decoder StreamDecoder
	var rows sqlbase.EncDatumRows
	var metas []ProducerMetadata
	drainSignalSent := false
	for {
		msg, err := serverStream.Recv()
		if err != nil {
			if err == io.EOF {
				break
			}
			t.Fatal(err)
		}
		err = decoder.AddMessage(msg)
		if err != nil {
			t.Fatal(err)
		}
		rows, metas = testGetDecodedRows(t, &decoder, rows, metas)
		// Eliminate the "-1" rows, that were sent before the producer found out
		// about the draining.
		last := -1
		for i := 0; i < len(rows); i++ {
			if rows[i].String() != "[-1]" {
				last = i
				continue
			}
			for j := i; j < len(rows); j++ {
				if rows[j].String() == "[-1]" {
					continue
				}
				rows[i] = rows[j]
				i = j
				last = j
				break
			}
		}
		rows = rows[0 : last+1]

		// After we receive one row, we're going to ask the producer to drain.
		if !drainSignalSent && len(rows) > 0 {
			sig := ConsumerSignal{DrainRequest: &DrainRequest{}}
			if err := serverStream.Send(&sig); err != nil {
				t.Fatal(err)
			}
			drainSignalSent = true
		}
	}
	if err := <-producerC; err != nil {
		t.Fatalf("%+v", err)
	}

	if len(metas) != 2 {
		t.Fatalf("expected 2 metadata records, got: %d", len(metas))
	}
	for i, m := range metas {
		expectedStr := fmt.Sprintf("meta %d", i)
		if m.Err.Error() != expectedStr {
			t.Fatalf("expected: %q, got: %q", expectedStr, m.Err.Error())
		}
	}
	str := rows.String()
	expected := "[[0]]"
	if str != expected {
		t.Errorf("invalid results: %s, expected %s'", str, expected)
	}

	// The outbox should shut down since the producer closed.
	outboxWG.Wait()
	// Signal the server to shut down the stream.
	streamNotification.donec <- nil
}

// Test that an outbox connects its stream as soon as possible (i.e. before
// receiving any rows). This is important, since there's a timeout on waiting on
// the server-side for the streams to be connected.
func TestOutboxInitializesStreamBeforeRecevingAnyRows(t *testing.T) {
	defer leaktest.AfterTest(t)()

	stopper := stop.NewStopper()
	defer stopper.Stop(context.TODO())
	mockServer, addr, err := startMockDistSQLServer(stopper)
	if err != nil {
		t.Fatal(err)
	}

	flowCtx := FlowCtx{
		evalCtx: parser.EvalContext{},
		rpcCtx:  newInsecureRPCContext(stopper),
	}
	flowID := FlowID{uuid.MakeV4()}
	streamID := StreamID(42)
	outbox := newOutbox(&flowCtx, addr.String(), flowID, streamID)

	var outboxWG sync.WaitGroup
	outboxWG.Add(1)
	// Start the outbox. This should cause the stream to connect, even though
	// we're not sending any rows.
	outbox.start(context.TODO(), &outboxWG)

	streamNotification := <-mockServer.inboundStreams
	serverStream := streamNotification.stream
	producerMsg, err := serverStream.Recv()
	if err != nil {
		t.Fatal(err)
	}
	if producerMsg.Header == nil {
		t.Fatal("missing header")
	}
	if producerMsg.Header.FlowID != flowID || producerMsg.Header.StreamID != streamID {
		t.Fatalf("wrong header: %v", producerMsg)
	}

	// Signal the server to shut down the stream. This should also prompt the
	// outbox (the client) to terminate its loop.
	streamNotification.donec <- nil
	outboxWG.Wait()
}

// Test that the outbox responds to the consumer shutting down in an unexpected
// way by closing.
func TestOutboxClosesWhenConsumerCloses(t *testing.T) {
	defer leaktest.AfterTest(t)()

	testCases := []struct {
		// When set, the outbox will establish the stream with a FlowRpc call. When
		// not set, the consumer will establish the stream with RunSyncFlow.
		outboxIsClient bool
		// Only takes effect with outboxIsClient is set. When set, the consumer
		// (i.e. the server) returns an error from RunSyncFlow. This error will be
		// translated into a grpc error received by the client (i.e. the outbox) in
		// its stream.Recv()) call. Otherwise, the client doesn't return an error
		// (and the outbox should receive io.EOF).
		serverReturnsError bool
	}{
		{outboxIsClient: true, serverReturnsError: false},
		{outboxIsClient: true, serverReturnsError: true},
		{outboxIsClient: false},
	}
	for _, tc := range testCases {
		t.Run("", func(t *testing.T) {
			stopper := stop.NewStopper()
			defer stopper.Stop(context.TODO())
			mockServer, addr, err := startMockDistSQLServer(stopper)
			if err != nil {
				t.Fatal(err)
			}

			flowCtx := FlowCtx{
				evalCtx: parser.EvalContext{},
				rpcCtx:  newInsecureRPCContext(stopper),
			}
			flowID := FlowID{uuid.MakeV4()}
			streamID := StreamID(42)
			var outbox *outbox
			var wg sync.WaitGroup
			wg.Add(1)
			var expectedErr error
			consumerReceivedMsg := make(chan struct{})
			if tc.outboxIsClient {
				outbox = newOutbox(&flowCtx, addr.String(), flowID, streamID)
				outbox.start(context.TODO(), &wg)

				// Wait for the outbox to connect the stream.
				streamNotification := <-mockServer.inboundStreams
				// Wait for the consumer to receive the header message that the outbox
				// sends on start. If we don't wait, the consumer returning from the
				// FlowStream() RPC races with the outbox sending the header msg and the
				// send might get an io.EOF error.
				if _, err := streamNotification.stream.Recv(); err != nil {
					t.Errorf("expected err: %q, got %v", expectedErr, err)
				}

				// Have the server return from the FlowStream call. This should prompt the
				// outbox to finish.
				if tc.serverReturnsError {
					expectedErr = errors.Errorf("FlowStream server error")
				} else {
					expectedErr = nil
				}
				streamNotification.donec <- expectedErr
			} else {
				// We're going to perform a RunSyncFlow call and then have the client
				// cancel the call's context.
				conn, err := flowCtx.rpcCtx.GRPCDial(addr.String())
				if err != nil {
					t.Fatal(err)
				}
				client := NewDistSQLClient(conn)
				var outStream DistSQL_RunSyncFlowClient
				ctx, cancel := context.WithCancel(context.Background())
				expectedErr = errors.Errorf("context canceled")
				go func() {
					outStream, err = client.RunSyncFlow(ctx)
					if err != nil {
						t.Error(err)
					}
					// Check that Recv() receives an error once the context is cancelled.
					// Perhaps this is not terribly important to test; one can argue that
					// the client should either not be Recv()ing after it cancelled the
					// ctx or that it otherwise should otherwise be aware of the
					// cancellation when processing the results, but I've put it here
					// because bidi streams are confusing and this provides some
					// information.
					for {
						_, err := outStream.Recv()
						if err == nil {
							consumerReceivedMsg <- struct{}{}
							continue
						}
						if !testutils.IsError(err, expectedErr.Error()) {
							t.Errorf("expected err: %q, got %v", expectedErr, err)
						}
						break
					}
				}()
				// Wait for the consumer to connect.
				call := <-mockServer.runSyncFlowCalls
				outbox = newOutboxSyncFlowStream(call.stream)
				// In a RunSyncFlow call, the outbox runs under the call's context.
				outbox.start(call.stream.Context(), &wg)
				// Wait for the consumer to receive the header message that the outbox
				// sends on start. If we don't wait, the context cancellation races with
				// the outbox sending the header msg; if the cancellation makes it to
				// the outbox right as the outbox is trying to send the header, the
				// outbox might finish with a "the stream has been done" error instead
				// of "context canceled".
				<-consumerReceivedMsg
				// cancel the RPC's context. This is how a streaming RPC client can inform
				// the server that it's done. We expect the outbox to finish.
				cancel()
				defer func() {
					// Allow the RunSyncFlow RPC to finish.
					call.donec <- nil
				}()
			}

			wg.Wait()
			if expectedErr == nil {
				if outbox.err != nil {
					t.Fatalf("unexpected outbox.err: %s", outbox.err)
				}
			} else {
				// We use error string comparison because we actually expect a grpc
				// error wrapping the expected error.
				if !testutils.IsError(outbox.err, expectedErr.Error()) {
					t.Fatalf("expected err: %q, got %v", expectedErr, outbox.err)
				}
			}
		})
	}
}

// startMockDistSQLServer starts a MockDistSQLServer and returns the address on
// which it's listening.
func startMockDistSQLServer(stopper *stop.Stopper) (*MockDistSQLServer, net.Addr, error) {
	rpcContext := newInsecureRPCContext(stopper)
	server := rpc.NewServer(rpcContext)
	mock := newMockDistSQLServer()
	RegisterDistSQLServer(server, mock)
	ln, err := netutil.ListenAndServeGRPC(stopper, server, util.IsolatedTestAddr)
	if err != nil {
		return nil, nil, err
	}
	return mock, ln.Addr(), nil
}

func newInsecureRPCContext(stopper *stop.Stopper) *rpc.Context {
	return rpc.NewContext(
		log.AmbientContext{},
		&base.Config{Insecure: true},
		hlc.NewClock(hlc.UnixNano, time.Nanosecond),
		stopper,
	)
}

// MockDistSQLServer implements the DistSQLServer (gRPC) interface and allows
// clients to control the inbound streams.
type MockDistSQLServer struct {
	inboundStreams   chan InboundStreamNotification
	runSyncFlowCalls chan RunSyncFlowCall
}

// InboundStreamNotification is the MockDistSQLServer's way to tell its clients
// that a new gRPC call has arrived and thus a stream has arrived. The rpc
// handler is blocked until donec is signaled.
type InboundStreamNotification struct {
	stream DistSQL_FlowStreamServer
	donec  chan<- error
}

type RunSyncFlowCall struct {
	stream DistSQL_RunSyncFlowServer
	donec  chan<- error
}

// MockDistSQLServer implements the DistSQLServer interface.
var _ DistSQLServer = &MockDistSQLServer{}

func newMockDistSQLServer() *MockDistSQLServer {
	return &MockDistSQLServer{
		inboundStreams:   make(chan InboundStreamNotification),
		runSyncFlowCalls: make(chan RunSyncFlowCall),
	}
}

// RunSyncFlow is part of the DistSQLServer interface.
func (ds *MockDistSQLServer) RunSyncFlow(stream DistSQL_RunSyncFlowServer) error {
	donec := make(chan error)
	ds.runSyncFlowCalls <- RunSyncFlowCall{stream: stream, donec: donec}
	return <-donec
}

// SetupFlow is part of the DistSQLServer interface.
func (ds *MockDistSQLServer) SetupFlow(
	_ context.Context, req *SetupFlowRequest,
) (*SimpleResponse, error) {
	return nil, nil
}

// FlowStream is part of the DistSQLServer interface.
func (ds *MockDistSQLServer) FlowStream(stream DistSQL_FlowStreamServer) error {
	donec := make(chan error)
	ds.inboundStreams <- InboundStreamNotification{stream: stream, donec: donec}
	return <-donec
}


text:
@implementation KWFailure

#pragma mark - Initializing

- (id)initWithCallSite:(KWCallSite *)aCallSite message:(NSString *)aMessage {
    self = [super init];
    if (self) {
        _callSite = aCallSite;
        _message = [aMessage copy];
    }

    return self;
}

- (id)initWithCallSite:(KWCallSite *)aCallSite format:(NSString *)format, ... {
    va_list argumentList;
    va_start(argumentList, format);
    NSString *aMessage = [[NSString alloc] initWithFormat:format arguments:argumentList];
    va_end(argumentList);
    return [self initWithCallSite:aCallSite message:aMessage];
}

+ (id)failureWithCallSite:(KWCallSite *)aCallSite message:(NSString *)aMessage {
    return [[self alloc] initWithCallSite:aCallSite message:aMessage];
}

+ (id)failureWithCallSite:(KWCallSite *)aCallSite format:(NSString *)format, ... {
    va_list argumentList;
    va_start(argumentList, format);
    NSString *message = [[NSString alloc] initWithFormat:format arguments:argumentList];
    va_end(argumentList);
    return [self failureWithCallSite:aCallSite message:message];
}

@end