text:
require "jieba_rb/version"
require "jieba"
module JiebaRb
  abs = File.expand_path File.dirname(__FILE__)
  EXT_BASE = "#{abs}/../ext/cppjieba/"
  DEFAULT_JIEBA_DICT = EXT_BASE + "dict/jieba.dict.utf8";
  DEFAULT_HMM_DICT = EXT_BASE + "dict/hmm_model.utf8";
  DEFAULT_USER_DICT = EXT_BASE + "dict/user.dict.utf8";

  class Segment
    private :_init
    def initialize opts = {}
      valid_modes = [:mix, :hmm, :mp]
      if mode = opts[:mode]
        raise "Mode must be one of :mix :hmm :mp" unless valid_modes.include? mode
      else
        mode = :mix #default
      end

      jieba_dict = opts[:jieba_dict] || DEFAULT_JIEBA_DICT
      hmm_dict = opts[:hmm_dict] || DEFAULT_HMM_DICT
      user_dict = opts[:user_dict] || ""
      user_dict = DEFAULT_USER_DICT if user_dict == :default

      _init mode, jieba_dict, hmm_dict, user_dict
    end
  end

  class Keyword
    DEFAULT_IDF = EXT_BASE + "dict/idf.utf8"
    DEFAULT_STOP_WORDS = EXT_BASE + "dict/stop_words.utf8"

    private :_init

    def initialize opts = {}
      valid_modes = [:tf_idf]
      if mode = opts[:mode]
        raise "Mode must be one of :tf_idf" unless valid_modes.include? mode
      else
        mode = :tf_idf #default
      end

      jieba_dict = opts[:jieba_dict] || DEFAULT_JIEBA_DICT
      hmm_dict = opts[:hmm_dict] || DEFAULT_HMM_DICT
      idf_path = opts[:idf] || DEFAULT_IDF
      stop_words_path = opts[:stop_words] || DEFAULT_STOP_WORDS

      user_dict = opts[:user_dict] || ""
      user_dict = DEFAULT_USER_DICT if user_dict == :default

      _init mode, jieba_dict, hmm_dict, idf_path, stop_words_path, user_dict
    end
  end

  class Tagging
    private :_init
    def initialize opts = {}
      jieba_dict = opts[:jieba_dict] || DEFAULT_JIEBA_DICT
      hmm_dict = opts[:hmm_dict] || DEFAULT_HMM_DICT
      user_dict = opts[:user_dict] || ""
      user_dict = DEFAULT_USER_DICT if user_dict == :default

      _init jieba_dict, hmm_dict, user_dict
    end
  end
end


text:
<?php

  /* void database connection */
  $dbConnect = 'no';
  /* avoid loading includes.lst in app folders */
  $cfgAvoidIncludesLst = 'yes';

  /* load yeapf directly */
  require_once "includes/yeapf.functions.php";

  function grantDirectory($dirName)
  {
    if (!is_dir($dirName)) {
      echo "Granting '$dirName' ... ";
      $ret=grantDir($dirName);
      echo ($ret?'Ok':'Error');
      echo "\n";
      if (!$ret) {
        echo "'$dirName' cannot be granted\n";
        exit(10);
      }
    }
  }

  function copyFile($srcFileName, $tgtFolder, $addHeader = false)
  {
    if (file_exists($srcFileName)) {
      grantDirectory($tgtFolder);
      $auxFile = _file($srcFileName);
      if ($addHeader) {
        $auxFile = "/* YeAPF 0.8.64-7 built on 2020-03-20 13:04 (-3 DST) Copyright (C) 2004-2020 Esteban Daniel Dortta - dortta@yahoo.com - MIT License */\n".$auxFile;
      }
      $tgtFileName=basename($srcFileName);
      if (file_put_contents("$tgtFolder/$tgtFileName", $auxFile))
        echo "\t$srcFileName: OK\n";
      else
        echo "\t$srcFileName: Error Writting '$tgtFolder'!\n";
    } else {
      if (file_exists("$tgtFolder/$srcFileName"))
        if (!unlink("$tgtFolder/$srcFileName"))
          echo "Error file '$tgtFolder/$srcFileName' cannot be deleted\n";
    }
  }

  function copyMobileFiles($targetFolder)
  {
    grantDirectory($targetFolder);
    copyFile("app-src/js/ysandboxifc.js",                           $targetFolder);
    copyFile("app-src/js/ystorage.js",                              $targetFolder);
    copyFile("app-src/js/yifc.js",                                  $targetFolder);
    copyFile("app-src/js/ycomm-worker.js",                          $targetFolder);
    copyFile("app-src/js/ystorage-indexedDB-interface.js",          $targetFolder);
    copyFile("app-src/js/ystorage-indexedDB-slave.js",              $targetFolder);

    copyFile("app-src/js/min/ysandboxifc.min.js",                   $targetFolder, true);
    copyFile("app-src/js/min/ystorage.min.js",                      $targetFolder, true);
    copyFile("app-src/js/min/yifc.min.js",                          $targetFolder, true);
    copyFile("app-src/js/min/ycomm-worker.min.js",                  $targetFolder, true);
    copyFile("app-src/js/min/ystorage-indexedDB-interface.min.js",  $targetFolder, true);
    copyFile("app-src/js/min/ystorage-indexedDB-slave.min.js",      $targetFolder, true);
  }

  function copyYeapfAppFiles($targetFolder)
  {
    copyFile("app-src/js/min/yapp.min.js",      $targetFolder, true);
  }

  function putVersion($targetFilename, $fileContent)
  {
    echo "Writting $targetFilename ... ";
    if (file_exists($targetFilename))
      if (!unlink($targetFilename)) {
        echo "Error: file cannot be deleted\n";
        exit(10);
      }
    if ($fileContent>'')
      if (!file_put_contents($targetFilename, trim($fileContent))) {
        echo "Error: file '$targetFilename' cannot be written\n";
        exit(10);
      }
    echo "OK\n";
    return true;
  }

  echo "Working at ".getcwd()."\n";

  $temp = $argv[1];
  if (!file_exists($temp)) {
    echo "Error: '$temp' file not found";
    exit(10);
  }
  echo "Expanded version source: $temp\n";
  $yeapfJS = join(" ", file($temp));

  $yeapf_minJS='';
  $minJS = $argv[2];

  if (file_exists($minJS)) {
    echo "Minified version source: $minJS\n";
    $yeapf_minJS = join("", file($minJS));
    $yeapf_minJS = "/* YeAPF 0.8.64-7 built on 2020-03-20 13:04 (-3 DST) Copyright (C) 2004-2020 Esteban Daniel Dortta - dortta@yahoo.com - MIT License */\n".$yeapf_minJS;
  }

  grantDirectory("skel/chromeApp/js");
  grantDirectory("skel/MoSyncApp/LocalFiles/js");
  grantDirectory("skel/electron/js");
  grantDirectory("skel/webApp/js");
  grantDirectory("skel/webApp/templates/bs3/js");
  grantDirectory("skel/webApp/templates/bs4/js");
  grantDirectory("skel/webApp/templates/milligram-1.3/js");
  grantDirectory("skel/webApp/templates/pure/js");
  grantDirectory("skel/webApp/templates/skeleton/js");
  grantDirectory("skel/webApp/templates/materialize/js");
  grantDirectory("skel/webSocket");
  grantDirectory("skel/service");
  grantDirectory("skel/cli");
  grantDirectory("skel/base/js");
  grantDirectory("skel/workbench");
  grantDirectory("skel/workbench/www");

  /* yloader.js and yloader.min.js */
  $yloaderTarget = array(
    "app-src/i_configure/js/yloader.min.js",
    "skel/base/js/yloader.min.js",
    "skel/base/js/yloader.js"
    /* OBSOLETE 20190627
    ,
    "skel/base/js/yloader.min.js",
    "skel/chromeApp/js/yloader.js",
    "skel/chromeApp/js/yloader.min.js",
    "skel/workbench/www/js/yloader.js",
    "skel/workbench/www/js/yloader.min.js",
    "skel/workbench/js/yloader.js",
    "skel/workbench/js/yloader.min.js",
    "skel/webApp/js/yloader.js",
    "skel/webApp/js/yloader.min.js",
    "skel/electron/js/yloader.js",
    "skel/electron/js/yloader.min.js",
    "skel/webApp/templates/bs3/js/yloader.js",
    "skel/webApp/templates/bs3/js/yloader.min.js",
    "skel/webApp/templates/bs4/js/yloader.js",
    "skel/webApp/templates/bs4/js/yloader.min.js",
    "skel/webApp/templates/milligram-1.3/js/yloader.js",
    "skel/webApp/templates/milligram-1.3/js/yloader.min.js",
    "skel/webApp/templates/pure/js/yloader.js",
    "skel/webApp/templates/pure/js/yloader.min.js",
    "skel/webApp/templates/materialize/js/yloader.js",
    "skel/webApp/templates/materialize/js/yloader.min.js",
    "skel/webApp/templates/skeleton/js/yloader.js",
    "skel/webApp/templates/skeleton/js/yloader.min.js",
    "skel/MoSyncApp/LocalFiles/js/yloader.js",
    "skel/MoSyncApp/LocalFiles/js/yloader.min.js",
    "skel/chromeApp/js/yloader.js",
    "skel/chromeApp/js/yloader.min.js"
    */
  );

  foreach($yloaderTarget as $tgt) {
    $r=null;
    if (strpos($tgt, ".min.js")>0) {
      $r=putVersion($tgt, $yeapf_minJS);
    } else {
      $r=putVersion($tgt, $yeapfJS);
    }
    if ($r!=null) {
      if (!$r) {
        echo "\n\nError creating $tgt !\n";
        exit(10);
      }
    }
  }

  /* OBSOLETE 20190627
  copyYeapfAppFiles("skel/base/templates/bs4/js");

  copyMobileFiles("skel/electron/js");
  copyMobileFiles("skel/chromeApp/js");
  copyMobileFiles("skel/workbench/www/js");
  copyMobileFiles("skel/MoSyncApp/LocalFiles/js");

  copyFile("app-src/js/ycomm-worker.js",                         "skel/webApp/js");
  copyFile("app-src/js/min/ycomm-worker.min.js",                 "skel/webApp/js", false);
  copyFile("app-src/js/min/ystorage.min.js",                     "skel/webApp/js", false);
  copyFile("app-src/js/min/ystorage-indexedDB-interface.min.js", "skel/webApp/js", false);
  copyFile("app-src/js/min/ystorage-indexedDB-slave.min.js",     "skel/webApp/js", false);
  */

  /* samples */
  /* OBSOLETE 20190619
  $jsSpreadTargets = array("samples/html-editor", "samples/key-admin", "samples/yIndexedDB", "skel/cordova");
  */
  $jsSpreadTargets = array("skel/base");
  foreach($jsSpreadTargets as $targetFolder) {
    echo "ystorage and yloader -> $targetFolder\n";

    copyFile("app-src/js/ycomm-worker.js",                         "$targetFolder/js");
    copyFile("app-src/js/min/ycomm-worker.min.js",                 "$targetFolder/js", false);

    copyFile("app-src/js/min/ystorage.min.js",                     "$targetFolder/js", false);
    copyFile("app-src/js/min/ystorage-indexedDB-interface.min.js", "$targetFolder/js", false);
    copyFile("app-src/js/min/ystorage-indexedDB-slave.min.js",     "$targetFolder/js", false);

    copyFile("app-src/js/ystorage.js",                         "$targetFolder/js", false);
    copyFile("app-src/js/ystorage-indexedDB-interface.js",     "$targetFolder/js", false);
    copyFile("app-src/js/ystorage-indexedDB-slave.js",         "$targetFolder/js", false);

  }

?>

redpajama_set_name: RedPajamaGithub


text:
package stroom.resource.impl;

import stroom.resource.api.ResourceStore;

import com.google.inject.AbstractModule;

public class MockResourceModule extends AbstractModule {

    @Override
    protected void configure() {
        bind(ResourceStore.class).to(MockResourceStore.class);
    }
}


text:
import os

try:
    # Assumes package is located in the same directory
    # where this file resides
    PACKAGE_DIR = os.path.dirname(os.path.abspath(__file__))
except:
    PACKAGE_DIR = ""

def parent_dir(path):
    return os.path.abspath(os.path.join(path, os.pardir))

PROJECT_ROOT = parent_dir(PACKAGE_DIR)
# Where to build static files to
FREEZER_DESTINATION = os.path.join(PROJECT_ROOT, 'build')
FREEZER_DESTINATION_IGNORE = ['*.coffee']
DEBUG = True
SECRET_KEY = 'shhhh'
FLATPAGES_MARKDOWN_EXTENSIONS = ['codehilite', 'fenced_code', 'footnotes']
FLATPAGES_ROOT = os.path.join(PROJECT_ROOT, 'killtheyak-pages')
FLATPAGES_EXTENSION = '.md'

BASE_URL = 'http://anschwa.github.io/savetheyak'
GITHUB_REPO = 'http://www.github.com/anschwa/savetheyak'
PAGES_REPO = 'http://www.github.com/anschwa/savetheyak-pages'
RAW_PAGES_PREFIX = "https://raw.github.com/anschwa/savetheyak-pages/master/"

# View site locally
FREEZER_RELATIVE_URLS = True


text:
#include "curl/curl.h"
#include "curl/easy.h"

#include <stdlib.h>
#include <stdio.h>

static size_t writedata_callback(void* buffer, size_t size, size_t cnt, void* user)
{
    FILE* fp = (FILE*)user;
    fwrite(buffer, size, cnt, fp);
}

static void simple_test(const char* uri, FILE* fp)
{
   CURL* h = curl_easy_init();

   // uri
   curl_easy_setopt(h, CURLOPT_URL, uri);
   // show http protocal head
   curl_easy_setopt(h, CURLOPT_HEADER, true);
   // set timeout
   curl_easy_setopt(h, CURLOPT_TIMEOUT, 1500);
   // data and data-function callback
   curl_easy_setopt(h, CURLOPT_WRITEFUNCTION, writedata_callback);
   curl_easy_setopt(h, CURLOPT_WRITEDATA, fp);
}

/*
 * ===  FUNCTION  ======================================================================
 *         Name:  main
 *       Author:  bbxyard
 *      Created:  2014/08/08 20时36分53秒
 *  Description:
 * =====================================================================================
 */
int main (int argc, char *argv[])
{
    const char* uri = "www.baidu.com";
    if (argc >= 2)
    {
        uri = argv[1];
    }
    simple_test(uri, stdout);
    return EXIT_SUCCESS;
} /* ----------  end of function main  ---------- */


text:
// @formatter:off

package com.microsoft.alm.visualstudio.services.releasemanagement.webapi.contracts;

import java.net.URI;

/**
 */
public class ArtifactProvider {

    private int id;
    private String name;
    private URI sourceUri;
    private String version;

    public int getId() {
        return id;
    }

    public void setId(final int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(final String name) {
        this.name = name;
    }

    public URI getSourceUri() {
        return sourceUri;
    }

    public void setSourceUri(final URI sourceUri) {
        this.sourceUri = sourceUri;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(final String version) {
        this.version = version;
    }
}


text:
package examples.multibox;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * Perform any tasks and setup any data that
 * must be prepared before the form is displayed.
 *
 * @version $Rev: 471754 $ $Date: 2006-11-06 08:55:09 -0600 (Mon, 06 Nov 2006) $
 */
public class PrepareMultiboxAction extends Action {

    // ------------------------------------------------------------ Constructors

    /**
     * Constructor for PrepareOptionsAction.
     */
    public PrepareMultiboxAction() {
        super();
    }

    // ---------------------------------------------------------- Action Methods

    /**
     * Process the request and return an ActionForward instance
     * describing where and how control should be forwarded, or
     * nullif the response has already been completed.
     *
     * @param mapping The ActionMapping used to select this instance
     * @param form The optional ActionForm bean for this request (if any)
     * @param request The HTTP request we are processing
     * @param response The HTTP response we are creating
     *
     * @exception Exception if an exception occurs
     *
     * @return the ActionForward to forward control to
     */
    public ActionForward execute(
        ActionMapping mapping,
        ActionForm form,
        HttpServletRequest request,
        HttpServletResponse response)
        throws Exception {

        System.out.println("Prepare MultiboxActionForm ....");

        /*
         * Prepare a String array of color names used to generate
         * checkboxes using html:multibox tags in the JSP page.
         */
        String[] colors =
            { "Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet" };
        request.setAttribute("colors", colors);

        /*
         * Set default checkbox values.
         */
        String[] defaultFruits = { "Orange", "Banana", "Apple" };
        String[] defaultColors = { "Orange", "Yellow" };
        MultiboxActionForm multiboxForm = (MultiboxActionForm) form;
        multiboxForm.setFruits(defaultFruits);
        multiboxForm.setColors(defaultColors);

        // Return an ActionForward to the form
        return mapping.findForward("success");

    }

}


text:
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using Repsaj.Submerged.GatewayApp.Universal.Control.LED;
using Repsaj.Submerged.GatewayApp.Universal.Models.ConfigurationModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Repsaj.Submerged.Gateway.Tests.UnitTests
{
    [TestClass]
    public class LEDUnitTests
    {
        [TestMethod]
        public void LED_RGBWValue_Success()
        {
            LightingPointInTime point = new LightingPointInTime()
            {
                Color = "#e9e9e9",
                White = 233
            };

            RGBWValue value = RGBWHelper.FromLedenetPointInTime(point);

            Assert.IsNotNull(value);
            Assert.AreEqual(233, value.R);
            Assert.AreEqual(233, value.G);
            Assert.AreEqual(233, value.B);
            Assert.AreEqual(233, value.W);
        }

        [TestMethod]
        public void LED_RGBWValue_Success2()
        {
            LightingPointInTime point = new LightingPointInTime()
            {
                Color = "#720031",
                White = 128
            };

            RGBWValue value = RGBWHelper.FromLedenetPointInTime(point);

            Assert.IsNotNull(value);
            Assert.AreEqual(114, value.R);
            Assert.AreEqual(0, value.G);
            Assert.AreEqual(49, value.B);
            Assert.AreEqual(128, value.W);
        }

        [TestMethod]
        public void LED_RGBWValue_Invalid()
        {
            LightingPointInTime point = new LightingPointInTime()
            {
                Color = "invalid",
                White = 233
            };

            Assert.ThrowsException<ArgumentException>(() =>
            {
                RGBWValue value = RGBWHelper.FromLedenetPointInTime(point);
            });
        }

        [TestMethod]
        public void LED_CalculateProgram_Success()
        {
            var points = new List<LightingPointInTime>();

            // 30 minute fade-in at 10AM
            points.Add(new LightingPointInTime()
            {
                Time = 600,
                Color = "#f1f3be",
                FadeIn = 30,
                White = 128
            });

            // 15 minute noon fade-in high output at 2PM
            points.Add(new LightingPointInTime()
            {
                Time = 840,
                Color = "#f1f3be",
                FadeIn = 15,
                White = 255
            });

            // 1 hour fade-out to moonlight at 8PM
            points.Add(new LightingPointInTime()
            {
                Time = 1200,
                Color = "#1a1247",
                FadeIn = 60,
                White = 0
            });

            // 15 minute fade-out at 11PM
            points.Add(new LightingPointInTime()
            {
                Time = 1380,
                Color = "#000000",
                FadeIn = 15,
                White = 0
            });

            var program = RGBWHelper.CalculateProgram(points);

            Assert.AreEqual(1440, program.Length);

            RGBWValue black = new RGBWValue(0, 0, 0, 0);
            RGBWValue morning = new RGBWValue(241, 243, 190, 128);
            RGBWValue noon = new RGBWValue(241, 243, 190, 255);
            RGBWValue moonlight = new RGBWValue(26, 18, 71, 0);

            // check for blackout between 00:00 and 09:30
            for (int i = 0; i < 570; i++)
                Assert.AreEqual(black, program[i]);

            // check morning color
            Assert.AreEqual(morning, program[10 * 60]);
            // check noon color
            Assert.AreEqual(noon, program[14 * 60]);
            // check moonlight color
            Assert.AreEqual(moonlight, program[20 * 60]);

            // check for blackout between 23:00 and 23:59
            for (int i = 1380; i < 1440; i++)
                Assert.AreEqual(black, program[i]);
        }

        [TestMethod]
        public void LED_CalculateFade_Success()
        {
            RGBWValue previous = new RGBWValue(136, 85, 34, 10);
            LightingPointInTime nextPoint = new LightingPointInTime()
            {
                Time = 1320,
                Color = "#000000",
                FadeIn = 30,
                Level = 0,
                White = 0
            };

            var result = RGBWHelper.CalculateRGBWValue(previous, nextPoint, 1290);

            RGBWValue expected = new RGBWValue(136, 85, 34, 10);

            Assert.IsNotNull(result);
            Assert.AreEqual(expected, result);
        }

        [TestMethod]
        public void LED_CalculateFade2_Success()
        {
            RGBWValue previous = new RGBWValue(136, 86, 34, 10);
            LightingPointInTime nextPoint = new LightingPointInTime()
            {
                Time = 1320,
                Color = "#000000",
                FadeIn = 30,
                Level = 0,
                White = 0
            };

            var result = RGBWHelper.CalculateRGBWValue(previous, nextPoint, 1305);

            RGBWValue expected = new RGBWValue(68, 43, 17, 5);

            Assert.IsNotNull(result);
            Assert.AreEqual(expected, result);
        }
    }
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
	value: true
});
var register = exports.register = function register(Handlebars) {
	Handlebars.registerHelper('toString', function (string) {
		return string && string.toString() || '';
	});
};


text:
Creates a new [PDF document](document.md).

**Arguments:**

- **opts** - document styling options

**Options:**

- **width** (default: [595.296](#units)) - the page width
- **height** (default: [841.896](#units)) - the page height
- **padding**, **paddingTop**, **paddingRight**, **paddingBottom**, **paddingLeft** (default: 0) - the page padding
- **precision** (default: 3) - precision used when creating the PDF and writing floating point numbers
- **threshold** (default: 64) - threshold for the computation iterations done, before throwing; used to don't get caught in endless computations (should be increased for huge documents)
- + [Text Options](document.md#texttext-opts)

**Example:**

```js
var doc = new pdfjs.Document({
  font:    new pdfjs.TTFFont(buffer),
  padding: 10
})
```

For an explanation of the units and different paper sizes have a look at the [units](#units) section.

### new pdfjs.TTFFont(buffer) | pdfjs.createTTFFont(buffer)

Creates a new TTF Font object that can be used with PDF documents. The created TTF Font object can be used multiple times.

**Arguments:**

- **buffer** - the font data, as either Buffer or ArrayBuffer

### new pdfjs.Image(buffer) | pdfjs.createImage(buffer)

Creates a new Image object that [can be used with PDF documents](document.md#imageimg-opts). The created image object can be used multiple times. Supported images are: JPEG, PDF

**Arguments:**

- **buffer** - the font data, as either Buffer or ArrayBuffer

### pdfjs.load(path, callback)

Helper method to load a specific file (image or font). Works on both server and client.

**Example:**

```js
pdfjs.load('/assets/fonts/opensans.ttf', function(err, buf) {
    if (err) throw err

    var font = new pdfjs.TTFFont(buf)
    // ...
})
```

### Units

PDFs are measured in points (`1/72"`), i.e., **each point is `1/72` of an inch**. That is, the paper size of an US letter is in points `8.5 * 72 = 612` wide and `11 * 72 = 792` high.

**Paper Sizes:**

- **A4** (default) - 210mm × 297mm (8.27in × 11.7in) = 595.296 x 841.896
- **American Letter** - 215.9mm × 279.4mm (8.5in × 11in) = 612 x 792


text:
require 'spec_helper'

describe 'php5::extension::xdebug' do

  describe command('php --ri xdebug') do
    its(:exit_status) { should eq 0 }
    its(:stdout) { should match /xdebug.remote_host => 127.0.0.1/ }
    its(:stdout) { should match /xdebug.remote_port => 1234/ }
    its(:stdout) { should match /xdebug.remote_autostart => On/ }
    its(:stdout) { should match /xdebug.remote_connect_back => Off/ }
  end

  describe file('/var/log/php/error.log') do
    its(:content) { should_not match /Warning.*xdebug.*already loaded/ }
  end
end


text:
package io.thisandthat.drawing;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class DrawingActivity extends Activity implements ColorPickerDialog.OnColorChangedListener {

    private static final int COLOR_MENU_ID = Menu.FIRST;

    private DrawingView mDrawingView;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDrawingView = new DrawingView(this);
        setContentView(mDrawingView);
    }

    @Override
    public void onStart() {
        super.onStart();
        // Set up a notification to let us know when we're connected or disconnected from the Firebase servers

    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        menu.add(0, COLOR_MENU_ID, 0, "Color").setShortcut('3', 'c');
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == COLOR_MENU_ID) {
            new ColorPickerDialog(this, this, 0xFFFF0000).show();
            return true;
        } else {
            return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void colorChanged(int newColor) {
        mDrawingView.setColor(newColor);
    }
}


text:
package org.willian.owb2infa.helper.owb;

import java.util.ArrayList;

import org.willian.owb2infa.model.MetadataOperator;
import org.willian.owb2infa.model.MetadataProperty;

public final class OWBPropConstants {

	public static final String HOST = "HOST";
	public static final String PORT = "PORT";
	public static final String ORACLE_SID = "SID";
	public static final String USER = "USER";
	public static final String PASSWORD = "PASSWD";
	public static final String OWB_PROJECT = "PROJECT";
	public static final String OWB_REPOSITORY = "OWBREPO";
	public static final String OWB_MODULE = "MODULE";

	public static boolean isSupportedOWBSourceOperator(String opType) {

		switch (opType) {
			case "TABLE":
			case "VIEW":
			case "EXTERNAL_TABLE":
			case "MATERIALIZED_VIEW":
				return true;
			default:
				return false;
		}
	}

	public static String getOWBOPProperty(MetadataOperator op, String propertyName) {
		ArrayList<MetadataProperty> props = op.getProperties();

		if (props != null) {

			for (MetadataProperty prop : props) {
				if (prop.getName().equalsIgnoreCase(propertyName)) {
					return prop.getValue();
				}
			}
		}

		return null;
	}
}


text:
namespace elang {
namespace compiler {

//////////////////////////////////////////////////////////////////////
//
// Translator::BreakContext represents target blocks of |break| and
// |continue| statements. |switch| statement also specify |continue_block|
// from outer |BreakContext|.
//
struct Translator::BreakContext final {
  ir::Control* break_block;
  ir::Control* continue_block;
  const BreakContext* outer;

  BreakContext(const BreakContext* outer,
               ir::Control* break_block,
               ir::Control* continue_block)
      : break_block(break_block),
        continue_block(continue_block),
        outer(outer) {}
};

class Translator::ScopedBreakContext final {
 public:
  ScopedBreakContext(Translator* generator,
                     ir::Control* break_block,
                     ir::Control* continue_block);
  ~ScopedBreakContext();

 private:
  Translator* const translator_;
  BreakContext const context_;

  DISALLOW_COPY_AND_ASSIGN(ScopedBreakContext);
};

Translator::ScopedBreakContext::ScopedBreakContext(Translator* generator,
                                                   ir::Control* break_block,
                                                   ir::Control* continue_block)
    : translator_(generator),
      context_(translator_->break_context_, break_block, continue_block) {
  translator_->break_context_ = &context_;
}

Translator::ScopedBreakContext::~ScopedBreakContext() {
  DCHECK_EQ(translator_->break_context_, &context_);
  translator_->break_context_ = context_.outer;
}

//////////////////////////////////////////////////////////////////////
//
// Translator
//
void Translator::TranslateStatement(ast::Statement* node) {
  DCHECK(!visit_result_);
  Traverse(node);
  DCHECK(!visit_result_);
}

//
// ast::Visitor statement nodes
//
void Translator::VisitBlockStatement(ast::BlockStatement* node) {
  builder_->StartVariableScope();

  for (auto const statement : node->statements()) {
    if (!builder()->has_control()) {
      Error(ErrorCode::TranslatorStatementUnreachable, statement);
      continue;
    }
    TranslateStatement(statement);
  }

  builder_->EndVariableScope();
}

void Translator::VisitBreakStatement(ast::BreakStatement* node) {
  DCHECK(node);
  DCHECK(break_context_);
  builder_->EndBlockWithJump(break_context_->break_block);
}

void Translator::VisitContinueStatement(ast::ContinueStatement* node) {
  DCHECK(node);
  DCHECK(break_context_);
  DCHECK(break_context_->continue_block);
  builder_->EndBlockWithJump(break_context_->continue_block);
}

void Translator::VisitDoStatement(ast::DoStatement* node) {
  auto const loop_block = NewLoop();
  auto const break_block = NewMerge({});
  auto const continue_block = NewMerge({});

  builder_->StartDoLoop(loop_block);
  {
    ScopedBreakContext scope(this, break_block, continue_block);
    TranslateStatement(node->statement());
  }
  builder_->EndBlockWithJump(continue_block);

  builder_->StartMergeBlock(continue_block);
  auto const condition = TranslateBool(node->condition());
  builder_->EndLoopBlock(condition, loop_block, break_block);

  builder_->StartMergeBlock(break_block);
}

void Translator::VisitExpressionList(ast::ExpressionList* node) {
  for (auto const expression : node->expressions())
    Translate(expression);
}

void Translator::VisitExpressionStatement(ast::ExpressionStatement* node) {
  Translate(node->expression());
}

void Translator::VisitForStatement(ast::ForStatement* node) {
  auto const loop_block = NewLoop();
  auto const continue_block = builder_->NewMergeBlock();
  auto const break_block = builder_->NewMergeBlock();

  // Loop head
  TranslateStatement(node->initializer());
  auto const head_compare = Translate(node->condition());
  builder_->StartWhileLoop(head_compare, loop_block, break_block);

  // Loop body
  {
    ScopedBreakContext scope(this, break_block, continue_block);
    TranslateStatement(node->statement());
  }
  builder_->EndBlockWithJump(continue_block);

  // Continue block
  builder_->StartMergeBlock(continue_block);
  TranslateStatement(node->step());
  auto const continue_compare = Translate(node->condition());
  builder_->EndLoopBlock(continue_compare, loop_block, break_block);

  builder_->StartMergeBlock(break_block);
}

//    for (var element : array)
//      use(element);
//
//    head:
//      ...
//      element elty* %start = %array, 0
//      length int32 %length = %array, 0
//      element elty* %end = %array, %length
//      static_cast uintptr %1 = %ptr
//      static_cast uintptr %2 = %end
//      lt %cmp = %1, %2
//      br %cmp, loop, break
//    loop:
//      phi %ptr = head: %ptr, continue: %ptr2
//      load elty %element = %array, %ptr,
//      call $"use", %element
//      br continue
//    continue:
//      static_cast uintptr %ptrint, %ptr
//      add elty* %ptrint2 = %ptrint, sizeof(elty)
//      static_cast elty* %ptr2 = %ptrint2
//      static_cast uintptr %1 = %ptr2
//      static_cast uintptr %2 = %end
//      lt %cmp = %1, %2
//      br %cmp, loop, break
//    break:
//      ...
void Translator::VisitForEachStatement(ast::ForEachStatement* node) {
  auto const array = Translate(node->enumerable());
  if (!array->output_type()->is<ir::PointerType>()) {
    Error(ErrorCode::CodeGeneratorStatementNotYetImplemented, node);
    return;
  }
  auto const array_type = array->output_type()
                              ->as<ir::PointerType>()
                              ->pointee()
                              ->as<ir::ArrayType>();
  if (!array_type) {
    Error(ErrorCode::CodeGeneratorStatementNotYetImplemented, node);
    return;
  }

  auto const loop_block = NewLoop();
  auto const continue_block = builder_->NewMergeBlock();
  auto const break_block = builder_->NewMergeBlock();

  // Loop head
  auto const pointer_variable = session()->semantic_factory()->NewVariable(
      analysis()->SemanticOf(node->variable())->as<sm::Variable>()->type(),
      sm::StorageClass::Local, node->variable()->name());

  auto const element_type = array_type->as<ir::ArrayType>()->element_type();
  auto const element_pointer_type = NewPointerType(element_type);
  auto const start_element_pointer = NewElement(array, NewInt32(0));
  auto const end_element_pointer = NewElement(array, NewLength(array, 0));

  builder_->BindVariable(pointer_variable, start_element_pointer);
  auto const head_compare =
      NewIntCmp(ir::IntCondition::UnsignedLessThan, start_element_pointer,
                end_element_pointer);
  builder_->StartWhileLoop(head_compare, loop_block, break_block);

  // Loop body
  auto const element_pointer_0 = builder_->VariableValueOf(pointer_variable);
  {
    ScopedBreakContext scope(this, break_block, continue_block);
    auto const element_value = builder_->NewLoad(array, element_pointer_0);
    auto const variable = SemanticOf(node->variable())->as<sm::Variable>();
    DCHECK(variable);
    builder_->StartVariableScope();
    builder_->BindVariable(variable, element_value);
    TranslateStatement(node->statement());
    builder_->EndVariableScope();
  }
  builder_->EndBlockWithJump(continue_block);

  // Continue block
  builder_->StartMergeBlock(continue_block);
  auto const pointer_int = NewStaticCast(uintptr_type(), element_pointer_0);
  auto const pointer_add = NewIntAdd(pointer_int, NewSizeOf(element_type));
  auto const element_pointer_1 =
      NewStaticCast(element_pointer_type, pointer_add);
  builder_->AssignVariable(pointer_variable, element_pointer_1);
  auto const continue_compare =
      NewIntCmp(ir::IntCondition::UnsignedLessThan, element_pointer_1,
                end_element_pointer);
  builder_->EndLoopBlock(continue_compare, loop_block, break_block);

  builder_->StartMergeBlock(break_block);
}

void Translator::VisitIfStatement(ast::IfStatement* node) {
  auto const condition = TranslateBool(node->condition());
  auto const if_node = builder_->EndBlockWithBranch(condition);
  auto const merge_node = NewMerge({});

  builder_->StartIfBlock(NewIfTrue(if_node));
  TranslateStatement(node->then_statement());
  builder_->EndBlockWithJump(merge_node);

  builder_->StartIfBlock(NewIfFalse(if_node));
  if (node->else_statement())
    TranslateStatement(node->else_statement());
  builder_->EndBlockWithJump(merge_node);

  builder_->StartMergeBlock(merge_node);
}

void Translator::VisitReturnStatement(ast::ReturnStatement* node) {
  auto const expression = node->expression();
  builder()->EndBlockWithRet(expression ? Translate(expression) : void_value());
}

void Translator::VisitVarStatement(ast::VarStatement* node) {
  for (auto const declaration : node->variables()) {
    auto const variable =
        SemanticOf(declaration->variable())->as<sm::Variable>();
    DCHECK(variable);
    builder_->BindVariable(variable, Translate(declaration->expression()));
  }
}

void Translator::VisitWhileStatement(ast::WhileStatement* node) {
  auto const loop_block = NewLoop();
  auto const continue_block = builder_->NewMergeBlock();
  auto const break_block = builder_->NewMergeBlock();

  // Loop head
  auto const head_compare = Translate(node->condition());
  builder_->StartWhileLoop(head_compare, loop_block, break_block);

  // Loop body
  {
    ScopedBreakContext scope(this, break_block, continue_block);
    TranslateStatement(node->statement());
  }
  builder_->EndBlockWithJump(continue_block);

  // Continue block
  builder_->StartMergeBlock(continue_block);
  auto const continue_compare = Translate(node->condition());
  builder_->EndLoopBlock(continue_compare, loop_block, break_block);

  builder_->StartMergeBlock(break_block);
}

}  // namespace compiler
}  // namespace elang


text:
layout: doc
title: "Vitess Roadmap"
redirect_from: /resources/roadmap.html
description: Current version, what we are working on, what's planned.
modified:
excerpt:
tags: []
image:
  feature:
  teaser:
  thumb:
toc: true
share: false
---
Vitess is an active open source project.  Here is a list of recent and upcoming
features the team is focused on: Check with us on
our [forums](https://groups.google.com/forum/#!forum/vitess) for more
information.

## Vitess before 2.0 GA

Vitess has been used internally by YouTube for a few years now, but the first
public versions lacked polish and documentation. Version 1.0 was mostly an
internal release.

## Vitess 2.0 GA

[Vitess 2.0 GA](https://github.com/youtube/vitess/releases/tag/v2.0.0) was
created on July 11, 2016. It was the first major public release.

It contains all the core features of the Vitess product:

* Advanced data access:

  * Automatic query routing to actively serving instances.

  * Scalability through sharding, with transparent access to sharded data,
    without need for proprietary API.

  * Map-Reduce support for data warehousing queries.

  * Limit the negative impact of bad queries.

* Advanced manageability features:

  * Orchestrator integration, auto-reparent on master failure.

  * Out-of-the-box support for Kubernetes

  * No-downtime dynamic resharding.

  * Expose data for advanced monitoring and bad query detection.

## Vitess 2.1

Vitess 2.1 is actively being worked on. Apart from the multiple small changes
we've been making to address a number of small issues, we are adding the
following core features:

* Support for distributed transactions, using 2 phase commit.

* Resharding workflow improvements, to increase manageability of the process.

* Online schema swap, to apply complex schema changes without any downtime.

* New dynamic UI (vtctld), rewritten from scratch in Angular 2. We will still
  have the old UI in Vitess 2.1 as a fallback, but it will be removed in Vitess
  2.2.

* Update Stream functionality, for applications to subscribe to a change stream
  (for cache invalidation, for instance).

* Improved Map-Reduce support, for tables with non-uniform distributions.

* Increase large installation scalability with two-layer vtgate pools (l2vtgate,
  applicable to 100+ shard installations).

* Better Kubernetes support (Helm support, better scripts, ...).

* New implementations of the topology services for Zookeeper (`zk2`) and etcd
  (`etcd2`).  In Vitess 2.1 they will become the recommended implementations and
  the old `zookeeper` and `etcd` will be deprecated. In Vitess 2.2 only the new
  `zk2` and `etcd2` implementations will remain, so please migrate after upgrade
  to Vitess 2.1.

* Added support for [Consul](http://consul.io) topology service client.

* Initial version of the Master Buffering feature. It allows for buffering
  master traffic while a failover is in progress, and trade downtime with
  extra latency.

We already cut
the
[2.1.0-alpha.1 release](https://github.com/youtube/vitess/releases/tag/v2.1.0-alpha.1),
and we are finalizing the last details at the moment. Release ETA is around
beginning of 2017.

## Vitess Moving Forward

The following list contains areas where we want to focus next, after the current
set of changes. Let us know if one of these areas is of particular interest to
your application!

### Data Access

* Additional support for cross-shard constructs (IN clause, ordering and
  filtering, ...).

* ExecuteBatch improvements (to increase performance of bulk imports for
  instance).

* Multi-value inserts (across shards or not).

### Manageability

* Better support for MySQL DDL constructs.

* Support for MySQL 8.0.

* Additional Kubernetes integration.

* Include resharding workflows in the control panel UI (vtctld).

* Support vertical splits to an existing keyspace, so any table can be moved
  around to any keyspace. Only for unsharded keyspaces, at first.

* Out-of-the-box integration with Promotheus for monitoring.

### Scaling

* Better resource utilization / less CPU usage.

## Future Work

We are considering integration/implementation of the following technologies in
our roadmap.  For specific features, reach out to us to discuss opportunities to
collaborate or prioritize some of the work:

* Integration with Mesos and DC/OS.

* Integration with Docker Swarm.

* Improved support for row-based replication (for Update Stream for instance).

* Better integration with Apache Spark (native instead of relying on Hadoop
  InputSource).


text:
export function reducer(state, action) {
  switch(action.type) {

  }
  return state;
}


text:
typedef struct mapinfo {
    struct mapinfo *next;
    unsigned start;
    unsigned end;
    int pkgRef;
    char name[];
} mapinfo;

mapinfo *init_mapinfo(int pid);

void deinit_mapinfo(mapinfo *mi);

const char *map_to_name(mapinfo *mi, unsigned pc, const char *def);

const mapinfo *pc_to_mapinfo(mapinfo *mi, unsigned pc, unsigned *rel_pc);

#endif //ANTIVM_MAPINFO_H


text:
from datetime import datetime, timedelta
from typing import TYPE_CHECKING, List, Dict, Any
from msrest import Serializer, Deserializer
from azure.core.exceptions import HttpResponseError
from azure.core.pipeline.policies import BearerTokenCredentialPolicy

if TYPE_CHECKING:
    from azure.core.credentials import TokenCredential

def get_authentication_policy(
    credential,  # type: "TokenCredential"
    audience=None # type: str
):
    # type: (...) -> BearerTokenCredentialPolicy
    """Returns the correct authentication policy"""
    if not audience:
        audience = "https://api.loganalytics.io/"
    scope = audience.rstrip('/') + "/.default"
    if credential is None:
        raise ValueError("Parameter 'credential' must not be None.")
    if hasattr(credential, "get_token"):
        return BearerTokenCredentialPolicy(
            credential, scope
        )

    raise TypeError("Unsupported credential")

def get_metrics_authentication_policy(
    credential,  # type: TokenCredential
    audience=None # type: str
):
    # type: (...) -> BearerTokenCredentialPolicy
    """Returns the correct authentication policy"""
    if not audience:
        audience = "https://management.azure.com/"
    scope = audience.rstrip('/') + "/.default"
    if credential is None:
        raise ValueError("Parameter 'credential' must not be None.")
    if hasattr(credential, "get_token"):
        return BearerTokenCredentialPolicy(
            credential, scope
        )

    raise TypeError("Unsupported credential")

def order_results(request_order, mapping, **kwargs):
    # type: (List, Dict, Any) -> List
    ordered = [mapping[id] for id in request_order]
    results = []
    for item in ordered:
        if not item.body.error:
            results.append(
                kwargs.get("obj")._from_generated(item.body) # pylint: disable=protected-access
            )
        else:
            error = item.body.error
            if error.code == "PartialError":
                res = kwargs.get("partial_err")._from_generated(  # pylint: disable=protected-access
                    item.body, kwargs.get("raise_with")
                )
                results.append(res)
            else:
                results.append(
                    kwargs.get("err")._from_generated(error) # pylint: disable=protected-access
                )
    return results

def construct_iso8601(timespan=None):
    if not timespan:
        return None
    try:
        start, end, duration = None, None, None
        if isinstance(timespan[1], datetime):  # we treat thi as start_time, end_time
            start, end = timespan[0], timespan[1]
        elif isinstance(
            timespan[1], timedelta
        ):  # we treat this as start_time, duration
            start, duration = timespan[0], timespan[1]
        else:
            raise ValueError(
                "Tuple must be a start datetime with a timedelta or an end datetime."
            )
    except TypeError:
        duration = timespan  # it means only duration (timedelta) is provideds
    if duration:
        try:
            duration = "PT{}S".format(duration.total_seconds())
        except AttributeError:
            raise ValueError("timespan must be a timedelta or a tuple.")
    iso_str = None
    if start is not None:
        start = Serializer.serialize_iso(start)
        if end is not None:
            end = Serializer.serialize_iso(end)
            iso_str = start + "/" + end
        elif duration is not None:
            iso_str = start + "/" + duration
        else:  # means that an invalid value None that is provided with start_time
            raise ValueError(
                "Duration or end_time cannot be None when provided with start_time."
            )
    else:
        iso_str = duration
    return iso_str

def native_col_type(col_type, value):
    if col_type == "datetime":
        try:
            value = Deserializer.deserialize_iso(value)
        except Exception: # pylint: disable=broad-except
            # if there is any exception in deserializing the iso,
            # return the value to the user
            pass
    elif col_type in ("timespan", "guid"):
        value = str(value)
    return value

def process_row(col_types, row):
    return [native_col_type(col_types[ind], val) for ind, val in enumerate(row)]

def process_error(error, model):
    try:
        model = model._from_generated( # pylint: disable=protected-access
            error.model.error
        )
    except AttributeError:  # model can be none
        pass
    raise HttpResponseError(message=error.message, response=error.response, model=model)

def process_prefer(server_timeout, include_statistics, include_visualization):
    prefer = ""
    if server_timeout:
        prefer += "wait=" + str(server_timeout) + ","
    if include_statistics:
        prefer += "include-statistics=true,"
    if include_visualization:
        prefer += "include-render=true"
    return prefer.rstrip(",")


text:
namespace BCompute
{
    public enum Genotype
    {
        Dominant,
        Heterozygous,
        Recessive
    }
}


text:
package org.gedcomx.atom;

import org.codehaus.enunciate.Facet;
import org.codehaus.enunciate.json.JsonName;
import org.codehaus.jackson.annotate.JsonProperty;
import org.gedcomx.atom.rt.AtomModelVisitor;
import org.gedcomx.common.URI;
import org.gedcomx.links.Link;
import org.gedcomx.links.SupportsLinks;
import org.gedcomx.rt.GedcomxConstants;
import org.gedcomx.rt.json.JsonElementWrapper;
import org.gedcomx.search.ResultConfidence;

import javax.xml.XMLConstants;
import javax.xml.bind.annotation.*;
import javax.xml.namespace.QName;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * The "atom:entry" element represents an individual entry, acting as a container for metadata and data associated with the entry.
 *
 * @author Ryan Heaton
 */
@XmlRootElement
@XmlType ( name = "Entry" )
@JsonElementWrapper ( name = "entries" )
@SuppressWarnings ( "gedcomx:no_id" )
@Facet ( name = GedcomxConstants.FACET_GEDCOMX_RS )
public class Entry extends ExtensibleElement implements SupportsLinks {

  private List<Person> authors;
  private List<Category> categories;
  private Content content;
  private List<Person> contributors;
  private URI id;
  private Float score;
  private ResultConfidence confidence;
  private List<Link> links;
  private Date published;
  private String rights;
  private String title;
  private Date updated;
  private Map<QName, String> extensionAttributes;

  /**
   * The author of the entry.
   *
   * @return The author of the entry.
   */
  @XmlElement ( name = "author" )
  @JsonName ( "authors" )
  @JsonProperty ( "authors" )
  public List<Person> getAuthors() {
    return authors;
  }

  /**
   * The author of the entry.
   *
   * @param authors The author of the entry.
   */
  @JsonProperty ( "authors" )
  public void setAuthors(List<Person> authors) {
    this.authors = authors;
  }

  /**
   * information about a category associated with an entry.
   *
   * @return information about a category associated with an entry.
   */
  @XmlElement ( name = "category" )
  @JsonName ( "categories" )
  @JsonProperty ( "categories" )
  public List<Category> getCategories() {
    return categories;
  }

  /**
   * information about a category associated with an entry.
   *
   * @param categories information about a category associated with an entry.
   */
  @JsonProperty ( "categories" )
  public void setCategories(List<Category> categories) {
    this.categories = categories;
  }

  /**
   * The content of the entry.
   *
   * @return The content of the entry.
   */
  public Content getContent() {
    return content;
  }

  /**
   * The content of the entry.
   *
   * @param content The content of the entry.
   */
  public void setContent(Content content) {
    this.content = content;
  }

  /**
   * information about a category associated with the entry
   *
   * @return information about a category associated with the entry
   */
  @XmlElement ( name = "contributor" )
  @JsonName ( "contributors" )
  @JsonProperty ( "contributors" )
  public List<Person> getContributors() {
    return contributors;
  }

  /**
   * information about a category associated with the entry
   *
   * @param contributors information about a category associated with the entry
   */
  @JsonProperty ( "contributors" )
  public void setContributors(List<Person> contributors) {
    this.contributors = contributors;
  }

  /**
   * a permanent, universally unique identifier for the entry.
   *
   * @return a permanent, universally unique identifier for the entry.
   */
  @XmlSchemaType ( name = "anyURI", namespace = XMLConstants.W3C_XML_SCHEMA_NS_URI )
  public URI getId() {
    return id;
  }

  /**
   * a permanent, universally unique identifier for the entry.
   *
   * @param id a permanent, universally unique identifier for the entry.
   */
  public void setId(URI id) {
    this.id = id;
  }

  /**
   * The relevance score, if this entry represents a search result. The value of this score is implementation-specific.
   *
   * @return The relevance score.
   */
  @XmlElement ( namespace = GedcomxConstants.GEDCOMX_NAMESPACE )
  public Float getScore() {
    return score;
  }

  /**
   * The relevance score, if this entry represents a search result. The value of this score is implementation-specific.
   *
   * @param score The relevance score.
   */
  public void setScore(Float score) {
    this.score = score;
  }

  /**
   * The confidence of the result, if this entry represents a search result.
   *
   * @return The confidence of the result, if this entry represents a search result.
   */
  @XmlElement ( namespace = GedcomxConstants.GEDCOMX_NAMESPACE )
  public ResultConfidence getConfidence() {
    return confidence;
  }

  /**
   * The confidence of the result, if this entry represents a search result.
   *
   * @param confidence The confidence of the result, if this entry represents a search result.
   */
  public void setConfidence(ResultConfidence confidence) {
    this.confidence = confidence;
  }

  /**
   * a reference from a entry to a Web resource.
   *
   * @return a reference from a entry to a Web resource.
   */
  @XmlElement ( name = "link" )
  @JsonName ( "links" )
  @JsonProperty ( "links" )
  public List<Link> getLinks() {
    return links;
  }

  /**
   * a reference from a entry to a Web resource.
   *
   * @param links a reference from a entry to a Web resource.
   */
  @JsonProperty ( "links" )
  public void setLinks(List<Link> links) {
    this.links = links;
  }

  /**
   * Add a hypermedia link.
   *
   * @param link The hypermedia link.
   */
  public void addLink(Link link) {
    if (this.links == null) {
      setLinks(new ArrayList<Link>());
    }

    this.links.add(link);
  }

  /**
   * Add a hypermedia link.
   *
   * @param rel  The link rel.
   * @param href The target URI.
   */
  public void addLink(String rel, URI href) {
    addLink(new Link(rel, href));
  }

  /**
   * Add a templated link.
   *
   * @param rel      The link rel.
   * @param template The link template.
   */
  public void addTemplatedLink(String rel, String template) {
    Link link = new Link();
    link.setRel(rel);
    link.setTemplate(template);
    addLink(link);
  }

  /**
   * Get a link by its rel.
   *
   * @param rel The link rel.
   * @return The link by rel.
   */
  public Link getLink(String rel) {
    if (this.links != null) {
      for (Link link : getLinks()) {
        if (rel.equals(link.getRel())) {
          return link;
        }
      }
    }
    return null;
  }

  /**
   * Get a list of links by rel.
   *
   * @param rel The rel of the links.
   * @return The link.
   */
  public List<Link> getLinks(String rel) {
    ArrayList<Link> links = new ArrayList<Link>();
    if (this.links != null) {
      for (Link link : getLinks()) {
        if (rel.equals(link.getRel())) {
          links.add(link);
        }
      }
    }
    return links;
  }

  /**
   * instant in time associated with an event early in the life cycle of the entry.
   *
   * @return instant in time associated with an event early in the life cycle of the entry.
   */
  public Date getPublished() {
    return published;
  }

  /**
   * instant in time associated with an event early in the life cycle of the entry.
   *
   * @param published instant in time associated with an event early in the life cycle of the entry.
   */
  public void setPublished(Date published) {
    this.published = published;
  }

  /**
   * information about rights held in and over the entry.
   *
   * @return information about rights held in and over the entry.
   */
  public String getRights() {
    return rights;
  }

  /**
   * information about rights held in and over the entry.
   *
   * @param rights information about rights held in and over the entry.
   */
  public void setRights(String rights) {
    this.rights = rights;
  }

  /**
   * a human-readable title for the entry
   *
   * @return a human-readable title for the entry
   */
  public String getTitle() {
    return title;
  }

  /**
   * a human-readable title for the entry
   *
   * @param title a human-readable title for the entry
   */
  public void setTitle(String title) {
    this.title = title;
  }

  /**
   * the most recent instant in time when the entry was modified in a way the publisher considers significant.
   *
   * @return the most recent instant in time when the entry was modified in a way the publisher considers significant.
   */
  public Date getUpdated() {
    return updated;
  }

  /**
   * the most recent instant in time when the entry was modified in a way the publisher considers significant.
   *
   * @param updated the most recent instant in time when the entry was modified in a way the publisher considers significant.
   */
  public void setUpdated(Date updated) {
    this.updated = updated;
  }

  @XmlAnyAttribute
  public Map<QName, String> getExtensionAttributes() {
    return extensionAttributes;
  }

  public void setExtensionAttributes(Map<QName, String> extensionAttributes) {
    this.extensionAttributes = extensionAttributes;
  }

  /**
   * Accept a visitor.
   *
   * @param visitor The visitor to accept.
   */
  public void accept(AtomModelVisitor visitor) {
    visitor.visitEntry(this);
  }
}


text:
<?php

namespace frontend\models;

use common\helper\Helper;
use Yii;

/**
 * This is the model class for table "manage".
 *
 * @property integer $id
 * @property string $username
 * @property string $password
 * @property string $mobile
 */
class Manage extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public $rePassword;
    public static function tableName()
    {
        return 'manage';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['username', 'required', 'message'=>"用户名不能为空"],
            ['password', 'required', 'message'=>"密码不能为空"],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'username' => 'Username',
            'password' => 'Password',
        ];
    }

    public function login($data)
    {
        if ($this->validate()) {

            //根据用户名来查询密码.
            $arr = Helper::getService('Manage.Manage')->login($data['Manage']['username']);

            if (empty($arr)) {
                $this->addError('username', '用户名或者密码错误');
                return false;
            }

            if ($arr['password'] != md5($data['Manage']['password'])) {
                $this->addError('username', '用户名或者密码错误');
                return false;
            }

            Yii::$app->session->set('manage', $arr);
            return true;

        } else {
          return false;
        }
    }

}


text:
using System;
using System.Net.Http;
using Cuemon.Configuration;

namespace Cuemon.Extensions.Net.Http
{
    /// <summary>
    /// Configuration options for <see cref="SlimHttpClientFactory"/>.
    /// </summary>
    /// <seealso cref="IParameterObject"/>
    public class SlimHttpClientFactoryOptions : IParameterObject
    {
        private TimeSpan _handlerLifetime;

        /// <summary>
        /// Initializes a new instance of the <see cref="SlimHttpClientFactoryOptions"/> class.
        /// </summary>
        /// <remarks>
        /// The following table shows the initial property values for an instance of <see cref="SlimHttpClientFactoryOptions"/>.
        /// <list type="table">
        ///     <listheader>
        ///         <term>Property</term>
        ///         <description>Initial Value</description>
        ///     </listheader>
        ///     <item>
        ///         <term><see cref="HandlerLifetime"/></term>
        ///         <description><c>TimeSpan.FromMinutes(5);</c></description>
        ///     </item>
        /// </list>
        /// </remarks>
        public SlimHttpClientFactoryOptions()
        {
            HandlerLifetime = TimeSpan.FromMinutes(5);
        }

        /// <summary>
        /// Gets or sets the lifetime of the <see cref="HttpMessageHandler"/>.
        /// </summary>
        /// <value>The lifetime of the <see cref="HttpMessageHandler"/>.</value>
        public TimeSpan HandlerLifetime
        {
            get => _handlerLifetime;
            set
            {
                if (value < SlimHttpClientFactory.ExpirationTimerDueTime) { value = SlimHttpClientFactory.ExpirationTimerDueTime; }
                _handlerLifetime = value;
            }
        }
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.mysql.fluent.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

/** The properties of a server firewall rule. */
@Fluent
public final class FirewallRuleProperties {
    @JsonIgnore private final ClientLogger logger = new ClientLogger(FirewallRuleProperties.class);

    /*
     * The start IP address of the server firewall rule. Must be IPv4 format.
     */
    @JsonProperty(value = "startIpAddress", required = true)
    private String startIpAddress;

    /*
     * The end IP address of the server firewall rule. Must be IPv4 format.
     */
    @JsonProperty(value = "endIpAddress", required = true)
    private String endIpAddress;

    /**
     * Get the startIpAddress property: The start IP address of the server firewall rule. Must be IPv4 format.
     *
     * @return the startIpAddress value.
     */
    public String startIpAddress() {
        return this.startIpAddress;
    }

    /**
     * Set the startIpAddress property: The start IP address of the server firewall rule. Must be IPv4 format.
     *
     * @param startIpAddress the startIpAddress value to set.
     * @return the FirewallRuleProperties object itself.
     */
    public FirewallRuleProperties withStartIpAddress(String startIpAddress) {
        this.startIpAddress = startIpAddress;
        return this;
    }

    /**
     * Get the endIpAddress property: The end IP address of the server firewall rule. Must be IPv4 format.
     *
     * @return the endIpAddress value.
     */
    public String endIpAddress() {
        return this.endIpAddress;
    }

    /**
     * Set the endIpAddress property: The end IP address of the server firewall rule. Must be IPv4 format.
     *
     * @param endIpAddress the endIpAddress value to set.
     * @return the FirewallRuleProperties object itself.
     */
    public FirewallRuleProperties withEndIpAddress(String endIpAddress) {
        this.endIpAddress = endIpAddress;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (startIpAddress() == null) {
            throw logger
                .logExceptionAsError(
                    new IllegalArgumentException(
                        "Missing required property startIpAddress in model FirewallRuleProperties"));
        }
        if (endIpAddress() == null) {
            throw logger
                .logExceptionAsError(
                    new IllegalArgumentException(
                        "Missing required property endIpAddress in model FirewallRuleProperties"));
        }
    }
}


text:
package org.gradle.performance.results.report;

import org.apache.commons.lang.StringUtils;
import org.gradle.api.GradleException;
import org.gradle.performance.results.FileRenderer;
import org.gradle.performance.results.NoResultsStore;
import org.gradle.performance.results.PerformanceDatabase;
import org.gradle.performance.results.PerformanceExperiment;
import org.gradle.performance.results.PerformanceReportScenario;
import org.gradle.performance.results.PerformanceTestExecutionResult;
import org.gradle.performance.results.PerformanceTestHistory;
import org.gradle.performance.results.ResultsStore;
import org.gradle.performance.results.ResultsStoreHelper;
import org.gradle.util.internal.GFileUtils;

import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static org.gradle.performance.results.report.PerformanceFlakinessDataProvider.EmptyPerformanceFlakinessDataProvider;

public abstract class AbstractReportGenerator<R extends ResultsStore> {

    protected void generateReport(String... args) {
        File outputDirectory = new File(args[0]);
        String projectName = args[1];
        List<File> resultJsons = new ArrayList<>();
        for (int i = 2; i < args.length; i++) {
            resultJsons.add(new File(args[i]));
        }

        Set<String> performanceTestBuildIds = new HashSet<>(Arrays.asList(System.getProperty("org.gradle.performance.dependencyBuildIds", "").split(",")));

        try (ResultsStore store = getResultsStore()) {
            PerformanceExecutionDataProvider executionDataProvider = getExecutionDataProvider(store, resultJsons, performanceTestBuildIds);
            PerformanceFlakinessDataProvider flakinessDataProvider = getFlakinessDataProvider();
            generateReport(store, flakinessDataProvider, executionDataProvider, outputDirectory, projectName);
            checkResult(flakinessDataProvider, executionDataProvider);
        } catch (IOException | ReflectiveOperationException e) {
            throw new RuntimeException(e);
        }
    }

    protected PerformanceFlakinessDataProvider getFlakinessDataProvider() {
        return EmptyPerformanceFlakinessDataProvider.INSTANCE;
    }

    protected PerformanceExecutionDataProvider getExecutionDataProvider(ResultsStore store, List<File> resultJsons, Set<String> performanceTestBuildIds) {
        return new DefaultPerformanceExecutionDataProvider(store, resultJsons, performanceTestBuildIds);
    }

    protected void generateReport(ResultsStore store, PerformanceFlakinessDataProvider flakinessDataProvider, PerformanceExecutionDataProvider executionDataProvider, File outputDirectory, String projectName) throws IOException {
        renderIndexPage(flakinessDataProvider, executionDataProvider, new File(outputDirectory, "index.html"));
        List<String> executedBuildIds = executionDataProvider.getReportScenarios().stream()
            .flatMap(scenario -> scenario.getTeamCityExecutions().stream().map(PerformanceTestExecutionResult::getTeamCityBuildId))
            .collect(Collectors.toList());

        executionDataProvider.getReportScenarios().stream()
            .map(PerformanceReportScenario::getPerformanceExperiment)
            .distinct()
            .forEach(experiment -> {
                PerformanceTestHistory testResults = store.getTestResults(experiment, 500, 90, ResultsStoreHelper.determineChannelPatterns(), executedBuildIds);
                renderScenarioPage(projectName, outputDirectory, testResults);
            });

        copyResource("jquery.min-3.5.1.js", outputDirectory);
        copyResource("flot-0.8.1-min.js", outputDirectory);
        copyResource("flot.selection.min.js", outputDirectory);
        copyResource("style.css", outputDirectory);
        copyResource("report.js", outputDirectory);
        copyResource("performanceGraph.js", outputDirectory);
        copyResource("performanceReport.js", outputDirectory);
    }

    protected void renderIndexPage(PerformanceFlakinessDataProvider flakinessDataProvider, PerformanceExecutionDataProvider executionDataProvider, File output) throws IOException {
        new FileRenderer().render(null, new IndexPageGenerator(flakinessDataProvider, executionDataProvider), output);
    }

    protected void checkResult(PerformanceFlakinessDataProvider flakinessDataProvider, PerformanceExecutionDataProvider executionDataProvider) {
        boolean onlyOneTestExecuted = executionDataProvider.getReportScenarios().size() == 1;
        FailureCollector failureCollector = new FailureCollector();
        collectFailures(flakinessDataProvider, executionDataProvider, failureCollector);
        String resultString = onlyOneTestExecuted
            ? formatSingleResultString(executionDataProvider, failureCollector)
            : formatResultString(failureCollector);
        if (failureCollector.isFailBuild()) {
            String failedMessage = "Performance test failed" + resultString;
            if (onlyOneTestExecuted) {
                System.out.println("##teamcity[buildStatus text='" + failedMessage + "']");
            }
            throw new GradleException(failedMessage);
        }
        String successMessage = "Performance test passed" + resultString;
        System.out.println(successMessage);
        markBuildAsSuccessful(successMessage);
    }

    protected abstract void collectFailures(PerformanceFlakinessDataProvider flakinessDataProvider, PerformanceExecutionDataProvider executionDataProvider, FailureCollector failureCollector);

    private void markBuildAsSuccessful(String successMessage) {
        System.out.println("##teamcity[buildStatus status='SUCCESS' text='" + successMessage + "']");
    }

    private String formatResultString(FailureCollector failureCollector) {
        StringBuilder sb = new StringBuilder();
        if (failureCollector.getBuildFailures() != 0) {
            sb.append(", ").append(failureCollector.getBuildFailures()).append(" scenario(s) failed");
        }
        if (failureCollector.getRegressedScenarios() != 0) {
            sb.append(", ").append(failureCollector.getRegressedScenarios()).append(" stable scenario(s) regressed");
        }
        if (failureCollector.getFlakyScenarioBigRegressions() != 0) {
            sb.append(", ").append(failureCollector.getFlakyScenarioBigRegressions()).append(" flaky scenario(s) regressed badly");
        }

        if (failureCollector.getFlakyScenarioSmallRegressions() != 0) {
            sb.append(", ").append(failureCollector.getFlakyScenarioSmallRegressions()).append(" flaky scenarios(s) regressed slightly");
        }

        sb.append('.');
        return sb.toString();
    }

    private String formatSingleResultString(PerformanceExecutionDataProvider executionDataProvider, FailureCollector failureCollector) {
        PerformanceExperiment performanceExperiment = executionDataProvider.getReportScenarios().first().getPerformanceExperiment();
        String messageTemplate;
        if (failureCollector.getBuildFailures() != 0) {
            messageTemplate = ", scenario %s failed.";
        } else if (failureCollector.getRegressedScenarios() != 0) {
            messageTemplate = ", stable scenario %s regressed.";
        } else if (failureCollector.getFlakyScenarioBigRegressions() != 0) {
            messageTemplate = ", flaky scenario %s regressed badly.";
        } else if (failureCollector.getFlakyScenarioSmallRegressions() != 0) {
            messageTemplate = ", flaky scenario %s regressed slightly.";
        } else {
            messageTemplate = ", scenario %s succeeded.";
        }
        return String.format(messageTemplate, performanceExperiment.getDisplayName());
    }

    protected void renderScenarioPage(String projectName, File outputDirectory, PerformanceTestHistory testResults) {
        FileRenderer fileRenderer = new FileRenderer();
        TestPageGenerator testHtmlRenderer = new TestPageGenerator(projectName);
        TestDataGenerator testDataRenderer = new TestDataGenerator();
        try {
            fileRenderer.render(testResults, testHtmlRenderer, new File(outputDirectory, "tests/" + testResults.getId() + ".html"));
            fileRenderer.render(testResults, testDataRenderer, new File(outputDirectory, "tests/" + testResults.getId() + ".json"));
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    protected ResultsStore getResultsStore() throws ReflectiveOperationException {
        if (!PerformanceDatabase.isAvailable()) {
            return NoResultsStore.getInstance();
        }
        Type superClass = getClass().getGenericSuperclass();
        Class<? extends ResultsStore> resultsStoreClass = (Class<R>) ((ParameterizedType) superClass).getActualTypeArguments()[0];
        return resultsStoreClass.getConstructor().newInstance();
    }

    protected void copyResource(String resourceName, File outputDirectory) {
        URL resource = getClass().getClassLoader().getResource("org/gradle/reporting/" + resourceName);
        String dir = StringUtils.substringAfterLast(resourceName, ".");
        GFileUtils.copyURLToFile(resource, new File(outputDirectory, dir + "/" + resourceName));
    }

    public static class FailureCollector {
        private int buildFailures = 0;
        private int regressedScenarios = 0;
        private int flakyScenarioBigRegressions = 0;
        private int flakyScenarioSmallRegressions = 0;
        private boolean failBuild;

        public void scenarioFailed() {
            buildFailures++;
            failBuild = true;
        }

        public void scenarioRegressed() {
            regressedScenarios++;
            failBuild = true;
        }

        public void flakyScenarioWithBigRegression() {
            flakyScenarioBigRegressions++;
            failBuild = true;
        }

        public void flakyScenarioWithSmallRegression() {
            flakyScenarioSmallRegressions++;
        }

        public boolean isFailBuild() {
            return failBuild;
        }

        public int getBuildFailures() {
            return buildFailures;
        }

        public int getRegressedScenarios() {
            return regressedScenarios;
        }

        public int getFlakyScenarioBigRegressions() {
            return flakyScenarioBigRegressions;
        }

        public int getFlakyScenarioSmallRegressions() {
            return flakyScenarioSmallRegressions;
        }
    }
}


text:
AddressBase-Premium is provided to HMRC according to the following agreed process. OS-GB provide a Webdav server containing files to be collected by HMRC automatically.

Overall, the following text describes the existing process offered by OS-GB in issuing AddressBase, with added specialisation to allow reliable automation of the file transfer.

## Requirements

Operating the process is must take little or no effort. The process must be resistant to human-induced errors; therefore it will be fully automatic (or as near fully automatic as possible). Therefore

1. The data on the webdav server must be self-describing. This will ensure that different products and/or versions don't get mixed up.

2. The data will consist of some rather large files. Therefore transfers will take a moderate amount of time and the transfer process must be resistant to race conditions.

3. The downloading software must ensure that there will not be any concurrent downloads that are able to corrupt any data due to the concurrency. (Perhaps this might be ensured by preventing more than one download at a time.)

4. Broadly, the process must be simple enough that it is easy to alter or enhance should future needs arise.

5. There is no particular need for high performance because this operates as a background batch function. Suffice it to say that excessively wasteful repetitiveness or high latencies are unwanted.

## Specification

1. There is a webdav server provided by OS-GB; HMRC will download data from it automatically.

2. There are several datasets held on the server.

3. Each dataset has a version history. Each version is called an epoch. Each epoch is indicated by a number that always increases over time.

4. We differentiate between 'full' product supply (i.e. the entire dataset) and change-only updates. In the current implementation, only full supply is supported.

### Directories

1. Each product is containined in a top-level folder with a suitable name. More products may be added later at this level. For now, the products are

    * **abp** – Addressbase GB (England, Scotland, Wales)
    * **abi** – Addressbase Islands (NI, IoM, Guernsey, Jersey)

2. Each product directory contains one or more epoch datasets. The epoch is a number, as mentioned above.

3. Each epoch contains the supply type. We only implement '**full**' supply at the moment.

In summary, the naming pattern is "**product/epoch/variant**", for example: `abp/41/full`

### Content

1. Each new dataset is copied into the new 'full' folder, named as above. This may contain subdirectories, for example "data", "doc" and "resources".

2. The primary datafiles are CSV documents that are zipped. The filenames end with `.zip`. The names of the files must be such that, when sorted alphabetically and processed in that order, the sequence of the contained data will be delivered in the intended sequence. The details of the contained data are described in the AddressBase-Premium Technical Specification.

3. When upload of all the files of a dataset is complete, an empty marker file is created called `ready-to-collect.txt`. This must be within the 'full' folder. It must not be present until the upload has fully completed, so that race conditions are prevented.

4. Besides the files described above, it is possible for there to be other files or folders in any of the folders; they will essentially be ignored by download software.

5. When a new epoch is uploaded, no changes will be made to older epochs, except that the oldest epochs may be culled (deleted). Typically, the server will contain the current epoch and the previous epoch for every product.

### Remarks

It may be obvious from the above that incomplete uploads will be ignored by the downloader; only when the `ready-to-collect.txt` file is present can download commence.

### Example Directory Structure

The structure might look like this, which illustrates one epoch of 'abi' and two of 'abp', all of them are ready to collect.

```
/
  abi/
    42/
      full/
        ... lots of zipped csv files
        ready-to-collect.txt

  abp/
    41/
      full/
        data/
          ... lots of zipped csv files
        doc/
          ... anything here you want
        resources/
          ... metadata
        ready-to-collect.txt
    42/
      full/
        data/
          ... lots of zipped csv files
        doc/
          ... anything here you want
        resources/
          ... metadata
        ready-to-collect.txt
```

In this example, the abi folder above does not have subdirectories, whereas the other two products do - this is quite acceptable.


text:
package com.twitter.finagle.netty4.proxy

import com.twitter.finagle.{ChannelClosedException, ProxyConnectException}
import com.twitter.finagle.client.Transporter
import com.twitter.finagle.client.Transporter.Credentials
import com.twitter.finagle.netty4.channel.BufferingChannelOutboundHandler
import com.twitter.finagle.netty4.channel.ConnectPromiseDelayListeners._
import com.twitter.util.Base64StringEncoder
import io.netty.channel._
import io.netty.handler.codec.http._
import io.netty.util.ReferenceCountUtil
import io.netty.util.concurrent.{GenericFutureListener, Future => NettyFuture}
import java.nio.charset.StandardCharsets.UTF_8
import java.net.SocketAddress

/**
 * An internal handler that upgrades the pipeline to delay connect-promise satisfaction until the
 * remote HTTP proxy server is ready to proxy traffic to an ultimate destination represented as
 * `host` (i.e., HTTP proxy connect procedure is successful).
 *
 * This enables "Tunneling TCP-based protocols (i.e., TLS/SSL) through Web proxy servers" [1] and
 * may be used with any TCP traffic, not only HTTP(S). See Squid documentation on this feature [2].
 *
 * @note We don't use Netty's implementation [3] here because it supports an opposite direction: the
 *       destination passed to `Channel.connect` is an ultimate target and the `HttpProxyHandler`
 *       is supposed to replace it with proxy addr (represented as a `SocketAddress`). This is the
 *       exact approach we used for Netty 3 implementation, but we don't do that anymore because we
 *       don't want to bypass Finagle's load balancers while resolving the proxy endpoint.
 *
 * @note This mixes in a [[BufferingChannelOutboundHandler]] so we can protect ourselves from
 *       channel handlers that write on `channelAdded` or `channelActive`.
 *
 * [1]: https://tools.ietf.org/html/draft-luotonen-web-proxy-tunneling-01
 * [2]: https://wiki.squid-cache.org/Features/HTTPS
 * [3]: https://github.com/netty/netty/blob/4.1/handler-proxy/src/main/java/io/netty/handler/proxy/HttpProxyHandler.java
 *
 * @param host the ultimate host a remote proxy server connects to
 *
 * @param credentialsOption optional credentials for a proxy server
 */
private[netty4] class HttpProxyConnectHandler(
  host: String,
  credentialsOption: Option[Transporter.Credentials],
  httpClientCodec: ChannelHandler = new HttpClientCodec()) // exposed for testing
    extends ChannelDuplexHandler
    with BufferingChannelOutboundHandler { self =>

  private[this] final def httpCodecKey = "httpProxyClientCodec"

  private[this] var connectPromise: ChannelPromise = _
  private[this] var proxyResponseStatus: HttpResponseStatus = _

  private[this] final def proxyAuthorizationHeader(c: Credentials): String = {
    val bytes = "%s:%s".format(c.username, c.password).getBytes(UTF_8)
    "Basic " + Base64StringEncoder.encode(bytes)
  }

  private[this] final def fail(t: Throwable): Unit = {
    // We "try" because it might be already cancelled and we don't need to handle
    // cancellations here - it's already done by `proxyCancellationsTo`.
    connectPromise.tryFailure(t)
    failPendingWrites(t)
  }

  override def connect(
    ctx: ChannelHandlerContext,
    remote: SocketAddress,
    local: SocketAddress,
    promise: ChannelPromise
  ): Unit = {
    val proxyConnectPromise = ctx.newPromise()

    // Cancel new promise if an original one is canceled.
    // NOTE: We don't worry about cancelling/failing pending writes here since it will happen
    // automatically on channel closure.
    promise.addListener(proxyCancellationsTo(proxyConnectPromise, ctx))

    // Fail old promise if a new one is failed.
    proxyConnectPromise.addListener(new GenericFutureListener[NettyFuture[Any]] {
      override def operationComplete(f: NettyFuture[Any]): Unit =
        if (f.isSuccess) {
          // Add HTTP client codec so we can talk to an HTTP proxy.
          ctx.pipeline().addBefore(ctx.name(), httpCodecKey, httpClientCodec)

          // Create new connect HTTP proxy connect request.
          val req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.CONNECT, host)
          req.headers().set(HttpHeaderNames.HOST, host)
          credentialsOption.foreach(c =>
            req.headers().add(HttpHeaderNames.PROXY_AUTHORIZATION, proxyAuthorizationHeader(c)))

          ctx.writeAndFlush(req)
          readIfNeeded(ctx)
        } else {
          // The connect request was cancelled or failed so the channel was never active. Since no
          // writes are expected from the previous handler, no need to fail the pending writes.
          if (!f.isCancelled) {
            promise.setFailure(f.cause())
          }
        }
    })

    // We propagate the pipeline with a new promise thereby delaying the original connect's
    // satisfaction.
    connectPromise = promise
    ctx.connect(remote, local, proxyConnectPromise)
  }

  override def channelRead(ctx: ChannelHandlerContext, msg: Any): Unit = {
    def finishOrRead(o: HttpObject): Unit = {
      ReferenceCountUtil.release(o)

      if (o.isInstanceOf[LastHttpContent]) finishProxyHandshake(ctx)
      else readIfNeeded(ctx)
    }

    msg match {
      case rep: HttpResponse =>
        // The first portion of a response has arrived so we capture the status.
        proxyResponseStatus = rep.status()
        finishOrRead(rep)

      case chunk: HttpContent =>
        // Some proxy servers send their error messages as HTML formatted documents so
        // we need to swallow them.
        finishOrRead(chunk)

      case other => ctx.fireChannelRead(other)
    }
  }

  override def exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable): Unit = {
    fail(cause)
    ctx.fireExceptionCaught(cause) // we don't call super.exceptionCaught since we've already filed
    // both connect promise and pending writes in `fail`
    ctx.close() // close a channel since we've failed to perform an HTTP proxy handshake
  }

  override def channelInactive(ctx: ChannelHandlerContext): Unit = {
    fail(new ChannelClosedException(ctx.channel().remoteAddress()))
    ctx.fireChannelInactive()
  }

  private[this] final def finishProxyHandshake(ctx: ChannelHandlerContext): Unit = {
    // A remote HTTP proxy is ready to proxy traffic to an ultimate destination. We no longer
    // need HTTP proxy pieces in the pipeline.
    if (proxyResponseStatus == HttpResponseStatus.OK) {
      ctx.pipeline().remove(httpCodecKey)
      ctx.pipeline().remove(self) // drains pending writes when removed

      connectPromise.trySuccess()
    } else {
      val failure =
        new ProxyConnectException(
          s"Unexpected status returned from an HTTP proxy server: $proxyResponseStatus.",
          ctx.channel().remoteAddress()
        )

      fail(failure)
      ctx.close()
    }
  }

  private[this] final def readIfNeeded(ctx: ChannelHandlerContext): Unit = {
    // We issue a read request if auto-read is disabled.
    if (!ctx.channel().config().isAutoRead) {
      ctx.read()
    }
  }
}


text:
package org.remdev.android.commander.services.handlers;

import android.os.Bundle;
import android.os.ResultReceiver;
import android.support.annotation.NonNull;

import org.remdev.android.commander.models.InteractionResult;
import org.remdev.android.commander.models.MessageBundle;
import org.remdev.timlog.Log;
import org.remdev.timlog.LogFactory;

public abstract class CommandsHandler extends AbstractCommandsHandler {

    private static final Log log = LogFactory.create(CommandsHandler.class);

    protected abstract InteractionResult executeCommand(int deviceCommand, Bundle data);

    protected Runnable createTask(final int deviceCommand, final ResultReceiver resultReceiver, Bundle data) {
        log.d("Creating task for command: %s", deviceCommand);
        return generateTask(deviceCommand, resultReceiver, data);
    }

    @NonNull
    private Runnable generateTask(final int deviceCommand, final ResultReceiver resultReceiver, final Bundle data) {
        return new Runnable() {
            @Override
            public void run() {
                InteractionResult payload = executeCommand(deviceCommand, data);
                if (payload == null) {
                    return;
                }
                resultReceiver.send(payload.getCode(), MessageBundle.build(deviceCommand, payload).toBundle());
            }
        };
    }
}


text:
package org.aesh.command.container;

import org.aesh.command.Command;
import org.aesh.command.impl.internal.ProcessedCommand;
import org.aesh.command.impl.parser.CommandLineParser;
import org.aesh.command.validator.OptionValidatorException;
import org.aesh.readline.AeshContext;
import org.aesh.command.invocation.InvocationProviders;
import org.aesh.command.CommandException;
import org.aesh.command.invocation.CommandInvocation;
import org.aesh.command.parser.CommandLineParserException;
import org.aesh.command.validator.CommandValidatorException;
import org.aesh.command.CommandResult;
import org.aesh.parser.ParsedLine;

import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @author Ståle W. Pedersen
 */
public abstract class DefaultCommandContainer<CI extends CommandInvocation> implements CommandContainer<CI> {

    private final ConcurrentLinkedQueue<ParsedLine> lines;

    public DefaultCommandContainer() {
        lines = new ConcurrentLinkedQueue<>();
    }

    @Override
    public void addLine(ParsedLine aeshLine) {
        lines.add(aeshLine);
    }

    @Override
    public ParsedLine pollLine() {
        return lines.poll();
    }

    @Override
    public void emptyLine() {
        lines.clear();
    }

    @Override
    public ProcessedCommand<Command<CI>, CI> parseAndPopulate(InvocationProviders invocationProviders,
                                                              AeshContext aeshContext)
            throws CommandLineParserException, OptionValidatorException {
        if(lines.isEmpty())
            return null;
        ParsedLine aeshLine = lines.poll();
        getParser().parse(aeshLine.iterator(), CommandLineParser.Mode.STRICT);
        if (getParser().getProcessedCommand().parserExceptions().size() > 0) {
            throw getParser().getProcessedCommand().parserExceptions().get(0);
        }
        getParser().parsedCommand().getCommandPopulator().populateObject(getParser().parsedCommand().getProcessedCommand(),
                invocationProviders, aeshContext, CommandLineParser.Mode.VALIDATE);
        return getParser().parsedCommand().getProcessedCommand();
    }

    @Override
    public CommandContainerResult executeCommand(ParsedLine line, InvocationProviders invocationProviders,
                                                 AeshContext aeshContext,
                                                 CI commandInvocation)
            throws CommandLineParserException, OptionValidatorException, CommandValidatorException, CommandException, InterruptedException {

        getParser().parse(line.iterator(), CommandLineParser.Mode.STRICT);
        return executeCommand(invocationProviders, aeshContext, commandInvocation);
    }

    private CommandContainerResult executeCommand(InvocationProviders invocationProviders,
            AeshContext aeshContext,
            CI commandInvocation)
            throws CommandLineParserException, OptionValidatorException, CommandValidatorException, CommandException, InterruptedException {

        getParser().parsedCommand().getCommandPopulator().populateObject(getParser().parsedCommand().getProcessedCommand(), invocationProviders, aeshContext, CommandLineParser.Mode.VALIDATE);
        if (getParser().parsedCommand().getProcessedCommand().validator() != null  && !getParser().parsedCommand().getProcessedCommand().hasOptionWithOverrideRequired()) {
            getParser().parsedCommand().getProcessedCommand().validator().validate(getParser().parsedCommand().getCommand());
        }

        CommandResult result = getParser().parsedCommand().getCommand().execute(commandInvocation);

        return new CommandContainerResult(getParser().parsedCommand().getProcessedCommand().resultHandler(), result);
    }

    @Override
    public String printHelp(String childCommandName) {
       if(getParser().isGroupCommand() && childCommandName.contains(" ")) {
           String[] names = childCommandName.split(" ");
           if(names.length > 1 && names[1].length() > 0) {
               CommandLineParser current = getParser();
               for(int i = 1; i < names.length; i++) {
                   CommandLineParser child = current.getChildParser(names[i]);
                   if(child != null) {
                       if(child.isGroupCommand()) {
                           current = child;
                       }
                       else
                           return child.printHelp();
                   }

               }
          }
           return "Child command "+names[1]+" not found.";
       }
       else
           return getParser().printHelp();
    }
}