text:
package ch.ethz.globis.tinspin.util.rmi;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.rmi.ConnectException;
import java.rmi.NotBoundException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class TestProcessLauncher implements Runnable {

	private final Process process;

	private TestProcessLauncher(Process process) {
		this.process = process;
	}

	public static Process launchProcess(String optionsAsString, Class<?> mainClass,
			String[] arguments) {
		try {
			ProcessBuilder processBuilder = createProcess(optionsAsString, mainClass, arguments);
			processBuilder.redirectErrorStream(true);
			Process prc = processBuilder.start();
			TestProcessLauncher l = new TestProcessLauncher(prc);

			//output monitor thread
			new Thread(l).start();

			return prc;
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	private static ProcessBuilder createProcess(String optionsAsString, Class<?> cls,
			String[] arguments) {
		String jvm =
				System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
		String cp = System.getProperty("java.class.path");

		String[] options = optionsAsString.split(" ");
		List<String> command = new ArrayList <>();
		command.add(jvm);
		command.addAll(Arrays.asList(options));
		command.add(cls.getName());
		command.addAll(Arrays.asList(arguments));

		ProcessBuilder processBuilder = new ProcessBuilder(command);
		Map< String, String > environment = processBuilder.environment();
		environment.put("CLASSPATH", cp);
		return processBuilder;
	}

	public static void launchRmiRegistry() {
		//check if it exists
		try {
			Registry registry = LocateRegistry.getRegistry();
			registry.lookup("Hello");
		} catch (ConnectException e) {
			//that's fine, that means we need to start it
		} catch (NotBoundException e) {
			//that's fine, that means it's running
			System.out.println("Found RMI process already running");
			return;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}

		try {
			ProcessBuilder processBuilder = createRmiProcess();
			processBuilder.redirectErrorStream(true);
			Process prc = processBuilder.start();
			TestProcessLauncher l = new TestProcessLauncher(prc);

			//output monitor thread
			new Thread(l).start();

			System.out.println("Waiting for RMI to start");
			for (int i = 0; i < 5; i++) {
				Thread.sleep(1000);
				//TODO we could try a rebind here an stop sleeping if it succeeds
//				if (prc.isAlive()) {
//					break;
//				}
//				System.out.println("WPPPP" + i);
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		} catch (InterruptedException e) {
			Thread.currentThread().interrupt();
		}
	}

	private static ProcessBuilder createRmiProcess() {
		String cmd = System.getProperty("java.home") +
				File.separator + "bin" + File.separator + "rmiregistry";
		String cp = System.getProperty("java.class.path");

		List<String> command = new ArrayList <>();
		command.add(cmd);

		ProcessBuilder processBuilder = new ProcessBuilder(command);
		Map< String, String > environment = processBuilder.environment();
		environment.put("CLASSPATH", cp);
		return processBuilder;
	}

	@Override
	public void run() {
		try {
			InputStream is = process.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			String line;
			while ((line = br.readLine()) != null) {
				System.out.println(line);
			}
			System.out.println("Program terminated!");
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}


text:
import sys

def get_arg(index):
    if len(sys.argv) > index:
        return sys.argv[index]
    return None

def get_arg_list(start_index):
    params = []
    for index in range(start_index, len(sys.argv)):
        params.append(sys.argv[index])
    return params

redpajama_set_name: RedPajamaGithub


text:
package org.jooq.lambda.fi.util.function;

import java.util.function.LongFunction;

/**
 * A {@link LongFunction} that allows for checked exceptions.
 *
 * @author Lukas Eder
 */
@FunctionalInterface
public interface CheckedLongFunction<R> {

    /**
     * Applies this function to the given argument.
     *
     * @param value the function argument
     * @return the function result
     */
    R apply(long value) throws Throwable;
}


text:
<?php

namespace Beryllium\CacheBundle\Client;

use Beryllium\CacheBundle\ClientCacheInterface;

/**
 * Completely untested and undocumented. Use at your own risk!
 *
 * Fixes appreciated!
 *
 * @uses ClientCacheInterface
 * @package
 * @version $id$
 * @author Kevin Boyd <beryllium@beryllium.ca>
 * @license See LICENSE.md
 */
class FilecacheClient implements ClientCacheInterface
{
    protected $path = null;
    public $dic = null;

    /**
     * @param string|null $path
     */
    public function __construct($path = null)
    {
        if (!empty($path) && is_dir($path) && is_writable($path)) {
            $this->path = $path;
        } else {
            $this->path = null;
        }
    }

    /**
     * @param $dic
     */
    public function setContainer($dic)
    {
        $this->dic = $dic;
    }

    /**
     * @param string $key
     * @return bool|mixed
     */
    public function get($key)
    {
        if (!$this->isSafe() || empty($key)) {
            return false;
        }

        // @todo Implement multi-get
        if (file_exists($this->buildFilename($key))) {
            $file = file_get_contents($this->buildFilename($key));
            $file = unserialize($file);

            if (!is_array($file)) {
                return false;
            } else if ($file['key'] != $key) {
                return false;
            } else {
                if (time() - $file['ctime'] > $file['ttl']) {
                    return false;
                } else {
                    return unserialize($file['value']);
                }
            }
        } else {
            return false;
        }
    }

    /**
     * @param string $key
     * @param mixed $value
     * @param int $ttl
     * @return bool|int
     */
    public function set($key, $value, $ttl = 300)
    {
        $file = array(
            'key'   => $key,
            'value' => serialize($value),
            'ttl'   => $ttl,
            'ctime' => time(),
        );

        if ($this->isSafe() && !empty($key)) {
            return file_put_contents($this->buildFilename($key), serialize($file));
        }

        return false;
    }

    /**
     * @param string $key
     */
    public function delete($key)
    {
        $filename = $this->buildFilename($key);

        if (file_exists($filename)) {
            unlink($filename);
        }
    }

    /**
     * @param string $path
     * @return bool
     */
    public function setPath($path)
    {
        if (!empty($path) && is_dir($path) && is_writable($path)) {
            $this->path = $path;

            return true;
        }

        $this->path = null;

        return false;
    }

    /**
     * @return bool
     */
    public function isSafe()
    {
        if (is_null($this->path)) {
            return false;
        }

        return is_dir($this->path) && is_writable($this->path);
    }

    /**
     * @return bool
     */
    public function isFull()
    {
        //Check if the cache has exceeded its alotted size
    }

    /**
     * @param string $key
     * @return string
     */
    protected function buildFilename($key)
    {
        return $this->path . md5($key) . '_file.cache';
    }
}


text:
from __future__ import absolute_import, division, print_function

from PyQt5.QtCore import QSettings

SELECTED_THEME_DIR_KEY = 'selectedThemeDir'
FIRST_START_KEY = 'firstStart'

class Settings(object):
    def __init__(self):
        self._settings = QSettings("athre0z", "IDASkins")

    @property
    def selected_theme_dir(self):
        theme_dir = self._settings.value(SELECTED_THEME_DIR_KEY, None)
        return None if theme_dir is None else theme_dir.encode()

    @selected_theme_dir.setter
    def selected_theme_dir(self, v):
        assert isinstance(v, str)
        self._settings.setValue(SELECTED_THEME_DIR_KEY, v)

    @property
    def first_start(self):
        # PyQt seems to be returning unicode strings instead of QVariant.
        return not self._settings.value(FIRST_START_KEY, True) in [u'false', False]

    @first_start.setter
    def first_start(self, v):
        assert isinstance(v, bool)
        self._settings.setValue(FIRST_START_KEY, v)


text:
<?php

/**
 * Paydirekt request class
 */
class zsPaydirektPaydirektRequest
{
    /**
     * Paydirekt response data
     *
     * @var array
     */
    protected $_aData = array();

    /**
     * Sets value to data by given key.
     *
     * @param string $sKey   Key of data value.
     * @param string $sValue Data value.
     */
    public function setParameter($sKey, $sValue)
    {
        $this->_aData[$sKey] = $sValue;
    }

    /**
     * Returns value by given key.
     *
     * @param string $sKey Key of data value.
     *
     * @return string
     */
    public function getParameter($sKey)
    {
        return $this->_aData[$sKey];
    }

    /**
     * Set request data.
     *
     * @param array $aResponseData Response data from Paydirekt.
     */
    public function setData($aResponseData)
    {
        $this->_aData = $aResponseData;
    }

    /**
     * Return request data.
     *
     * @return array
     */
    public function getData()
    {
        return $this->_aData;
    }

    /**
     * Return value from data by given key.
     *
     * @param string $sKey   Key of data value.
     * @param string $sValue Data value.
     */
    protected function _setValue($sKey, $sValue)
    {
        $this->_aData[$sKey] = $sValue;
    }
}


text:
Automatically creates Phaser simple load commands from a directory of assets.

## Quick-Start Guide
1. Install Node.js
2. Open empty directory and install Grunt with `npm install grunt --save-dev`
3. Put the Gruntfile.js and package.json files into that directory
4. Create a folder called 'assets' in the same directory and put all of your images, sounds, spritesheets in there. The internal structure of the asset folder doesn't matter. The script will find all the files and their corresponding paths.
5. Open a command line in that directory and run `grunt ` or `grunt default` (it does the same thing)
6. If all went right, you should see a green "Done, without errors" message in the log.
7. There should be a directory called dest with a .js file with all the Phaser commands. Copy that into your game and get coding. =)


text:
/*****************************************************************************/
/*  Copyright (c) 2016, Alessandro Pieropan                                  */
/*  All rights reserved.                                                     */
/*                                                                           */
/*  Redistribution and use in source and binary forms, with or without       */
/*  modification, are permitted provided that the following conditions       */
/*  are met:                                                                 */
/*                                                                           */
/*  1. Redistributions of source code must retain the above copyright        */
/*  notice, this list of conditions and the following disclaimer.            */
/*                                                                           */
/*  2. Redistributions in binary form must reproduce the above copyright     */
/*  notice, this list of conditions and the following disclaimer in the      */
/*  documentation and/or other materials provided with the distribution.     */
/*                                                                           */
/*  3. Neither the name of the copyright holder nor the names of its         */
/*  contributors may be used to endorse or promote products derived from     */
/*  this software without specific prior written permission.                 */
/*                                                                           */
/*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS      */
/*  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT        */
/*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR    */
/*  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT     */
/*  HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,   */
/*  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT         */
/*  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,    */
/*  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY    */
/*  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT      */
/*  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE    */
/*  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.     */
/*****************************************************************************/
#ifndef GL_INTEROP_H
#define GL_INTEROP_H

#include <cuda_runtime.h>
#include <stdexcept>
#include <iostream>
#include <stdexcept>

namespace fato {
namespace gpu {

typedef unsigned char uchar;

void downloadDepthTexture(float *d_out_image, cudaArray *in_array, int width,
                          int height);

void downloadTextureToRGBA(uchar4 *d_out_image, cudaArray *in_array, int width,
                           int height) ;

void convertRGBArrayToGrayVX(uchar *d_out_image, cudaArray *in_array,
                             int width, int height, int step);

std::runtime_error cudaException(const char* file, int line,
                                 cudaError_t error);

} // end of namespace
} // end fato

#endif  // GL_INTEROP_H


text:
package pgbouncer

import (
	"bytes"
	"strconv"

	"github.com/influxdata/telegraf"
	"github.com/influxdata/telegraf/config"
	"github.com/influxdata/telegraf/plugins/inputs"
	"github.com/influxdata/telegraf/plugins/inputs/postgresql"
	_ "github.com/jackc/pgx/v4/stdlib" // register driver
)

type PgBouncer struct {
	postgresql.Service
}

var ignoredColumns = map[string]bool{"user": true, "database": true, "pool_mode": true,
	"avg_req": true, "avg_recv": true, "avg_sent": true, "avg_query": true,
}

func (p *PgBouncer) Gather(acc telegraf.Accumulator) error {
	var (
		err     error
		query   string
		columns []string
	)

	query = `SHOW STATS`

	rows, err := p.DB.Query(query)
	if err != nil {
		return err
	}

	defer rows.Close()

	// grab the column information from the result
	if columns, err = rows.Columns(); err != nil {
		return err
	}

	for rows.Next() {
		tags, columnMap, err := p.accRow(rows, columns)

		if err != nil {
			return err
		}

		fields := make(map[string]interface{})
		for col, val := range columnMap {
			_, ignore := ignoredColumns[col]
			if ignore {
				continue
			}

			switch v := (*val).(type) {
			case int64:
				// Integer fields are returned in pgbouncer 1.5 through 1.9
				fields[col] = v
			case string:
				// Integer fields are returned in pgbouncer 1.12
				integer, err := strconv.ParseInt(v, 10, 64)
				if err != nil {
					return err
				}

				fields[col] = integer
			}
		}
		acc.AddFields("pgbouncer", fields, tags)
	}

	err = rows.Err()
	if err != nil {
		return err
	}

	query = `SHOW POOLS`

	poolRows, err := p.DB.Query(query)
	if err != nil {
		return err
	}

	defer poolRows.Close()

	// grab the column information from the result
	if columns, err = poolRows.Columns(); err != nil {
		return err
	}

	for poolRows.Next() {
		tags, columnMap, err := p.accRow(poolRows, columns)
		if err != nil {
			return err
		}

		if user, ok := columnMap["user"]; ok {
			if s, ok := (*user).(string); ok && s != "" {
				tags["user"] = s
			}
		}

		if poolMode, ok := columnMap["pool_mode"]; ok {
			if s, ok := (*poolMode).(string); ok && s != "" {
				tags["pool_mode"] = s
			}
		}

		fields := make(map[string]interface{})
		for col, val := range columnMap {
			_, ignore := ignoredColumns[col]
			if !ignore {
				fields[col] = *val
			}
		}
		acc.AddFields("pgbouncer_pools", fields, tags)
	}

	return poolRows.Err()
}

type scanner interface {
	Scan(dest ...interface{}) error
}

func (p *PgBouncer) accRow(row scanner, columns []string) (map[string]string,
	map[string]*interface{}, error) {
	var columnVars []interface{}
	var dbname bytes.Buffer

	// this is where we'll store the column name with its *interface{}
	columnMap := make(map[string]*interface{})

	for _, column := range columns {
		columnMap[column] = new(interface{})
	}

	// populate the array of interface{} with the pointers in the right order
	for i := 0; i < len(columnMap); i++ {
		columnVars = append(columnVars, columnMap[columns[i]])
	}

	// deconstruct array of variables and send to Scan
	err := row.Scan(columnVars...)

	if err != nil {
		return nil, nil, err
	}
	if columnMap["database"] != nil {
		// extract the database name from the column map
		if _, err := dbname.WriteString((*columnMap["database"]).(string)); err != nil {
			return nil, nil, err
		}
	} else {
		if _, err := dbname.WriteString("postgres"); err != nil {
			return nil, nil, err
		}
	}

	var tagAddress string
	tagAddress, err = p.SanitizedAddress()
	if err != nil {
		return nil, nil, err
	}

	// Return basic tags and the mapped columns
	return map[string]string{"server": tagAddress, "db": dbname.String()}, columnMap, nil
}

func init() {
	inputs.Add("pgbouncer", func() telegraf.Input {
		return &PgBouncer{
			Service: postgresql.Service{
				MaxIdle:     1,
				MaxOpen:     1,
				MaxLifetime: config.Duration(0),
				IsPgBouncer: true,
			},
		}
	})
}


text:
<#
 .Synopsis
 Selects only certain fields from the input

 .Inputs
 psobject/any

 .Outputs
 psobject/any

 .Example
 ConvertFrom-Json '{"a": "foo", "b": 2, "c": 3}' | .\SelectFields.ps1 -Fields "a", "b"
 Take an object '{a: "foo", b: 2, c: 3}' and return properties/fields "a" and "b" => '{a: "foo", b: 2}'
#>
[OutputType([Object])]
param(
  [Parameter(ValueFromPipeline)][Object]$InputObject,
  [String[]]$Fields
)

$input | Select-Object -Property $Fields


text:
namespace Aliyun.OSS
{
    /// <summary>
    /// Sign HTTP method enum definition
    /// </summary>
    public enum SignHttpMethod
    {
        /// <summary>
        /// Represents HTTP GET. Default value.
        /// </summary>
        Get = 0,

        /// <summary>
        /// Represents HTTP DELETE.
        /// </summary>
        Delete,

        /// <summary>
        /// Represents HTTP HEAD.
        /// </summary>
        Head,

        /// <summary>
        /// Represents HTTP POST.
        /// </summary>
        Post,

        /// <summary>
        /// Represents HTTP PUT.
        /// </summary>
        Put,
    }
}


text:
`npm install find-youtube-urls --save`

```
var findYoutubeUrls = require("./index.js");

var string = "https://www.youtube.com/watch?v=gK87eRlyk7U";

var youtubeUrls = findYoutubeUrls(string);
// youtubeUrls = ["https://www.youtube.com/watch?v=gK87eRlyk7U"];
```

## Development

`npm install`

`gulp watch-test`

## Test
`gulp test`


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateRequestLineItemsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('request_line_items', function (Blueprint $table) {
            $table->increments('id');
            $table->longText('line_item_description')->nullable();
            $table->longText('lump_sum')->nullable();
            $table->string('order')->nullable();
            $table->string('option_flag')->nullable();

            $table->integer('request_id')->unsigned();

            $table->foreign('request_id')
                ->references('id')->on('requests')
                ->onDelete('cascade');

            $table->integer('creator_id')->unsigned();

            $table->foreign('creator_id')
                ->references('id')->on('users')
                ->onDelete('cascade');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('request_line_items');
    }
}


text:
namespace base {
class FilePath;
}

namespace media {

// Manages all CDM host files.
class MEDIA_EXPORT CdmHostFiles {
 public:
  CdmHostFiles();

  CdmHostFiles(const CdmHostFiles&) = delete;
  CdmHostFiles& operator=(const CdmHostFiles&) = delete;

  ~CdmHostFiles();

  // Opens all common files and CDM specific files for the CDM at |cdm_path|.
  void Initialize(const base::FilePath& cdm_path,
                  const std::vector<CdmHostFilePath>& cdm_host_file_paths);

  // Status of CDM host verification.
  // Note: Reported to UMA. Do not change the values.
  enum class Status {
    kNotCalled = 0,
    kSuccess = 1,
    kCdmLoadFailed = 2,
    kGetFunctionFailed = 3,
    kInitVerificationFailed = 4,
    kStatusCount
  };

  // Initializes the verification of CDM files by calling the function exported
  // by the CDM. If unexpected error happens, all files will be closed.
  // Otherwise, the PlatformFiles are passed to the CDM which will close the
  // files later.
  // NOTE: Initialize() must be called before calling this.
  Status InitVerification(base::NativeLibrary cdm_library);

  void CloseAllFiles();

 private:
  // Opens common CDM host files shared by all CDMs.
  void OpenCommonFiles(const std::vector<CdmHostFilePath>& cdm_host_file_paths);

  // Opens the CDM file.
  void OpenCdmFile(const base::FilePath& cdm_path);

  // Fills |cdm_host_files| with common and CDM specific files. The ownership
  // of those files are also transferred.
  void TakePlatformFiles(std::vector<cdm::HostFile>* cdm_host_files);

  using ScopedFileVector = std::vector<std::unique_ptr<CdmHostFile>>;

  // Files common to all CDM types, e.g. main executable.
  ScopedFileVector common_files_;

  // Files specific to each CDM type, e.g. the CDM binary.
  ScopedFileVector cdm_specific_files_;
};

}  // namespace media

#endif  // MEDIA_CDM_CDM_HOST_FILES_H_


text:
from bs4 import BeautifulSoup
import urllib2

class SpecificationScraper(object):
    def __init__(self, url):
        self.url = url
        self.specs_soup = None
        self.specs = {}

    def download_page(self):
        if self.specs_soup is not None:
            return

        try:
            p = urllib2.urlopen(self.url, None)
            s = BeautifulSoup(p.read(), "html.parser")

            self.specs_soup = s.find(id="product-specs")
        except:
            print "Failed to download specs"

    def parse_page(self):
        self.download_page()
        try:
            for tr in self.specs_soup.find_all('tr'):
                ths = tr.find_all('th')
                self.specs[ths[0].text] = ths[1].text
        except:
            print "Unable to parse specs"


text:
<?php defined('C5_EXECUTE') or die(_("Access Denied.")); ?>
<a href="<?php echo $this->action('view') . '?courseID=' . $courseID; ?>">« <?php echo t('Course dashboard'); ?>

<?php echo $courseTitle; ?>

    <?php
    if (isset($errors)) {
        foreach ($errors as $e) {
            echo "
" . $e . "
";
        }
    }
    ?>

<?php
$vt = Loader::helper('validation/token');
?>

<?php echo t('Edit session'); ?>

                <form method="post" role="form" enctype="multipart/form-data">

                        <?php echo t('Title'); ?>
                        <input class="form-control" type="text" name="title" value="<?php echo $title; ?>" />

                            <input type="checkbox" name="isPublished" value="1"<?php
                            if ($isPublished): echo 'checked';
                            endif;
                            ?> /> <?php echo t('Is published?'); ?>

                    <?php
                    // deactivated by now, maybe used later...
                    /*

                      <?php echo t('Learner completion requires teacher approval?'); ?>
                      <select name="completionApprovalNeeded">
                      <?php foreach ($completionApprovalNeededValues as $v) { ?>
                      <option value='<?php echo $v->value; ?>' <?php
                      if ($v->value == $completionApprovalNeeded): echo 'selected';
                      endif;
                      ?>><?php echo t($v->value); ?></option>
                      <?php } ?>
                      </select>

                     *
                     */
                    ?>

                <?php print $vt->output(); ?>
                <button type="submit" class="btn btn-primary"><?php echo t('Save changes'); ?></button>

            </form>


text:
#include <folly/executors/TimedDrivableExecutor.h>

#include <cstring>
#include <ctime>
#include <string>
#include <tuple>

namespace folly {

TimedDrivableExecutor::TimedDrivableExecutor() = default;

TimedDrivableExecutor::~TimedDrivableExecutor() noexcept {
  // Drain on destruction so that if work is added here during the collapse
  // of a future train, it will propagate.
  drain();
}

void TimedDrivableExecutor::add(Func callback) {
  queue_.enqueue(std::move(callback));
}

void TimedDrivableExecutor::drive() noexcept {
  wait();
  run();
}

bool TimedDrivableExecutor::try_drive() noexcept {
  return try_wait() && run() > 0;
}

size_t TimedDrivableExecutor::run() noexcept {
  size_t count = 0;
  size_t n = queue_.size();

  // If we have waited already, then func_ may have a value
  if (func_) {
    auto f = std::move(func_);
    f();
    count = 1;
  }

  while (count < n && queue_.try_dequeue(func_)) {
    auto f = std::move(func_);
    f();
    ++count;
  }

  return count;
}

size_t TimedDrivableExecutor::drain() noexcept {
  size_t tasksRun = 0;
  size_t tasksForSingleRun = 0;
  while ((tasksForSingleRun = run()) != 0) {
    tasksRun += tasksForSingleRun;
  }
  return tasksRun;
}

void TimedDrivableExecutor::wait() noexcept {
  if (!func_) {
    queue_.dequeue(func_);
  }
}

bool TimedDrivableExecutor::try_wait() noexcept {
  return func_ || queue_.try_dequeue(func_);
}

} // namespace folly


text:
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Test file</title>

    <!-- build:css -->
    <link rel="stylesheet" href="one.css">
    <link rel="stylesheet" href="two.css">
    <!-- endbuild -->
</head>
<body>
    <!-- build:js_files -->
    <script src="uncompressed.js"></script>
    <!-- endbuild -->

<!-- build:js_files_tpl -->
<script src="uncompressed.js"></script>
<!-- endbuild -->

<!-- build:js_files_tpl_multiple -->
<script src="uncompressed.js"></script>
<!-- endbuild -->

<!-- build:js_files_tpl_2vars -->
<script data-main="main.js" src="uncompressed.js"></script>
<!-- endbuild -->

<!-- build:js_files_tpl_2vars_multiple -->
<script data-main="main.js" src="uncompressed.js"></script>
<!-- endbuild -->

<!-- build:js_files_x_tpl -->
<script src="uncompressed.js"></script>
<!-- endbuild -->

<!-- build:js_files_x_tpl_src -->
<script src="uncompressed.js"></script>
<!-- endbuild -->

<!-- build:js_files_x_tpl_multiple -->
<script src="uncompressed.js"></script>
<!-- endbuild -->

<!-- build:js_files_x_tpl_2vars -->
<script src="uncompressed.js"></script>
<!-- endbuild -->

<!-- build:js_files_x_tpl_2vars_multiple -->
<script src="uncompressed.js"></script>
<!-- endbuild -->

<!-- build:lorem-ipsum -->
<!-- endbuild -->
</body>
</html>


text:
export class TestEmitter {

    showSectionRequest($scope, sectionId) {
        var payload = {
            id: sectionId
        };
        return payload;
    }

}


text:
<?php

namespace Swarming\SubscribePro\Plugin\Quote;

use Magento\Framework\App\State as AppState;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Quote\Model\Quote\Item as QuoteItem;
use SubscribePro\Service\Product\ProductInterface as PlatformProductInterface;

class QuoteItemUpdater
{
    /**
     * @var \Swarming\SubscribePro\Platform\Manager\Product
     */
    protected $platformProductManager;

    /**
     * @var \Swarming\SubscribePro\Model\Quote\SubscriptionOption\Updater
     */
    protected $subscriptionOptionUpdater;

    /**
     * @var \Magento\Catalog\Api\ProductRepositoryInterface
     */
    protected $productRepository;

    /**
     * @var \Swarming\SubscribePro\Helper\Product
     */
    protected $productHelper;

    /**
     * @var \Magento\Framework\Message\ManagerInterface
     */
    protected $messageManager;

    /**
     * @var \Magento\Framework\App\State
     */
    protected $appState;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    /**
     * @param \Swarming\SubscribePro\Platform\Manager\Product $platformProductManager
     * @param \Swarming\SubscribePro\Model\Quote\SubscriptionOption\Updater $subscriptionOptionUpdater
     * @param \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
     * @param \Swarming\SubscribePro\Helper\Product $productHelper
     * @param \Magento\Framework\Message\ManagerInterface $messageManager
     * @param \Magento\Framework\App\State $appState
     * @param \Psr\Log\LoggerInterface $logger
     */
    public function __construct(
        \Swarming\SubscribePro\Platform\Manager\Product $platformProductManager,
        \Swarming\SubscribePro\Model\Quote\SubscriptionOption\Updater $subscriptionOptionUpdater,
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
        \Swarming\SubscribePro\Helper\Product $productHelper,
        \Magento\Framework\Message\ManagerInterface $messageManager,
        \Magento\Framework\App\State $appState,
        \Psr\Log\LoggerInterface $logger
    ) {
        $this->platformProductManager = $platformProductManager;
        $this->subscriptionOptionUpdater = $subscriptionOptionUpdater;
        $this->productRepository = $productRepository;
        $this->productHelper = $productHelper;
        $this->messageManager = $messageManager;
        $this->appState = $appState;
        $this->logger = $logger;
    }
    /**
     * @param \Magento\Quote\Model\Quote\Item\Updater $subject
     * @param \Closure $proceed
     * @param \Magento\Quote\Model\Quote\Item $item
     * @param array $info
     * @return bool
     */
    public function aroundUpdate(
        \Magento\Quote\Model\Quote\Item\Updater $subject,
        \Closure $proceed,
        \Magento\Quote\Model\Quote\Item $item,
        array $info
    ) {
        $return = $proceed($item, $info);
        $this->updateAdminQuoteItem($item, $info);
        return $return;
    }

    /**
     * @param \Magento\Quote\Model\Quote\Item $quoteItem
     * @param array $quoteItemParams
     */
    protected function updateAdminQuoteItem(QuoteItem $quoteItem, array $quoteItemParams)
    {
        if (!$this->getSubscriptionOption($quoteItemParams) || !$this->getInterval($quoteItemParams)) {
            return;
        }

        $product = $quoteItem->getProduct();
        if ($quoteItem->getParentItem() && $quoteItem->getParentItem()->getProduct()) {
            $product = $quoteItem->getParentItem()->getProduct();
        }

        if (!$this->productHelper->isSubscriptionEnabled($product)) {
            return;
        }

        $platformProduct = $this->getPlatformProduct($product, $quoteItem->getQuote()->getStore()->getWebsiteId());
        if (!$platformProduct) {
            return;
        }

        $warnings = $this->subscriptionOptionUpdater->update(
            $quoteItem,
            $platformProduct,
            $this->getSubscriptionOption($quoteItemParams),
            $this->getInterval($quoteItemParams)
        );

        foreach ($warnings as $message) {
            $this->messageManager->addWarningMessage($message);
        }
    }

    /**
     * @param \Magento\Catalog\Model\Product $product
     * @param int|null $websiteId
     * @return \Swarming\SubscribePro\Api\Data\ProductInterface|null
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    protected function getPlatformProduct($product, $websiteId = null)
    {
        try {
            $platformProduct = $this->platformProductManager->getProduct(
                $product->getData(ProductInterface::SKU),
                $websiteId
            );
        } catch (NoSuchEntityException $e) {
            if ($this->appState->getMode() === AppState::MODE_DEVELOPER) {
                throw $e;
            }
            $this->logger->critical($e->getLogMessage());
            $platformProduct = null;
        }
        return $platformProduct;
    }

    protected function getSubscriptionOption(array $quoteItemParams)
    {
        if (!isset($quoteItemParams['admin_subscription_option']['option'])
            || !strlen($quoteItemParams['admin_subscription_option']['option'])
        ) {
            return false;
        }
        return $quoteItemParams['admin_subscription_option']['option'];
    }

    protected function getInterval(array $quoteItemParams)
    {
        if (!isset($quoteItemParams['admin_subscription_option']['interval'])) {
            return false;
        }
        return $quoteItemParams['admin_subscription_option']['interval'];
    }
}


text:
layout:     post
title:      Tweets
date:       2018-07-31
summary:    These are the tweets for July 31, 2018.
categories:
---


text:
// variables defining memory layout
// (these probably belong somewhere else...)
extern uint32_t _etext;
extern uint32_t _sidata;
extern uint32_t _ram_start;
extern uint32_t _sdata;
extern uint32_t _edata;
extern uint32_t _sbss;
extern uint32_t _ebss;
extern uint32_t _heap_start;
extern uint32_t _heap_end;
extern uint32_t _estack;
extern uint32_t _ram_end;

void gc_collect_init ();


text:
#include "I2cDxe.h"

EFI_DRIVER_BINDING_PROTOCOL gI2cHostDriverBinding = {
  I2cHostDriverSupported,
  I2cHostDriverStart,
  I2cHostDriverStop,
  0x10,
  NULL,
  NULL
};

//
// Driver name table
//
GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mI2cHostDriverNameTable[] = {
  { "eng;en", L"I2c Host Driver" },
  { NULL , NULL }
};

//
// EFI Component Name Protocol
//
GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL  gI2cHostComponentName = {
  (EFI_COMPONENT_NAME_GET_DRIVER_NAME) I2cHostComponentNameGetDriverName,
  (EFI_COMPONENT_NAME_GET_CONTROLLER_NAME) I2cHostComponentNameGetControllerName,
  "eng"
};

//
// EFI Component Name 2 Protocol
//
GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gI2cHostComponentName2 = {
  I2cHostComponentNameGetDriverName,
  I2cHostComponentNameGetControllerName,
  "en"
};

/**
  Retrieves a Unicode string that is the user readable name of the driver.

  This function retrieves the user readable name of a driver in the form of a
  Unicode string. If the driver specified by This has a user readable name in
  the language specified by Language, then a pointer to the driver name is
  returned in DriverName, and EFI_SUCCESS is returned. If the driver specified
  by This does not support the language specified by Language,
  then EFI_UNSUPPORTED is returned.

  @param  This[in]              A pointer to the EFI_COMPONENT_NAME2_PROTOCOL or
                                EFI_COMPONENT_NAME_PROTOCOL instance.

  @param  Language[in]          A pointer to a Null-terminated ASCII string
                                array indicating the language. This is the
                                language of the driver name that the caller is
                                requesting, and it must match one of the
                                languages specified in SupportedLanguages. The
                                number of languages supported by a driver is up
                                to the driver writer. Language is specified
                                in RFC 4646 or ISO 639-2 language code format.

  @param  DriverName[out]       A pointer to the Unicode string to return.
                                This Unicode string is the name of the
                                driver specified by This in the language
                                specified by Language.

  @retval EFI_SUCCESS           The Unicode string for the Driver specified by
                                This and the language specified by Language was
                                returned in DriverName.

  @retval EFI_INVALID_PARAMETER Language is NULL.

  @retval EFI_INVALID_PARAMETER DriverName is NULL.

  @retval EFI_UNSUPPORTED       The driver specified by This does not support
                                the language specified by Language.

**/
EFI_STATUS
EFIAPI
I2cHostComponentNameGetDriverName (
  IN  EFI_COMPONENT_NAME2_PROTOCOL  *This,
  IN  CHAR8                        *Language,
  OUT CHAR16                       **DriverName
  )
{
  return LookupUnicodeString2 (
           Language,
           This->SupportedLanguages,
           mI2cHostDriverNameTable,
           DriverName,
           (BOOLEAN)(This != &gI2cHostComponentName2)
           );
}

/**
  Retrieves a Unicode string that is the user readable name of the controller
  that is being managed by a driver.

  This function retrieves the user readable name of the controller specified by
  ControllerHandle and ChildHandle in the form of a Unicode string. If the
  driver specified by This has a user readable name in the language specified by
  Language, then a pointer to the controller name is returned in ControllerName,
  and EFI_SUCCESS is returned.  If the driver specified by This is not currently
  managing the controller specified by ControllerHandle and ChildHandle,
  then EFI_UNSUPPORTED is returned.  If the driver specified by This does not
  support the language specified by Language, then EFI_UNSUPPORTED is returned.

  @param  This[in]              A pointer to the EFI_COMPONENT_NAME2_PROTOCOL or
                                EFI_COMPONENT_NAME_PROTOCOL instance.

  @param  ControllerHandle[in]  The handle of a controller that the driver
                                specified by This is managing.  This handle
                                specifies the controller whose name is to be
                                returned.

  @param  ChildHandle[in]       The handle of the child controller to retrieve
                                the name of.  This is an optional parameter that
                                may be NULL.  It will be NULL for device
                                drivers.  It will also be NULL for a bus drivers
                                that wish to retrieve the name of the bus
                                controller.  It will not be NULL for a bus
                                driver that wishes to retrieve the name of a
                                child controller.

  @param  Language[in]          A pointer to a Null-terminated ASCII string
                                array indicating the language.  This is the
                                language of the driver name that the caller is
                                requesting, and it must match one of the
                                languages specified in SupportedLanguages. The
                                number of languages supported by a driver is up
                                to the driver writer. Language is specified in
                                RFC 4646 or ISO 639-2 language code format.

  @param  ControllerName[out]   A pointer to the Unicode string to return.
                                This Unicode string is the name of the
                                controller specified by ControllerHandle and
                                ChildHandle in the language specified by
                                Language from the point of view of the driver
                                specified by This.

  @retval EFI_SUCCESS           The Unicode string for the user readable name in
                                the language specified by Language for the
                                driver specified by This was returned in
                                DriverName.

  @retval EFI_INVALID_PARAMETER ControllerHandle is NULL.

  @retval EFI_INVALID_PARAMETER ChildHandle is not NULL and it is not a valid
                                EFI_HANDLE.

  @retval EFI_INVALID_PARAMETER Language is NULL.

  @retval EFI_INVALID_PARAMETER ControllerName is NULL.

  @retval EFI_UNSUPPORTED       The driver specified by This is not currently
                                managing the controller specified by
                                ControllerHandle and ChildHandle.

  @retval EFI_UNSUPPORTED       The driver specified by This does not support
                                the language specified by Language.

**/
EFI_STATUS
EFIAPI
I2cHostComponentNameGetControllerName (
  IN  EFI_COMPONENT_NAME2_PROTOCOL                    *This,
  IN  EFI_HANDLE                                      ControllerHandle,
  IN  EFI_HANDLE                                      ChildHandle        OPTIONAL,
  IN  CHAR8                                           *Language,
  OUT CHAR16                                          **ControllerName
  )
{
  return EFI_UNSUPPORTED;
}

/**
  Tests to see if this driver supports a given controller. If a child device is provided,
  it further tests to see if this driver supports creating a handle for the specified child device.

  This function checks to see if the driver specified by This supports the device specified by
  ControllerHandle. Drivers will typically use the device path attached to
  ControllerHandle and/or the services from the bus I/O abstraction attached to
  ControllerHandle to determine if the driver supports ControllerHandle. This function
  may be called many times during platform initialization. In order to reduce boot times, the tests
  performed by this function must be very small, and take as little time as possible to execute. This
  function must not change the state of any hardware devices, and this function must be aware that the
  device specified by ControllerHandle may already be managed by the same driver or a
  different driver. This function must match its calls to AllocatePages() with FreePages(),
  AllocatePool() with FreePool(), and OpenProtocol() with CloseProtocol().
  Since ControllerHandle may have been previously started by the same driver, if a protocol is
  already in the opened state, then it must not be closed with CloseProtocol(). This is required
  to guarantee the state of ControllerHandle is not modified by this function.

  @param[in]  This                 A pointer to the EFI_DRIVER_BINDING_PROTOCOL instance.
  @param[in]  ControllerHandle     The handle of the controller to test. This handle
                                   must support a protocol interface that supplies
                                   an I/O abstraction to the driver.
  @param[in]  RemainingDevicePath  A pointer to the remaining portion of a device path.  This
                                   parameter is ignored by device drivers, and is optional for bus
                                   drivers. For bus drivers, if this parameter is not NULL, then
                                   the bus driver must determine if the bus controller specified
                                   by ControllerHandle and the child controller specified
                                   by RemainingDevicePath are both supported by this
                                   bus driver.

  @retval EFI_SUCCESS              The device specified by ControllerHandle and
                                   RemainingDevicePath is supported by the driver specified by This.
  @retval EFI_ALREADY_STARTED      The device specified by ControllerHandle and
                                   RemainingDevicePath is already being managed by the driver
                                   specified by This.
  @retval EFI_ACCESS_DENIED        The device specified by ControllerHandle and
                                   RemainingDevicePath is already being managed by a different
                                   driver or an application that requires exclusive access.
                                   Currently not implemented.
  @retval EFI_UNSUPPORTED          The device specified by ControllerHandle and
                                   RemainingDevicePath is not supported by the driver specified by This.
**/
EFI_STATUS
EFIAPI
I2cHostDriverSupported (
  IN EFI_DRIVER_BINDING_PROTOCOL  *This,
  IN EFI_HANDLE                   Controller,
  IN EFI_DEVICE_PATH_PROTOCOL     *RemainingDevicePath
  )
{
  EFI_I2C_MASTER_PROTOCOL                       *I2cMaster;
  EFI_I2C_BUS_CONFIGURATION_MANAGEMENT_PROTOCOL *I2cBusConfigurationManagement;
  EFI_STATUS                                    Status;

  //
  //  Locate I2C Bus Configuration Management Protocol
  //
  Status = gBS->OpenProtocol (
                  Controller,
                  &gEfiI2cBusConfigurationManagementProtocolGuid,
                  (VOID **)&I2cBusConfigurationManagement,
                  This->DriverBindingHandle,
                  Controller,
                  EFI_OPEN_PROTOCOL_BY_DRIVER
                  );
  if (EFI_ERROR (Status)) {
    return Status;
  }

  //
  // Close the protocol because we don't use it here
  //
  gBS->CloseProtocol (
                  Controller,
                  &gEfiI2cBusConfigurationManagementProtocolGuid,
                  This->DriverBindingHandle,
                  Controller
                  );

  //
  //  Locate I2C Master Protocol
  //
  Status = gBS->OpenProtocol (
                  Controller,
                  &gEfiI2cMasterProtocolGuid,
                  (VOID **)&I2cMaster,
                  This->DriverBindingHandle,
                  Controller,
                  EFI_OPEN_PROTOCOL_GET_PROTOCOL
                  );
  if (EFI_ERROR (Status)) {
    return Status;
  }

  return EFI_SUCCESS;
}

/**
  Starts a device controller or a bus controller.

  The Start() function is designed to be invoked from the EFI boot service ConnectController().
  As a result, much of the error checking on the parameters to Start() has been moved into this
  common boot service. It is legal to call Start() from other locations,
  but the following calling restrictions must be followed, or the system behavior will not be deterministic.
  1. ControllerHandle must be a valid EFI_HANDLE.
  2. If RemainingDevicePath is not NULL, then it must be a pointer to a naturally aligned
     EFI_DEVICE_PATH_PROTOCOL.
  3. Prior to calling Start(), the Supported() function for the driver specified by This must
     have been called with the same calling parameters, and Supported() must have returned EFI_SUCCESS.

  @param[in]  This                 A pointer to the EFI_DRIVER_BINDING_PROTOCOL instance.
  @param[in]  ControllerHandle     The handle of the controller to start. This handle
                                   must support a protocol interface that supplies
                                   an I/O abstraction to the driver.
  @param[in]  RemainingDevicePath  A pointer to the remaining portion of a device path.  This
                                   parameter is ignored by device drivers, and is optional for bus
                                   drivers. For a bus driver, if this parameter is NULL, then handles
                                   for all the children of Controller are created by this driver.
                                   If this parameter is not NULL and the first Device Path Node is
                                   not the End of Device Path Node, then only the handle for the
                                   child device specified by the first Device Path Node of
                                   RemainingDevicePath is created by this driver.
                                   If the first Device Path Node of RemainingDevicePath is
                                   the End of Device Path Node, no child handle is created by this
                                   driver.

  @retval EFI_SUCCESS              The device was started.
  @retval EFI_DEVICE_ERROR         The device could not be started due to a device error.Currently not implemented.
  @retval EFI_OUT_OF_RESOURCES     The request could not be completed due to a lack of resources.
  @retval Others                   The driver failded to start the device.

**/
EFI_STATUS
EFIAPI
I2cHostDriverStart (
  IN EFI_DRIVER_BINDING_PROTOCOL        *This,
  IN EFI_HANDLE                         Controller,
  IN EFI_DEVICE_PATH_PROTOCOL           *RemainingDevicePath
  )
{
  EFI_STATUS                                          Status;
  EFI_I2C_MASTER_PROTOCOL                             *I2cMaster;
  EFI_I2C_BUS_CONFIGURATION_MANAGEMENT_PROTOCOL       *I2cBusConfigurationManagement;
  I2C_HOST_CONTEXT                                    *I2cHostContext;

  I2cMaster                     = NULL;
  I2cHostContext                = NULL;
  I2cBusConfigurationManagement = NULL;

  //
  // Locate I2C Bus Configuration Management Protocol
  //
  Status = gBS->OpenProtocol (
                  Controller,
                  &gEfiI2cBusConfigurationManagementProtocolGuid,
                  (VOID **)&I2cBusConfigurationManagement,
                  This->DriverBindingHandle,
                  Controller,
                  EFI_OPEN_PROTOCOL_BY_DRIVER
                  );
  if (EFI_ERROR (Status)) {
    DEBUG ((EFI_D_ERROR, "I2cHost: Open I2C bus configuration error, Status = %r\n", Status));
    return Status;
  }

  //
  // Locate I2C Master Protocol
  //
  Status = gBS->OpenProtocol (
                  Controller,
                  &gEfiI2cMasterProtocolGuid,
                  (VOID **)&I2cMaster,
                  This->DriverBindingHandle,
                  Controller,
                  EFI_OPEN_PROTOCOL_GET_PROTOCOL
                  );
  if (EFI_ERROR (Status)) {
    DEBUG ((EFI_D_ERROR, "I2cHost: Open I2C master error, Status = %r\n", Status));
    goto Exit;
  }

  //
  // Allocate the I2C Host Context structure
  //
  I2cHostContext = AllocateZeroPool (sizeof (I2C_HOST_CONTEXT));
  if (I2cHostContext == NULL) {
    DEBUG ((EFI_D_ERROR, "I2cHost: there is no enough memory to allocate.\n"));
    Status = EFI_OUT_OF_RESOURCES;
    goto Exit;
  }

  //
  // Initialize the context structure for the current I2C Controller
  //
  I2cHostContext->Signature                     = I2C_HOST_SIGNATURE;
  I2cHostContext->I2cMaster                     = I2cMaster;
  I2cHostContext->I2cBusConfigurationManagement = I2cBusConfigurationManagement;
  I2cHostContext->I2cBusConfiguration           = (UINTN) -1;
  InitializeListHead(&I2cHostContext->RequestList);

  //
  // Reset the controller
  //
  Status = I2cMaster->Reset (I2cMaster);
  if (EFI_ERROR (Status)) {
    DEBUG ((EFI_D_ERROR, "I2cHost: I2C controller reset failed!\n"));
    goto Exit;
  }

  //
  // Create the I2C transaction complete event
  //
  Status = gBS->CreateEvent (
                  EVT_NOTIFY_SIGNAL,
                  TPL_I2C_SYNC,
                  I2cHostRequestCompleteEvent,
                  I2cHostContext,
                  &I2cHostContext->I2cEvent
                  );
  if (EFI_ERROR (Status)) {
    DEBUG ((EFI_D_ERROR, "I2cHost: create complete event error, Status = %r\n", Status));
    goto Exit;
  }

  //
  // Get the bus management event
  //
  Status = gBS->CreateEvent (
                  EVT_NOTIFY_SIGNAL,
                  TPL_I2C_SYNC,
                  I2cHostI2cBusConfigurationAvailable,
                  I2cHostContext,
                  &I2cHostContext->I2cBusConfigurationEvent
                  );
  if (EFI_ERROR (Status)) {
    DEBUG ((EFI_D_ERROR, "I2cHost: create bus available event error, Status = %r\n", Status));
    goto Exit;
  }

  //
  // Build the I2C host protocol for the current I2C controller
  //
  I2cHostContext->I2cHost.QueueRequest              = I2cHostQueueRequest;
  I2cHostContext->I2cHost.I2cControllerCapabilities = I2cMaster->I2cControllerCapabilities;

  //
  //  Install the driver protocol
  //
  Status = gBS->InstallMultipleProtocolInterfaces (
                  &Controller,
                  &gEfiI2cHostProtocolGuid,
                  &I2cHostContext->I2cHost,
                  NULL
                  );
Exit:
  if (EFI_ERROR (Status)) {
    DEBUG ((EFI_D_ERROR, "I2cHost: Start() function failed, Status = %r\n", Status));
    if (I2cBusConfigurationManagement != NULL) {
      gBS->CloseProtocol (
                      Controller,
                      &gEfiI2cBusConfigurationManagementProtocolGuid,
                      This->DriverBindingHandle,
                      Controller
                      );
    }

    if ((I2cHostContext != NULL) && (I2cHostContext->I2cEvent != NULL)) {
      gBS->CloseEvent (I2cHostContext->I2cEvent);
      I2cHostContext->I2cEvent = NULL;
    }

    if ((I2cHostContext != NULL) && (I2cHostContext->I2cBusConfigurationEvent != NULL)) {
      gBS->CloseEvent (I2cHostContext->I2cBusConfigurationEvent);
      I2cHostContext->I2cBusConfigurationEvent = NULL;
    }

    //
    //  Release the context structure upon failure
    //
    if (I2cHostContext != NULL) {
      FreePool (I2cHostContext);
    }
  }

  //
  //  Return the operation status.
  //
  return Status;
}

/**
  Stops a device controller or a bus controller.

  The Stop() function is designed to be invoked from the EFI boot service DisconnectController().
  As a result, much of the error checking on the parameters to Stop() has been moved
  into this common boot service. It is legal to call Stop() from other locations,
  but the following calling restrictions must be followed, or the system behavior will not be deterministic.
  1. ControllerHandle must be a valid EFI_HANDLE that was used on a previous call to this
     same driver's Start() function.
  2. The first NumberOfChildren handles of ChildHandleBuffer must all be a valid
     EFI_HANDLE. In addition, all of these handles must have been created in this driver's
     Start() function, and the Start() function must have called OpenProtocol() on
     ControllerHandle with an Attribute of EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER.

  @param[in]  This              A pointer to the EFI_DRIVER_BINDING_PROTOCOL instance.
  @param[in]  ControllerHandle  A handle to the device being stopped. The handle must
                                support a bus specific I/O protocol for the driver
                                to use to stop the device.
  @param[in]  NumberOfChildren  The number of child device handles in ChildHandleBuffer.
  @param[in]  ChildHandleBuffer An array of child handles to be freed. May be NULL
                                if NumberOfChildren is 0.

  @retval EFI_SUCCESS           The device was stopped.
  @retval EFI_DEVICE_ERROR      The device could not be stopped due to a device error.

**/
EFI_STATUS
EFIAPI
I2cHostDriverStop (
  IN  EFI_DRIVER_BINDING_PROTOCOL       *This,
  IN  EFI_HANDLE                        Controller,
  IN  UINTN                             NumberOfChildren,
  IN  EFI_HANDLE                        *ChildHandleBuffer
  )
{
  EFI_STATUS                  Status;
  I2C_HOST_CONTEXT            *I2cHostContext;
  EFI_I2C_HOST_PROTOCOL       *I2cHost;
  EFI_TPL                     TplPrevious;

  TplPrevious = EfiGetCurrentTpl ();
  if (TplPrevious > TPL_I2C_SYNC) {
    DEBUG ((EFI_D_ERROR, "I2cHost: TPL %d is too high in Stop.\n", TplPrevious));
    return EFI_DEVICE_ERROR;
  }

  Status = gBS->OpenProtocol (
                  Controller,
                  &gEfiI2cHostProtocolGuid,
                  (VOID **) &I2cHost,
                  This->DriverBindingHandle,
                  Controller,
                  EFI_OPEN_PROTOCOL_GET_PROTOCOL
                  );

  if (EFI_ERROR (Status)) {
    return EFI_DEVICE_ERROR;
  }

  I2cHostContext = I2C_HOST_CONTEXT_FROM_PROTOCOL (I2cHost);

  //
  // Raise TPL for critical section
  //
  TplPrevious = gBS->RaiseTPL (TPL_I2C_SYNC);

  //
  // If there is pending request or pending bus configuration, do not stop
  //
  Status = EFI_DEVICE_ERROR;
  if (( !I2cHostContext->I2cBusConfigurationManagementPending )
    && IsListEmpty (&I2cHostContext->RequestList)) {

    //
    //  Remove the I2C host protocol
    //
    Status = gBS->UninstallMultipleProtocolInterfaces (
                    Controller,
                    &gEfiI2cHostProtocolGuid,
                    I2cHost,
                    NULL
                    );
  }

  //
  // Leave critical section
  //
  gBS->RestoreTPL (TplPrevious);
  if (!EFI_ERROR (Status)) {
    gBS->CloseProtocol (
           Controller,
           &gEfiI2cBusConfigurationManagementProtocolGuid,
           This->DriverBindingHandle,
           Controller
           );

    //
    // Release I2c Host resources
    //
    if (I2cHostContext->I2cBusConfigurationEvent != NULL) {
      gBS->CloseEvent (I2cHostContext->I2cBusConfigurationEvent);
      I2cHostContext->I2cBusConfigurationEvent = NULL;
    }

    if (I2cHostContext->I2cEvent != NULL) {
      gBS->CloseEvent (I2cHostContext->I2cEvent);
      I2cHostContext->I2cEvent = NULL;
    }

    FreePool (I2cHostContext);
  }

  //
  //  Return the stop status
  //
  return Status;
}

/**
  Handle the I2C bus configuration available event

  This routine is called at TPL_I2C_SYNC.

  @param[in] Event    Address of an EFI_EVENT handle
  @param[in] Context  Address of an I2C_HOST_CONTEXT structure

**/
VOID
EFIAPI
I2cHostI2cBusConfigurationAvailable (
  IN EFI_EVENT Event,
  IN VOID *Context
  )
{
  I2C_HOST_CONTEXT            *I2cHostContext;
  EFI_I2C_MASTER_PROTOCOL     *I2cMaster;
  I2C_REQUEST                 *I2cRequest;
  LIST_ENTRY                  *EntryHeader;
  LIST_ENTRY                  *Entry;
  EFI_STATUS                  Status;

  //
  // Mark this I2C bus configuration management operation as complete
  //
  I2cHostContext = (I2C_HOST_CONTEXT *)Context;
  I2cMaster      = I2cHostContext->I2cMaster;
  ASSERT (I2cMaster != NULL);
  //
  // Clear flag to indicate I2C bus configuration is finished
  //
  I2cHostContext->I2cBusConfigurationManagementPending = FALSE;

  //
  //  Validate the completion status
  //
  if (EFI_ERROR (I2cHostContext->Status)) {
    //
    // Setting I2C bus configuration failed before
    //
    I2cHostRequestComplete (I2cHostContext, I2cHostContext->Status);

    //
    // Unknown I2C bus configuration
    // Force next operation to enable the I2C bus configuration
    //
    I2cHostContext->I2cBusConfiguration = (UINTN) -1;

    //
    // Do not continue current I2C request
    //
    return;
  }

  //
  // Get the first request in the link with FIFO order
  //
  EntryHeader = &I2cHostContext->RequestList;
  Entry = GetFirstNode (EntryHeader);
  I2cRequest = I2C_REQUEST_FROM_ENTRY (Entry);

  //
  // Update the I2C bus configuration of the current I2C request
  //
  I2cHostContext->I2cBusConfiguration = I2cRequest->I2cBusConfiguration;

  //
  // Start an I2C operation on the host, the status is returned by I2cHostContext->Status
  //
  Status = I2cMaster->StartRequest (
                        I2cMaster,
                        I2cRequest->SlaveAddress,
                        I2cRequest->RequestPacket,
                        I2cHostContext->I2cEvent,
                        &I2cHostContext->Status
                        );

  if (EFI_ERROR (Status)) {
    DEBUG((DEBUG_ERROR, "I2cHostI2cBusConfigurationAvailable: Error starting I2C operation, %r\n", Status));
  }
}

/**
  Complete the current request

  This routine is called at TPL_I2C_SYNC.

  @param[in] I2cHostContext  Address of an I2C_HOST_CONTEXT structure.
  @param[in] Status          Status of the I2C operation.

  @return This routine returns the input status value.

**/
EFI_STATUS
I2cHostRequestComplete (
  I2C_HOST_CONTEXT *I2cHostContext,
  EFI_STATUS       Status
  )
{
  I2C_REQUEST *I2cRequest;
  LIST_ENTRY  *EntryHeader;
  LIST_ENTRY  *Entry;

  //
  // Remove the current I2C request from the list
  //
  EntryHeader = &I2cHostContext->RequestList;
  Entry = GetFirstNode (EntryHeader);
  I2cRequest = I2C_REQUEST_FROM_ENTRY (Entry);

  //
  // Save the status for QueueRequest
  //
  if ( NULL != I2cRequest->Status ) {
    *I2cRequest->Status = Status;
  }

  //
  //  Notify the user of the I2C request completion
  //
  if ( NULL != I2cRequest->Event ) {
    gBS->SignalEvent (I2cRequest->Event);
  }

  //
  // Done with this request, remove the current request from list
  //
  RemoveEntryList (&I2cRequest->Link);
  FreePool (I2cRequest->RequestPacket);
  FreePool (I2cRequest);

  //
  // If there is more I2C request, start next one
  //
  if(!IsListEmpty (EntryHeader)) {
    I2cHostRequestEnable (I2cHostContext);
  }

  return Status;
}

/**
  Handle the bus available event

  This routine is called at TPL_I2C_SYNC.

  @param[in] Event    Address of an EFI_EVENT handle
  @param[in] Context  Address of an I2C_HOST_CONTEXT structure

**/
VOID
EFIAPI
I2cHostRequestCompleteEvent (
  IN EFI_EVENT Event,
  IN VOID *Context
  )
{
  I2C_HOST_CONTEXT *I2cHostContext;

  //
  // Handle the completion event
  //
  I2cHostContext = (I2C_HOST_CONTEXT *)Context;
  I2cHostRequestComplete (I2cHostContext, I2cHostContext->Status);
}

/**
  Enable access to the I2C bus configuration

  @param[in] I2cHostContext     Address of an I2C_HOST_CONTEXT structure

  @retval EFI_SUCCESS           The operation completed successfully.
  @retval EFI_ABORTED           The request did not complete because the driver
                                was shutdown.
  @retval EFI_BAD_BUFFER_SIZE   The WriteBytes or ReadBytes buffer size is too large.
  @retval EFI_DEVICE_ERROR      There was an I2C error (NACK) during the operation.
                                This could indicate the slave device is not present.
  @retval EFI_INVALID_PARAMETER RequestPacket is NULL
  @retval EFI_NO_MAPPING        Invalid I2cBusConfiguration value
  @retval EFI_NO_RESPONSE       The I2C device is not responding to the
                                slave address.  EFI_DEVICE_ERROR may also be
                                returned if the controller can not distinguish
                                when the NACK occurred.
  @retval EFI_NOT_FOUND         I2C slave address exceeds maximum address
  @retval EFI_NOT_READY         I2C bus is busy or operation pending, wait for
                                the event and then read status.
  @retval EFI_OUT_OF_RESOURCES  Insufficient memory for I2C operation
  @retval EFI_TIMEOUT           The transaction did not complete within an internally
                                specified timeout period.

**/
EFI_STATUS
I2cHostRequestEnable (
  I2C_HOST_CONTEXT *I2cHostContext
  )
{
  UINTN                                                 I2cBusConfiguration;
  CONST EFI_I2C_BUS_CONFIGURATION_MANAGEMENT_PROTOCOL   *I2cBusConfigurationManagement;
  I2C_REQUEST                                           *I2cRequest;
  EFI_STATUS                                            Status;
  EFI_TPL                                               TplPrevious;
  LIST_ENTRY                                            *EntryHeader;
  LIST_ENTRY                                            *Entry;

  //
  //  Assume pending request
  //
  Status = EFI_NOT_READY;

  I2cBusConfigurationManagement = I2cHostContext->I2cBusConfigurationManagement;

  //
  //  Validate the I2c bus configuration
  //
  EntryHeader = &I2cHostContext->RequestList;
  Entry       = GetFirstNode (EntryHeader);
  I2cRequest = I2C_REQUEST_FROM_ENTRY (Entry);

  I2cBusConfiguration = I2cRequest->I2cBusConfiguration;

  if (I2cHostContext->I2cBusConfiguration != I2cBusConfiguration ) {
    //
    // Set flag to indicate I2C bus configuration is in progress
    //
    I2cHostContext->I2cBusConfigurationManagementPending = TRUE;
    //
    //  Update bus configuration for this device's requesting bus configuration
    //
    Status = I2cBusConfigurationManagement->EnableI2cBusConfiguration (
                I2cBusConfigurationManagement,
                I2cBusConfiguration,
                I2cHostContext->I2cBusConfigurationEvent,
                &I2cHostContext->Status
                );
  } else {
    //
    //  I2C bus configuration is same, no need change configuration and start I2c transaction directly
    //
    TplPrevious = gBS->RaiseTPL ( TPL_I2C_SYNC );

    //
    //  Same I2C bus configuration
    //
    I2cHostContext->Status = EFI_SUCCESS;
    I2cHostI2cBusConfigurationAvailable (I2cHostContext->I2cBusConfigurationEvent, I2cHostContext);

    //
    //  Release the thread synchronization
    //
    gBS->RestoreTPL ( TplPrevious );
  }
  return Status;
}

/**
  Queue an I2C operation for execution on the I2C controller.

  This routine must be called at or below TPL_NOTIFY.  For synchronous
  requests this routine must be called at or below TPL_CALLBACK.

  N.B. The typical consumers of this API are the I2C bus driver and
  on rare occasions the I2C test application.  Extreme care must be
  taken by other consumers of this API to prevent confusing the
  third party I2C drivers due to a state change at the I2C device
  which the third party I2C drivers did not initiate.  I2C platform
  drivers may use this API within these guidelines.

  This layer uses the concept of I2C bus configurations to describe
  the I2C bus.  An I2C bus configuration is defined as a unique
  setting of the multiplexers and switches in the I2C bus which
  enable access to one or more I2C devices.  When using a switch
  to divide a bus, due to speed differences, the I2C platform layer
  would define an I2C bus configuration for the I2C devices on each
  side of the switch.  When using a multiplexer, the I2C platform
  layer defines an I2C bus configuration for each of the selector
  values required to control the multiplexer.  See Figure 1 in the
  <a href="http://www.nxp.com/documents/user_manual/UM10204.pdf">I<sup>2</sup>C
  Specification</a> for a complex I2C bus configuration.

  The I2C host driver processes all operations in FIFO order.  Prior to
  performing the operation, the I2C host driver calls the I2C platform
  driver to reconfigure the switches and multiplexers in the I2C bus
  enabling access to the specified I2C device.  The I2C platform driver
  also selects the maximum bus speed for the device.  After the I2C bus
  is configured, the I2C host driver calls the I2C port driver to
  initialize the I2C controller and start the I2C operation.

  @param[in] This             Address of an EFI_I2C_HOST_PROTOCOL instance.
  @param[in] I2cBusConfiguration  I2C bus configuration to access the I2C
                                  device.
  @param[in] SlaveAddress     Address of the device on the I2C bus.
  @param[in] Event            Event to set for asynchronous operations,
                              NULL for synchronous operations
  @param[in] RequestPacket    Address of an EFI_I2C_REQUEST_PACKET
                              structure describing the I2C operation
  @param[out] I2cStatus       Optional buffer to receive the I2C operation
                              completion status

  @retval EFI_SUCCESS           The operation completed successfully.
  @retval EFI_BAD_BUFFER_SIZE   The WriteBytes or ReadBytes buffer size is too large.
  @retval EFI_DEVICE_ERROR      There was an I2C error (NACK) during the operation.
                                This could indicate the slave device is not present.
  @retval EFI_INVALID_PARAMETER RequestPacket is NULL
  @retval EFI_INVALID_PARAMETER TPL is too high
  @retval EFI_NO_MAPPING        Invalid I2cBusConfiguration value
  @retval EFI_NO_RESPONSE       The I2C device is not responding to the
                                slave address.  EFI_DEVICE_ERROR may also be
                                returned if the controller can not distinguish
                                when the NACK occurred.
  @retval EFI_NOT_FOUND         I2C slave address exceeds maximum address
  @retval EFI_NOT_READY         I2C bus is busy or operation pending, wait for
                                the event and then read status pointed to by
                                the request packet.
  @retval EFI_OUT_OF_RESOURCES  Insufficient memory for I2C operation
  @retval EFI_TIMEOUT           The transaction did not complete within an internally
                                specified timeout period.

**/
EFI_STATUS
EFIAPI
I2cHostQueueRequest (
  IN CONST EFI_I2C_HOST_PROTOCOL  *This,
  IN UINTN                        I2cBusConfiguration,
  IN UINTN                        SlaveAddress,
  IN EFI_EVENT                    Event            OPTIONAL,
  IN EFI_I2C_REQUEST_PACKET       *RequestPacket,
  OUT EFI_STATUS                  *I2cStatus       OPTIONAL
  )
{
  EFI_STATUS        Status;
  EFI_EVENT         SyncEvent;
  EFI_TPL           TplPrevious;
  I2C_REQUEST       *I2cRequest;
  I2C_HOST_CONTEXT  *I2cHostContext;
  BOOLEAN           FirstRequest;
  UINTN             RequestPacketSize;
  UINTN             StartBit;

  SyncEvent    = NULL;
  FirstRequest = FALSE;
  Status       = EFI_SUCCESS;

  if (RequestPacket == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  if ((SlaveAddress & I2C_ADDRESSING_10_BIT) != 0) {
    //
    // 10-bit address, bits 0-9 are used for 10-bit I2C slave addresses,
    // bits 10-30 are reserved bits and must be zero
    //
    StartBit = 10;
  } else {
    //
    // 7-bit address, Bits 0-6 are used for 7-bit I2C slave addresses,
    // bits 7-30 are reserved bits and must be zero
    //
    StartBit = 7;
  }

  if (BitFieldRead32 ((UINT32)SlaveAddress, StartBit, 30) != 0) {
    //
    // Reserved bit set in the SlaveAddress parameter
    //
    return EFI_NOT_FOUND;
  }

  I2cHostContext = I2C_HOST_CONTEXT_FROM_PROTOCOL (This);

  if (Event == NULL) {
    //
    // For synchronous transaction, register an event used to wait for finishing synchronous transaction
    //
    Status = gBS->CreateEvent (
                0,
                TPL_I2C_SYNC,
                NULL,
                NULL,
                &SyncEvent
                );
    if (EFI_ERROR (Status)) {
      return Status;
    }
  }

  //
  // TPL should be at or below TPL_NOTIFY.
  // For synchronous requests this routine must be called at or below TPL_CALLBACK.
  //
  TplPrevious = EfiGetCurrentTpl ();
  if ((TplPrevious > TPL_I2C_SYNC) || ((Event == NULL) && (TplPrevious > TPL_CALLBACK))) {
    DEBUG ((EFI_D_ERROR, "ERROR - TPL %d is too high!\n", TplPrevious));
    return EFI_INVALID_PARAMETER;
  }

  //
  // Allocate the request structure
  //
  I2cRequest = AllocateZeroPool (sizeof (I2C_REQUEST));
  if (I2cRequest == NULL) {
    DEBUG ((EFI_D_ERROR, "WARNING - Failed to allocate I2C_REQUEST!\n"));
    return EFI_OUT_OF_RESOURCES;
  }

  //
  // Initialize the request
  //
  I2cRequest->Signature           = I2C_REQUEST_SIGNATURE;
  I2cRequest->I2cBusConfiguration = I2cBusConfiguration;
  I2cRequest->SlaveAddress        = SlaveAddress;
  I2cRequest->Event               = (Event == NULL) ? SyncEvent : Event;
  I2cRequest->Status              = I2cStatus;

  //
  // Copy request packet into private buffer, as RequestPacket may be freed during asynchronous transaction
  //
  RequestPacketSize = sizeof (UINTN) + RequestPacket->OperationCount * sizeof (EFI_I2C_OPERATION);
  I2cRequest->RequestPacket = AllocateZeroPool (RequestPacketSize);
  ASSERT (I2cRequest->RequestPacket != NULL);
  CopyMem (I2cRequest->RequestPacket, RequestPacket, RequestPacketSize);

  //
  // Synchronize with the other threads
  //
  gBS->RaiseTPL ( TPL_I2C_SYNC );

  FirstRequest = IsListEmpty (&I2cHostContext->RequestList);

  //
  // Insert new I2C request in the list
  //
  InsertTailList (&I2cHostContext->RequestList, &I2cRequest->Link);

  //
  // Release the thread synchronization
  //
  gBS->RestoreTPL (TplPrevious);

  if (FirstRequest) {
    //
    // Start the first I2C request, then the subsequent of I2C request will continue
    //
    Status = I2cHostRequestEnable (I2cHostContext);
  }

  if (Event != NULL) {
    //
    // For asynchronous, return EFI_SUCCESS indicating that the asynchronously I2C transaction was queued.
    // No real I2C operation status in I2cStatus
    //
    return EFI_SUCCESS;
  }

  //
  // For synchronous transaction, wait for the operation completion
  //
  do {
    Status = gBS->CheckEvent (SyncEvent);
  } while (Status == EFI_NOT_READY);

  //
  // Get the I2C operation status
  //
  Status = I2cHostContext->Status;

  //
  // Return the I2C operation status
  //
  if (I2cStatus != NULL) {
    *I2cStatus = Status;
  }

  //
  // Close the event if necessary
  //
  if (SyncEvent != NULL) {
    gBS->CloseEvent (SyncEvent);
  }

  return Status;
}

/**
  The user Entry Point for I2C host module. The user code starts with this function.

  @param[in] ImageHandle    The firmware allocated handle for the EFI image.
  @param[in] SystemTable    A pointer to the EFI System Table.

  @retval EFI_SUCCESS       The entry point is executed successfully.
  @retval other             Some error occurs when executing this entry point.

**/
EFI_STATUS
EFIAPI
InitializeI2cHost(
  IN EFI_HANDLE           ImageHandle,
  IN EFI_SYSTEM_TABLE     *SystemTable
  )
{
  EFI_STATUS              Status;

  //
  // Install driver model protocol(s).
  //
  Status = EfiLibInstallDriverBindingComponentName2 (
             ImageHandle,
             SystemTable,
             &gI2cHostDriverBinding,
             ImageHandle,
             &gI2cHostComponentName,
             &gI2cHostComponentName2
             );
  ASSERT_EFI_ERROR (Status);
  return Status;
}

/**
  This is the unload handle for I2C host module.

  Disconnect the driver specified by ImageHandle from all the devices in the handle database.
  Uninstall all the protocols installed in the driver entry point.

  @param[in] ImageHandle           The drivers' driver image.

  @retval    EFI_SUCCESS           The image is unloaded.
  @retval    Others                Failed to unload the image.

**/
EFI_STATUS
EFIAPI
I2cHostUnload (
  IN EFI_HANDLE             ImageHandle
  )
{
  EFI_STATUS                        Status;
  EFI_HANDLE                        *DeviceHandleBuffer;
  UINTN                             DeviceHandleCount;
  UINTN                             Index;
  EFI_COMPONENT_NAME_PROTOCOL       *ComponentName;
  EFI_COMPONENT_NAME2_PROTOCOL      *ComponentName2;

  //
  // Get the list of all I2C Controller handles in the handle database.
  // If there is an error getting the list, then the unload
  // operation fails.
  //
  Status = gBS->LocateHandleBuffer (
                  ByProtocol,
                  &gEfiI2cHostProtocolGuid,
                  NULL,
                  &DeviceHandleCount,
                  &DeviceHandleBuffer
                  );

  if (!EFI_ERROR (Status)) {
    //
    // Disconnect the driver specified by ImageHandle from all
    // the devices in the handle database.
    //
    for (Index = 0; Index < DeviceHandleCount; Index++) {
      Status = gBS->DisconnectController (
                      DeviceHandleBuffer[Index],
                      ImageHandle,
                      NULL
                      );
      if (EFI_ERROR (Status)) {
        goto Done;
      }
    }
  }

  //
  // Uninstall all the protocols installed in the driver entry point
  //
  Status = gBS->UninstallMultipleProtocolInterfaces (
                  gI2cHostDriverBinding.DriverBindingHandle,
                  &gEfiDriverBindingProtocolGuid,
                  &gI2cHostDriverBinding,
                  NULL
                  );
  ASSERT_EFI_ERROR (Status);

  //
  // Note we have to one by one uninstall the following protocols.
  // It's because some of them are optionally installed based on
  // the following PCD settings.
  //   gEfiMdePkgTokenSpaceGuid.PcdDriverDiagnosticsDisable
  //   gEfiMdePkgTokenSpaceGuid.PcdComponentNameDisable
  //   gEfiMdePkgTokenSpaceGuid.PcdDriverDiagnostics2Disable
  //   gEfiMdePkgTokenSpaceGuid.PcdComponentName2Disable
  //
  Status = gBS->HandleProtocol (
                  gI2cHostDriverBinding.DriverBindingHandle,
                  &gEfiComponentNameProtocolGuid,
                  (VOID **) &ComponentName
                  );
  if (!EFI_ERROR (Status)) {
    gBS->UninstallProtocolInterface (
           gI2cHostDriverBinding.DriverBindingHandle,
           &gEfiComponentNameProtocolGuid,
           ComponentName
           );
  }

  Status = gBS->HandleProtocol (
                  gI2cHostDriverBinding.DriverBindingHandle,
                  &gEfiComponentName2ProtocolGuid,
                  (VOID **) &ComponentName2
                  );
  if (!EFI_ERROR (Status)) {
    gBS->UninstallProtocolInterface (
           gI2cHostDriverBinding.DriverBindingHandle,
           &gEfiComponentName2ProtocolGuid,
           ComponentName2
           );
  }

  Status = EFI_SUCCESS;

Done:
  //
  // Free the buffer containing the list of handles from the handle database
  //
  if (DeviceHandleBuffer != NULL) {
    gBS->FreePool (DeviceHandleBuffer);
  }

  return Status;
}


text:
package acstest;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.util.NoSuchElementException;
import java.util.function.Function;

import org.junit.Assert;

import Zql.ParseException;
import Zql.ZQuery;
import Zql.ZStatement;
import Zql.ZqlParser;
import simpledb.BadErrorException;
import simpledb.Database;
import simpledb.DbException;
import simpledb.DbIterator;
import simpledb.HeapFile;
import simpledb.ImputedLogicalPlan;
import simpledb.Insert;
import simpledb.LogicalPlan;
import simpledb.Parser;
import simpledb.ParsingException;
import simpledb.SeqScan;
import simpledb.TableStats;
import simpledb.TransactionAbortedException;
import simpledb.TransactionId;
import simpledb.TupleDesc;
import simpledb.Type;

public class RunQueries {
	private static final String OUT_FN = "queries.csv";

	private static FileWriter outFile;

	private static DbIterator planQuery(String query, Function<Void, LogicalPlan> planFactory) throws ParseException, TransactionAbortedException, DbException, IOException, ParsingException {
		ZqlParser p = new ZqlParser(new ByteArrayInputStream(query.getBytes("UTF-8")));
		ZStatement s = p.readStatement();
		Parser pp = new Parser(planFactory);
		return pp.handleQueryStatement((ZQuery)s, new TransactionId()).getPhysicalPlan();
	}

	private static void drain(DbIterator iter) throws DbException, TransactionAbortedException {
		while (iter.hasNext()) {
			try {
				iter.next();
			} catch(NoSuchElementException e) {
				e.printStackTrace();
			}
		}
	}

	private static void runQuery(String query) throws IOException, ParseException, TransactionAbortedException, DbException, ParsingException {
		String dirtyQuery = query.replaceAll("acs", "acs_dirty");

		Instant startPlan, endPlan, startRun, endRun;

		System.err.println("Planning queries...");
		DbIterator clean = planQuery(query, x -> new LogicalPlan());
		DbIterator dirty = planQuery(dirtyQuery, x -> new LogicalPlan());
		clean.open();

		dirty.open();
		Double baseErr = null;
		try {
			baseErr = clean.error(dirty);
		} catch (BadErrorException e) {}
		dirty.close();

		for (double a = 0.0; a <= 1.0; a += 1.0) {
			final double aa = a;
			startPlan = Instant.now();
			DbIterator imputedDirty = planQuery(dirtyQuery, x -> new ImputedLogicalPlan(aa));
			endPlan = Instant.now();

			startRun = Instant.now();
			imputedDirty.open();
			drain(imputedDirty);
			endRun = Instant.now();

			imputedDirty.rewind();
			clean.rewind();
			Double imputeErr = null;
			try {
				imputeErr = clean.error(imputedDirty);
			} catch (BadErrorException e) {}

			outFile.write(String.format("\"%s\",%f,%f,%d,%d,%f\n", query, baseErr, imputeErr,
					Duration.between(startPlan, endPlan).getSeconds(), Duration.between(startRun, endRun).getSeconds(), a));
			outFile.flush();
			imputedDirty.close();
		}
		clean.close();
	}

	public static void main(String args[]) throws IOException, NoSuchElementException, DbException, TransactionAbortedException, ParseException, ParsingException {
		(new AcsTestRule()).initializer.before();

		System.err.println("Creating new table with dirty data...");
		Database.getCatalog().addTable("acs_dirty", "", AcsTestRule.SCHEMA);
		int oldTblId = Database.getCatalog().getTableId("acs"),
			newTblId = Database.getCatalog().getTableId("acs_dirty");

		System.err.println("Adding synthetic data");
		int nfields = 10;
		Type[] types = new Type[nfields];
		String[] fields = new String[nfields];
		for (int i = 0; i < types.length; i++) {
			types[i] = Type.INT_TYPE;
			fields[i] = "f" + i;
		}
		TupleDesc schema = new TupleDesc(types, fields);
		ClassLoader loader = CleanTest.class.getClassLoader();
		File cleanData = new File(loader.getResource("testdata/clean.dat").getFile());
		Database.getCatalog().addTable(new HeapFile(cleanData, schema), "clean", "");
		File dirtyData = new File(loader.getResource("testdata/dirty.dat").getFile());
		Database.getCatalog().addTable(new HeapFile(dirtyData, schema), "dirty", "");

		System.err.println("Inserting dirty acs data...");
		TransactionId tid = new TransactionId();
		new Insert(tid, new Smudge(new SeqScan(tid, oldTblId), 0.1), newTblId).next();
		tid = null;

		TableStats.computeStatistics();
		System.err.println("Done.");

		outFile = new FileWriter(OUT_FN);
		outFile.write("query,base_err,impute_err,plan_time,run_time,alpha\n");

		for (Object[] query : DirtyTest.data()) {
			runQuery((String)query[0]);
		}
		outFile.close();
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Michael's Blog</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="css/clean-blog.min.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation
                    Menu
                </button>
                Michael's Blog

                        Home

                        About

                        Newest Post

                        Contact

Michael's Blog

                        A blog made to review video games

                            Final Fantasy XV

                            After ten years, it's finally here.

Posted by Michael Dean on December 12, 2016

                            Dishonored 2

Posted by Michael Dean on December 8, 2016

                            Call of Duty: Infinite Warfare

                            Does this year's Call of Duty live up to the hype, or does it fall flat on it's face?

Posted by Michael Dean on December 2, 2016

                            Gears of War 4

                            Does The Coalition's new title live up to the expectations of a numbered Gears title?

Posted by Michael Dean on December 1, 2016

                        Older Posts →

Copyright © Your Website 2016


text:
<?php

namespace Faker\Provider\en_HK;

class PhoneNumber extends \Faker\Provider\PhoneNumber
{
    protected static $formats = ['2#######', '3#######', '5#######', '6#######', '9#######'];
    protected static $mobileFormats = ['5#######', '6#######', '9#######'];
    protected static $landlineFormats = ['2#######', '3#######'];
    protected static $faxFormats = ['7#######'];

    /**
     * Return an en_HK mobile phone number
     * @return string
     */
    public static function mobileNumber()
    {
        return static::numerify(static::randomElement(static::$mobileFormats));
    }

    /**
     * Return an en_HK landline number
     * @return string
     */
    public static function landlineNumber()
    {
        return static::numerify(static::randomElement(static::$landlineFormats));
    }

    /**
     * Return an en_HK fax number
     * @return string
     */
    public static function faxNumber()
    {
        return static::numerify(static::randomElement(static::$faxFormats));
    }
}


text:
class CreateRates < ActiveRecord::Migration
  def self.up
    create_table :rates do |t|
      t.references :<%= file_name %>
      t.references :rateable, :polymorphic => true
      t.decimal :stars
      t.string :dimension

      t.timestamps
    end

    add_index :rates, :<%= file_name %>_id
    add_index :rates, :rateable_id
  end

  def self.down
    drop_table :rates
  end
end


text:
class WindowImpl {
    public:
        static std::vector<Window::DisplayMode> getFullscreenModes();
        static void create(Window::DisplayMode mode, ContextSettings contextSettings);
        static void destroy();

        static void setDisplayMode(Window::DisplayMode mode);
        static void setVsync(Window::VsyncMode mode);
        static vec2ui getSize();

        static void update();
        static void setTitle(std::string newTitle);
        static void setClosing(bool newClosing);
        static bool isFocused();
        static bool isClosing();
        static void setPosition(unsigned int x, unsigned int y);

        static void swapBuffers();

    private:
        // Initializes SDL if needed.
        static void initSDL();

        static void processEvent(const SDL_Event& e);

        static bool isSDLInit;
        static SDL_Window* window;
        static SDL_GLContext context;
        static bool focused;
        static bool closing;

        friend class InputImpl;
};

#endif // WINDOWIMPL_HPP


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;

namespace PerfEventsData
{
    /// <summary>
    /// Indicates the architecture where the performance data was collected.
    /// </summary>
    public enum Architecture
    {
        Amd64,
        X86
    }
}


text:
from django.contrib.auth.models import User

from social.exceptions import AuthFailed
from social.pipeline.mail import mail_validation as psa_mail_validation

def user_by_email(backend, details, *args, **kwargs):
    if backend.name == 'email':
        if not details.get('email'):
            raise AuthFailed(backend, 'Missing email')

        request_data = backend.strategy.request_data()
        password = request_data.get('password')
        if not request_data.get('verification_code') and not password:
            raise AuthFailed(backend, 'Missing password')

        try:
            user = User.objects.get(email=details['email'])
        except User.DoesNotExist:
            user = None
        else:
            if not request_data.get('verification_code') and \
               not user.check_password(password):
                raise AuthFailed(backend, 'Wrong password')
        return {'user': user, 'password': password}

def set_password(backend, user, is_new=False, *args, **kwargs):
    if backend.name == 'email' and is_new:
        user.set_password(kwargs['password'])
        user.save()

def mail_validation(*args, **kwargs):
    if kwargs.get('user') is None:
        return psa_mail_validation(*args, **kwargs)


text:
#import "MgImageLayer.h"

#import "MgCoderExtensions.h"
#import "MgImageCALayer.h"
#import "MgImageLayerState.h"
#import "MgImageProvider.h"
#import "MgLayerInternal.h"
#import "MgNodeInternal.h"

#import <Foundation/Foundation.h>

#define STATE ((MgImageLayerState *)(self.state))

@implementation MgImageLayer

static NSMutableSet *image_provider_classes;

+ (Class)stateClass
{
  return [MgImageLayerState class];
}

- (Class)viewLayerClass
{
  if ([MgImageCALayer supportsLayer:self])
    return [MgImageCALayer class];
  else
    return [super viewLayerClass];
}

+ (void)registerImageProviderClass:(Class)cls
{
  if (image_provider_classes == nil)
    image_provider_classes = [[NSMutableSet alloc] init];

  [image_provider_classes addObject:cls];
}

+ (NSSet *)imageProviderClasses
{
  if (image_provider_classes == nil)
    [MgImageLayer registerImageProviderClass:[MgImageProvider class]];

  return image_provider_classes;
}

+ (BOOL)automaticallyNotifiesObserversOfImageProvider
{
  return NO;
}

- (id<MgImageProvider>)imageProvider
{
  return STATE.imageProvider;
}

- (void)setImageProvider:(id<MgImageProvider>)p
{
  MgImageLayerState *state = STATE;

  if (state.imageProvider != p)
    {
      [self willChangeValueForKey:@"imageProvider"];
      state.imageProvider = p;
      [self incrementVersion];
      [self didChangeValueForKey:@"imageProvider"];
    }
}

+ (BOOL)automaticallyNotifiesObserversOfInterpolationQuality
{
  return NO;
}

- (CGInterpolationQuality)interpolationQuality
{
  return STATE.interpolationQuality;
}

- (void)setInterpolationQuality:(CGInterpolationQuality)q
{
  MgImageLayerState *state = STATE;

  if (state.interpolationQuality != q)
    {
      [self willChangeValueForKey:@"interpolationQuality"];
      state.interpolationQuality = q;
      [self incrementVersion];
      [self didChangeValueForKey:@"interpolationQuality"];
    }
}

+ (BOOL)automaticallyNotifiesObserversOfCropRect
{
  return NO;
}

- (CGRect)cropRect
{
  return STATE.cropRect;
}

- (void)setCropRect:(CGRect)r
{
  MgImageLayerState *state = STATE;

  if (!CGRectEqualToRect(state.cropRect, r))
    {
      [self willChangeValueForKey:@"cropRect"];
      state.cropRect = r;
      [self incrementVersion];
      [self didChangeValueForKey:@"cropRect"];
    }
}

+ (BOOL)automaticallyNotifiesObserversOfCenterRect
{
  return NO;
}

- (CGRect)centerRect
{
  return STATE.centerRect;
}

- (void)setCenterRect:(CGRect)r
{
  MgImageLayerState *state = STATE;

  if (!CGRectEqualToRect(state.centerRect, r))
    {
      [self willChangeValueForKey:@"centerRect"];
      state.centerRect = r;
      [self incrementVersion];
      [self didChangeValueForKey:@"centerRect"];
    }
}

+ (BOOL)automaticallyNotifiesObserversOfRepeats
{
  return NO;
}

- (BOOL)repeats
{
  return STATE.repeats;
}

- (void)setRepeats:(BOOL)flag
{
  MgImageLayerState *state = STATE;

  if (state.repeats != flag)
    {
      [self willChangeValueForKey:@"repeats"];
      state.repeats = flag;
      [self incrementVersion];
      [self didChangeValueForKey:@"repeats"];
    }
}

- (void)_renderLayerWithState:(MgLayerRenderState *)rs
{
  CGImageRef im = [self.imageProvider mg_providedImage];
  bool release_im = false;

  CGRect crop = self.cropRect;
  if (!CGRectIsEmpty(crop))
    {
      im = CGImageCreateWithImageInRect(im, crop);
      release_im = true;
    }

  if (im != NULL)
    {
      /* We're assuming top-left geometry, so flip images to keep them
	 oriented the right way vertically. */

      CGContextSaveGState(rs->ctx);
      CGContextTranslateCTM(rs->ctx, 0, self.bounds.size.height);
      CGContextScaleCTM(rs->ctx, 1, -1);

      /* FIXME: implement 9-part and tiling.
	 FIXME: is interpolationQuality part of the gstate? */

      CGInterpolationQuality old_quality
        = CGContextGetInterpolationQuality(rs->ctx);

      CGContextSetInterpolationQuality(rs->ctx, self.interpolationQuality);

      CGContextDrawImage(rs->ctx, self.bounds, im);

      CGContextSetInterpolationQuality(rs->ctx, old_quality);

      CGContextRestoreGState(rs->ctx);

      if (release_im)
	CGImageRelease(im);
    }
}

- (void)_renderLayerMaskWithState:(MgLayerRenderState *)rs
{
  float alpha = rs->alpha * self.alpha;

  if (alpha != 1)
    {
      [super _renderLayerMaskWithState:rs];
      return;
    }

  /* FIXME: incorrect, assumes image is opaque. Could just call
     CGContextClipToMask() and hope it does the right thing? */

  CGContextClipToRect(rs->ctx, self.bounds);
}

@end