text:
<?php

/**
 * Sugar DateTime container
 * Extends regular PHP DateTime with useful services
 * @api
 */
class SugarDateTime extends DateTime
{
    // Recognized properties and their formats
	protected $formats = array(
		"sec" => "s",
		"min" => "i",
		"hour" => "G",
		"zhour" => "H",
		"day" => "j",
		"zday" => "d",
		"days_in_month" => "t",
		"day_of_week" => "w",
		"day_of_year" => "z",
		"week" => "W",
		"month" => "n",
		"zmonth" => "m",
		"year" => "Y",
		"am_pm" => "A",
		"hour_12" => "g",
	);

	// Property aliases
	protected $var_gets = array(
		"24_hour" => "hour",
		"day_of_week" => "day_of_week_long",
		"day_of_week_short" => "day_of_week_short",
		"month_name" => "month_long",
		"hour" => "hour_12",
	);

	/**
	 * @var DateTimeZone
	 */
	protected static $_gmt;

    /**
     * Calendar strings
     * @var array
     */
    protected $_strings;

    /**
     * For testing - if we allowed to use PHP date parse
     * @var bool
     */
    public static $use_php_parser = true;

    /**
     * For testing - if we allowed to use strptime()
     * @var bool
     */
    public static $use_strptime = true;

    /**
	 * Copy of DateTime::createFromFormat
	 *
	 * Needed to return right type of the object
	 *
	 * @param string $format Format like in date()
	 * @param string $time Time to parse
	 * @param DateTimeZone $timezone
	 * @return SugarDateTime
	 * @see DateTime::createFromFormat
	 */
	public static function createFromFormat($format, $time, $timezone = null)
	{
	    if(empty($time) || empty($format)) {
	        return false;
	    }
		if(self::$use_php_parser && is_callable(array("DateTime", "createFromFormat"))) {
			// 5.3, hurray!
			if(!empty($timezone)) {
			    $d = parent::createFromFormat($format, $time, $timezone);
			} else {
			    $d = parent::createFromFormat($format, $time);
			}
		} else {
			// doh, 5.2, will have to simulate
			$d = self::_createFromFormat($format, $time, $timezone);
		}
		if(!$d) {
			return false;
		}
		$sd = new self($d->format(DateTime::ISO8601));
		$sd->setTimezone($d->getTimezone());
		return $sd;
	}

	/**
	 * Internal _createFromFormat implementation for 5.2
     * @internal
	 * @param string $format Format like in date()
	 * @param string $time Time string to parse
	 * @param DateTimeZone $timezone TZ
     * @return SugarDateTime
     * @see DateTime::createFromFormat
	 */
	protected static function _createFromFormat($format, $time, DateTimeZone $timezone = null)
	{
		$res = new self();
		if(!empty($timezone)) {
		    $res->setTimezone($timezone);
		}
		if(self::$use_strptime && function_exists("strptime")) {
    		$str_format = str_replace(array_keys(TimeDate::$format_to_str), array_values(TimeDate::$format_to_str), $format);
    		// for a reason unknown to modern science, %P doesn't work in strptime
    		$str_format = str_replace("%P", "%p", $str_format);
    		// strip spaces before am/pm as our formats don't have them
    		$time = preg_replace('/\s+(AM|PM)/i', '\1', $time);
    		// TODO: better way to not risk locale stuff problems?
    		$data = strptime($time, $str_format);
    		if(empty($data)) {
		        $GLOBALS['log']->error("Cannot parse $time for format $format");
    		    return null;
    		}
    		if($data["tm_year"] == 0) {
    		    unset($data["tm_year"]);
    		}
    		if($data["tm_mday"] == 0) {
    		    unset($data["tm_mday"]);
    		}
    		if(isset($data["tm_year"])) {
    		    $data["tm_year"] += 1900;
    		}
    		if(isset($data["tm_mon"])) {
    		    $data["tm_mon"]++;
    		}
    		$data += self::$data_init; // fill in missing parts
		} else {
		    // Windows, etc. might not have strptime - we'd have to work harder here
            $data = $res->_strptime($time, $format);
		}
		if(empty($data)) {
		    $GLOBALS['log']->error("Cannot parse $time for format $format");
		    return null;
		}
		if(isset($data["tm_year"])) {
     	    $res->setDate($data["tm_year"], $data["tm_mon"], $data["tm_mday"]);
		}
    	$res->setTime($data["tm_hour"], $data["tm_min"], $data["tm_sec"]);
		return $res;
	}

	/**
	 * Load language Calendar strings
     * @internal
	 * @param string $name string section to return
	 * @return array
	 */
	protected function _getStrings($name)
	{
		if(empty($this->_strings)) {
			$this->_strings = return_mod_list_strings_language($GLOBALS['current_language'],"Calendar");
		}
		return $this->_strings[$name];
	}

	/**
	 * Fetch property of the date by name
	 * @param string $var Property name
	 * @return mixed
	 */
	public function __get($var)
	{
		// simple formats
		if(isset($this->formats[$var])) {
			return $this->format($this->formats[$var]);
		}
		// conditional, derived and translated ones
		switch($var) {
			case "ts":
				return $this->format("U")+0;
			case "tz_offset":
				return $this->getTimezone()->getOffset($this);
			case "days_in_year":
				return $this->format("L") == '1'?366:365;
				break;
			case "day_of_week_short":
				$str = $this->_getStrings('dom_cal_weekdays');
				return $str[$this->day_of_week];
			case "day_of_week_long":
				$str = $this->_getStrings('dom_cal_weekdays_long');
				return $str[$this->day_of_week];
			case "month_short":
				$str = $this->_getStrings('dom_cal_month');
				return $str[$this->month];
			case "month_long":
				$str = $this->_getStrings('dom_cal_month_long');
				return $str[$this->month];
		}

		return '';
	}

	/**
	 * Implement some get_ methods that fetch variables
	 *
	 * @param string $name
	 * @param array $args
     * @return mixed
     */
	public function __call($name, $args)
	{
		// fill in 5.2.x gaps
		if($name == "getTimestamp") {
			return $this->format('U')+0;
		}
		if($name == "setTimestamp") {
			$sec = (int)$args[0];
			$sd = new self("@$sec");
			$sd->setTimezone($this->getTimezone());
			return $sd;
		}

		// getters
		if(substr($name, 0, 4) == "get_") {
			$var = substr($name, 4);

			if(isset($this->var_gets[$var])) {
				return $this->__get($this->var_gets[$var]);
			}

			if(isset($this->formats[$var])) {
				return $this->__get($var);
			}
		}
		$GLOBALS['log']->fatal("SugarDateTime: unknowm method $name called");
		sugar_die("SugarDateTime: unknowm method $name called");
		return false;
	}

	/**
	 * Get specific hour of today
	 * @param int $hour_index
	 * @return SugarDateTime
	 */
	public function get_datetime_by_index_today($hour_index)
	{
		if ( $hour_index < 0 || $hour_index > 23  )
		{
			sugar_die("hour is outside of range");
		}

		$newdate = clone $this;
		$newdate->setTime($hour_index, 0, 0);
		return $newdate;
	}

	/**
	 * Get the last second of current hour
	 * @return SugarDateTime
	 */
	function get_hour_end_time()
	{
		$newdate = clone $this;
		$newdate->setTime($this->hour, 59, 59);
		return $newdate;
	}

	/**
	 * Get the last second of the current day
	 * @return SugarDateTime
	 */
	function get_day_end_time()
	{
		$newdate = clone $this;
		return $newdate->setTime(23, 59, 59);
	}

	/**
	 * Get the beginning of i's day of the week
	 * @param int $day_index Day, 0 is Sunday, 1 is Monday, etc.
	 * @return SugarDateTime
	 */
	function get_day_by_index_this_week($day_index)
	{
		$newdate = clone $this;
		$newdate->setDate($this->year, $this->month, $this->day +
			($day_index - $this->day_of_week))->setTime(0,0);
		return $newdate;
	}

	/**
	 * Get the beginning of the last day of i's the month
	 * @deprecated
	 * FIXME: no idea why this function exists and what's the use of it
	 * @param int $month_index Month, January is 0
	 * @return SugarDateTime
	 */
	function get_day_by_index_this_year($month_index)
	{
		$newdate = clone $this;
		$newdate->setDate($this->year, $month_index+1, 1);
        $newdate->setDate($newdate->year, $newdate->month,  $newdate->days_in_month);
		$newdate->setTime(0, 0);
		return $newdate;
	}

	/**
	 * Get the beginning of i's day of the month
	 * @param int $day_index 0 is the first day of the month (sic!)
	 * @return SugarDateTime
	 */
	function get_day_by_index_this_month($day_index)
	{
		$newdate = clone $this;
		return $newdate->setDate($this->year, $this->month, $day_index+1)->setTime(0, 0);
	}

	/**
	 * Get new date, modified by date expression
	 *
	 * @example $yesterday = $today->get("yesterday");
	 *
	 * @param string $expression
	 * @return SugarDateTime
	 */
	function get($expression)
	{
		$newdate = clone $this;
		$newdate->modify($expression);
		return $newdate;
	}

	/**
	 * Create from ISO 8601 datetime
	 * @param string $str
	 * @return SugarDateTime
	 */
	static public function parse_utc_date_time($str)
	{
		return new self($str);
	}

	/**
	 * Create a list of time slots for calendar view
	 * Times must be in user TZ
	 * @param string $view Which view we are using - day, week, month
	 * @param SugarDateTime $start_time Start time
	 * @param SugarDateTime $end_time End time
     * @return array
     */
	static function getHashList($view, $start_time, $end_time)
	{
		$hash_list = array();

  		if ( $view != 'day')
		{
		  $end_time = $end_time->get_day_end_time();
		}

		$end = $end_time->ts;
		if($end <= $start_time->ts) {
			$end = $start_time->ts+1;
		}

		$new_time = clone $start_time;
		$new_time->setTime($new_time->hour, 0, 0);

        while ($new_time->ts < $end) {
            if ($view == 'day') {
                $hash_list[] = $new_time->format(TimeDate::DB_DATE_FORMAT) . ":" . $new_time->hour;
                $new_time->modify("next hour");
            } else {
                $hash_list[] = $new_time->format(TimeDate::DB_DATE_FORMAT);
                $new_time->modify("next day");
            }
        }

		return $hash_list;
	}

	/**
	 * Get the beginning of the given day
	 * @param int $day  Day, starting with 1, default is current
	 * @param int $month Month, starting with 1, default is current
	 * @param int $year Year, default is current
     * @return SugarDateTime
     */
	function get_day_begin($day = null, $month = null, $year = null)
	{
	    $newdate = clone $this;
	    $newdate->setDate(
	         $year?$year:$this->year,
	         $month?$month:$this->month,
	         $day?$day:$this->day);
	    $newdate->setTime(0, 0);
	    return $newdate;
	}

	/**
	 * Get the last second of the given day
	 * @param int $day  Day, starting with 1, default is current
	 * @param int $month Month, starting with 1, default is current
	 * @param int $year Year, default is current
	 * @return SugarDateTime
	 */
	function get_day_end($day = null, $month = null, $year = null)
	{
	    $newdate = clone $this;
	    $newdate->setDate(
	         $year?$year:$this->year,
	         $month?$month:$this->month,
	         $day?$day:$this->day);
	    $newdate->setTime(23, 59, 59);
	    return $newdate;
	}

	/**
	 * Get the beginning of the first day of the year
	 * @param int $year
	 * @return SugarDateTime
	 */
	function get_year_begin($year)
	{
        $newdate = clone $this;
        $newdate->setDate($year, 1, 1);
        $newdate->setTime(0,0);
        return $newdate;
	}

	/**
	 * Print datetime in standard DB format
	 *
	 * Set $tz parameter to false if you are sure that the date is in UTC.
	 *
	 * @param bool $tz do conversion to UTC
	 * @return string
	 */
	function asDb($tz = true)
	{
        if($tz) {
            if(empty(self::$_gmt)) {
                self::$_gmt = new DateTimeZone("UTC");
            }
            $this->setTimezone(self::$_gmt);
        }
        return $this->format(TimeDate::DB_DATETIME_FORMAT);
	}

	/**
	 * Print date in standard DB format
	 *
	 * Set $tz parameter to false if you are sure that the date is in UTC.
	 *
	 * @param bool $tz do conversion to UTC
	 * @return string
	 */
	function asDbDate($tz = true)
	{
        if($tz) {
            if(empty(self::$_gmt)) {
                self::$_gmt = new DateTimeZone("UTC");
            }
            $this->setTimezone(self::$_gmt);
        }
        return $this->format(TimeDate::DB_DATE_FORMAT);
	}

	/**
	 * Get query string for the date, year=%d&month=%d&day=%d&hour=%d
	 * @return string
	 */
	function get_date_str()
	{
        return sprintf("&year=%d&month=%d&day=%d&hour=%d", $this->year, $this->month, $this->day, $this->hour);
	}

	/**
	 * Convert date to string - 'r' format, like: Thu, 21 Dec 2000 16:01:07 +0200
     * @return string
     */
	function __toString()
	{
	    return $this->format('r');
	}

    /**
     * Match between tm_ parts and date() format strings
     * @var array
     */
	protected static $parts_match = array(
            'Y' => 'tm_year',
            'm' => 'tm_mon',
            'n' => 'tm_mon',
            'd' => 'tm_mday',
            'H' => 'tm_hour',
            'h' => 'tm_hour',
            'i' => 'tm_min',
            's' => 'tm_sec',
    );

    protected static $data_init = array(
        "tm_hour" => 0,
        "tm_min" => 0,
        "tm_sec" => 0,
    );

    protected static $strptime_short_mon, $strptime_long_mon;
	/**
     * DateTime homebrew parser
     *
     * Since some OSes and PHP versions (please upgrade to 5.3!) do not support built-in parsing functions,
     * we have to restort to this ugliness.
     * @internal
     * @param string $time  Time formatted string
     * @param string $format Format, as accepted by strptime()
     * @return array Parsed parts
     */
    protected function _strptime($time, $format)
    {
       $data = self::$data_init;
       if(empty(self::$strptime_short_mon)) {
           self::$strptime_short_mon = array_flip($this->_getStrings('dom_cal_month'));
           unset(self::$strptime_short_mon[""]);
       }
       if(empty(self::$strptime_long_mon)) {
           self::$strptime_long_mon = array_flip($this->_getStrings('dom_cal_month_long'));
           unset(self::$strptime_long_mon[""]);
       }

        $regexp = TimeDate::get_regular_expression($format);
        if(!preg_match('@'.$regexp['format'].'@', $time, $dateparts)) {
            return false;
        }

        foreach(self::$parts_match as $part => $datapart) {
            if (isset($regexp['positions'][$part]) && isset($dateparts[$regexp['positions'][$part]])) {
                $data[$datapart] = (int)$dateparts[$regexp['positions'][$part]];
            }
        }
        // now process non-numeric ones
        if ( isset($regexp['positions']['F']) && !empty($dateparts[$regexp['positions']['F']])) {
                       // FIXME: locale?
            $mon = $dateparts[$regexp['positions']['F']];
            if(isset(self::$sugar_strptime_long_mon[$mon])) {
                $data["tm_mon"] = self::$sugar_strptime_long_mon[$mon];
            } else {
                return false;
            }
        }
        if ( isset($regexp['positions']['M']) && !empty($dateparts[$regexp['positions']['M']])) {
                       // FIXME: locale?
            $mon = $dateparts[$regexp['positions']['M']];
            if(isset(self::$sugar_strptime_short_mon[$mon])) {
                $data["tm_mon"] = self::$sugar_strptime_short_mon[$mon];
            } else {
                return false;
            }
        }
        if ( isset($regexp['positions']['a']) && !empty($dateparts[$regexp['positions']['a']])) {
            $ampm = trim($dateparts[$regexp['positions']['a']]);
            if($ampm == 'pm') {
                if($data["tm_hour"] != 12) $data["tm_hour"] += 12;
            } else if($ampm == 'am') {
                if($data["tm_hour"] == 12) {
                    // 12:00am is 00:00
                    $data["tm_hour"] = 0;
                }
            } else {
                return false;
            }
        }

        if ( isset($regexp['positions']['A']) && !empty($dateparts[$regexp['positions']['A']])) {
            $ampm = trim($dateparts[$regexp['positions']['A']]);
            if($ampm == 'PM') {
                if($data["tm_hour"] != 12) $data["tm_hour"] += 12;
            } else if($ampm == 'AM') {
                if($data["tm_hour"] == 12) {
                    // 12:00am is 00:00
                    $data["tm_hour"] = 0;
                }
            } else {
                return false;
            }
        }

        return $data;
    }

    // 5.2 compatibility - 5.2 functions don't return $this, let's help them

    /**
     * (non-PHPdoc)
     * @see DateTime::setDate()
     * @param $year
     * @param $month
     * @param $day
     * @return SugarDateTime
     */
    public function setDate ($year, $month, $day)
    {
        parent::setDate($year, $month, $day);
        return $this;
    }

    /**
     * (non-PHPdoc)
     * @see DateTime::setTime()
     * @param $hour
     * @param $minute
     * @param int $sec
     * @return SugarDateTime
     */
    public function setTime($hour, $minute, $sec = 0)
    {
        parent::setTime($hour, $minute, $sec);
        return $this;
    }

    /**
     * (non-PHPdoc)
     * @see DateTime::modify()
     * @param $modify
     * @return SugarDateTime
     */
    public function modify($modify)
    {
        // We can't user PHP_VERSION_ID here because problem with yesterday and tomorrow appears in defferent versions
        // In that case we just set time to midnight for yesterday & tomorrow
        // To leave time as it is we can use -+1 day instead of yesterday & tomorrow
        if (strpos($modify, 'yesterday') !== false || strpos($modify, 'tomorrow') !== false) {
            $this->setTime(0, 0);
        }
        if(PHP_VERSION_ID >= 50300 || $modify != 'first day of next month') {
            parent::modify($modify);
        } else {
            /* PHP 5.2 does not understand 'first day of' and defaults need it */
            $this->setDate($this->year, $this->month+1, 1);
        }
        return $this;
    }

    /**
     * (non-PHPdoc)
     * @see DateTime::setTimezone()
     * @param DateTimeZone $timezone
     * @return SugarDateTime
     */
    public function setTimezone ($timezone)
    {
        parent::setTimezone($timezone);
        return $this;
    }

}


text:
; Copyright (c) 2004, Intel Corporation
; All rights reserved. This program and the accompanying materials
; are licensed and made available under the terms and conditions of the BSD License
; which accompanies this distribution.  The full text of the license may be found at
; http://opensource.org/licenses/bsd-license.php
;
; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
;
; Module Name:
;
;   Invd.Asm
;
; Abstract:
;
;   AsmInvd function
;
; Notes:
;
;------------------------------------------------------------------------------

    .code

;------------------------------------------------------------------------------
; VOID
; EFIAPI
; AsmInvd (
;   VOID
;   );
;------------------------------------------------------------------------------
AsmInvd PROC
    invd
    ret
AsmInvd ENDP

    END

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
  <link href="http://gmpg.org/xfn/11" rel="profile">

  <title>
    What's Jekyll? ·
    Hyde, By Ishan
  </title>

  <link rel="stylesheet" href="/public/css/hyde.css">
  <link rel="stylesheet" href="/public/css/syntax.css">
  <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:300,400italic,400,600,700|Abril+Fatface">

  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/public/touch-icon-144-precomposed.png">
  <link rel="shortcut icon" href="/public/favicon.png">

  <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">

Ishan

An elegant open source and mobile first theme for Jekyll. Made by @mdo.

              Download

              GitHub project

Currently v1.1.1

© 2014.  All rights reserved.

What's Jekyll?

  06 Feb 2012

Jekyll is a static site generator, an open-source tool for creating simple yet powerful websites of all shapes and sizes. From the project's readme:

> Jekyll is a simple, blog aware, static site generator. It takes a template directory [] and spits out a complete, static website suitable for serving with Apache or your favorite web server. This is also the engine behind GitHub Pages, which you can use to host your project's page or blog right here from GitHub.

It's an immensely useful tool and one we encourage you to use here with Hyde.

Find out more by visiting the project on GitHub.

Related Posts

            Hello, world!
            28 Dec 2013

            Example content
            07 Feb 2012


text:
This document represents the description of the feature that allows users of the API to declare bindings between interface types and their respective implementers.

## User API

Bindings will normally be declared using a static method that returns a type that can be operated on by the LINQ Extensions.

```csharp
public static IBinding<TInterface> Bind<TInterface>()
{
	return null;
}
```

Usage:

```csharp
IBinding<TInterface> b = Bind<TInterface>();
```

An interface type will be bound to a constructor using the `Select()` extension method.
The expressions passed into the select method are used for special "expression-hacks", allowing us to specify that a certain type should be used. In the future, functions may be used and special values that support the operations that we want _might_ be used.

## Examples

<strike>
Automatically-chosen constructor:

```csharp
IBinding<TInterface> finalBinding = b.Select(type => type as TImplementer);
IBinding<TInterface> finalBinding = from type in b select type as TImplementer;
```
</strike>

User-defined constructor:

```csharp
IBinding<TInterface> finalBinding = b.Select(type => new TImplementer());
IBinding<TInterface> finalBinding = from type in b select new TImplementer();
```

Dependencies are defined using the `Dependency()` method helper in a constructor:

```csharp
IBinding<TInterface> binding = from value in Bind<TInterface>()
                               select new TImplementer(Dependency(bindingImDependentOn));
```

## Internal API

~~Automatic bindings will be declared using an implementation of the `IBindToType<TInterface, TImplementer>` interface, which will normally be implemented by `BindToType<TInterface, TImplementer>` class.~~

~~Usage:~~
<strike>
```csharp
IBinding<TInterface> b = Bind<TInterface>().Select(type => type as TImplementer);

// Equivalent
IBinding<TInterface> b = new BindToType<TInterface, TImplementer>(Bind<TInterface>());
```
</strike>

Constructor bindings will be declared using an implementation of the `IBindToConstructor<TInterface, TImplementer>` interface, which will normally be implemented by `BindToConstructor<TInterface, TImplementer>` class.
In order to resolve dependencies effeciently, no `IKernel` or `IResolver` or `ILocator` interface will be provided to the constructor function, thereby reducing the need for dictionary lookups and reflection calls. Rather, when an object needs to be resolved a function is generated that contains all of the direct calls to the required constructors.

```csharp
IBinding<TInterface> finalBinding = b.Select(type => new TImplementer());

// Equivalent
IBinding<TInterface> finalBinding = new BindToConstructor<TInterface, TImplementer>(
	(Func<TImplementer>) () => new TImplementer()
);
```

Bindings that require internal resolutions (such as those that use the `default(T)` operator) will rely on the [binding grouping APIs][binding-grouping] for service lookup.

[binding-grouping]: ./binding-grouping.md


text:
<?php
include 'library.php'; // include the library file
include "classes/class.phpmailer.php"; // include the class name
$mail	= new PHPMailer; // call the class
$mail->IsSMTP();
$mail->Host = SMTP_HOST; //Hostname of the mail server
$mail->Port = SMTP_PORT; //Port of the SMTP like to be 25, 80, 465 or 587
$mail->SMTPAuth = true; //Whether to use SMTP authentication
$mail->Username = SMTP_UNAME; //Username for SMTP authentication any valid email created in your domain
$mail->Password = SMTP_PWORD;
$mail->AddReplyTo("reply@yourdomain.com", "Reply name"); //reply-to address
$mail->SetFrom("from@yourdomain.com", "Asif18 SMTP Mailer"); //From address of the mail
// put your while loop here like below,
$mail->Subject = "Your SMTP Mail"; //Subject od your mail
$recipients = array(
   'subscriber1@asif18.com' => 'Asif 18',
   'subscriber2@gmail.com' => 'Mohamed Asif'
);
foreach($recipients as $email => $name){
	// it will display the emails of all users in their Mailbox 'To' area. Simple multiple mail.
	$mail->AddAddress($email, $name); //To address who will receive this email
	$mail->MsgHTML("Hi, your first Newsletter mail through SMTP has been received. Great Job!..

by Asif18"); //Put your body of the message you can place html code here
	$mail->AddAttachment("images/asif18-logo.png"); //Attach a file here if any or comment this line (usimg absolute path),
	$send = $mail->Send(); //Send the mails
	// if you want to does not show other users email addresses like newsletter, daily, weekly, subscription emails means use the below line to clear previous email address
	$mail->ClearAddresses();
}
	if($send){
		echo '
Mail sent successfully
';
	}
	else{
		echo '
Mail error:
'.$mail->ErrorInfo;
	}
?>


text:
#ifndef AOM_DSP_PROB_H_
#define AOM_DSP_PROB_H_

#include "./aom_config.h"
#include "./aom_dsp_common.h"

#include "aom_ports/mem.h"

#ifdef __cplusplus
extern "C" {
#endif

typedef uint8_t aom_prob;

#define MAX_PROB 255

#define aom_prob_half ((aom_prob)128)

typedef int8_t aom_tree_index;

#define TREE_SIZE(leaf_count) (-2 + 2 * (leaf_count))

#define aom_complement(x) (255 - x)

#define MODE_MV_COUNT_SAT 20

/* We build coding trees compactly in arrays.
   Each node of the tree is a pair of aom_tree_indices.
   Array index often references a corresponding probability table.
   Index <= 0 means done encoding/decoding and value = -Index,
   Index > 0 means need another bit, specification at index.
   Nonnegative indices are always even;  processing begins at node 0. */

typedef const aom_tree_index aom_tree[];

static INLINE aom_prob clip_prob(int p) {
  return (p > 255) ? 255 : (p < 1) ? 1 : p;
}

static INLINE aom_prob get_prob(int num, int den) {
  return (den == 0) ? 128u : clip_prob(((int64_t)num * 256 + (den >> 1)) / den);
}

static INLINE aom_prob get_binary_prob(int n0, int n1) {
  return get_prob(n0, n0 + n1);
}

/* This function assumes prob1 and prob2 are already within [1,255] range. */
static INLINE aom_prob weighted_prob(int prob1, int prob2, int factor) {
  return ROUND_POWER_OF_TWO(prob1 * (256 - factor) + prob2 * factor, 8);
}

static INLINE aom_prob merge_probs(aom_prob pre_prob, const unsigned int ct[2],
                                   unsigned int count_sat,
                                   unsigned int max_update_factor) {
  const aom_prob prob = get_binary_prob(ct[0], ct[1]);
  const unsigned int count = AOMMIN(ct[0] + ct[1], count_sat);
  const unsigned int factor = max_update_factor * count / count_sat;
  return weighted_prob(pre_prob, prob, factor);
}

// MODE_MV_MAX_UPDATE_FACTOR (128) * count / MODE_MV_COUNT_SAT;
static const int count_to_update_factor[MODE_MV_COUNT_SAT + 1] = {
  0,  6,  12, 19, 25, 32,  38,  44,  51,  57, 64,
  70, 76, 83, 89, 96, 102, 108, 115, 121, 128
};

static INLINE aom_prob mode_mv_merge_probs(aom_prob pre_prob,
                                           const unsigned int ct[2]) {
  const unsigned int den = ct[0] + ct[1];
  if (den == 0) {
    return pre_prob;
  } else {
    const unsigned int count = AOMMIN(den, MODE_MV_COUNT_SAT);
    const unsigned int factor = count_to_update_factor[count];
    const aom_prob prob =
        clip_prob(((int64_t)(ct[0]) * 256 + (den >> 1)) / den);
    return weighted_prob(pre_prob, prob, factor);
  }
}

void aom_tree_merge_probs(const aom_tree_index *tree, const aom_prob *pre_probs,
                          const unsigned int *counts, aom_prob *probs);

DECLARE_ALIGNED(16, extern const uint8_t, aom_norm[256]);

#ifdef __cplusplus
}  // extern "C"
#endif

#endif  // AOM_DSP_PROB_H_


text:
'use strict';

const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');

// [START setup]
const Mailgun = require('mailgun').Mailgun;
const mg = new Mailgun(process.env.MAILGUN_API_KEY);
// [END setup]

const app = express();

// Setup view engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

// Parse form data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// [START index]
app.get('/', (req, res) => {
  res.render('index');
});
// [END index]

// [START hello]
app.post('/hello', (req, res, next) => {
  const servername = '';
  const options = {};

  mg.sendText(
    // From
    'no-reply@appengine-mailgun-demo.com',
    // To
    req.body.email,
    // Subject
    'Hello World!',
    // Body
    'Mailgun on Google App Engine with Node.js',
    servername,
    options,
    (err) => {
      if (err) {
        next(err);
        return;
      }
      // Render the index route on success
      res.render('index', {
        sent: true
      });
    }
  );
});
// [END hello]

// [START server]
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`App listening on port ${PORT}`);
  console.log('Press Ctrl+C to quit.');
});
// [END server]


text:
<?php

namespace Application\Filters;

use Application\DAL\DAOInterface;

use Zend\InputFilter\Input;
use Zend\InputFilter\InputFilter;
use Zend\Validator;
use Zend\Filter;
/**
 * Description of ProdutoFilter
 *
 * @author Irving Fernando de Medeiros Oliveira
 */
class ProdutoFilter extends InputFilter{

    private $descricaoTxt;
    private $tipoSlct;
    private $unidadeSlct;

    private $tipoProdutoDAO;
    private $unidadeDAO;

    public function __construct($descricaoTxt, $tipoSlct, $unidadeSlct,
            DAOInterface $tipoProdutoDAO, DAOInterface $unidadeDAO) {

        $this->descricaoTxt = $descricaoTxt;
        $this->tipoSlct = $tipoSlct;
        $this->unidadeSlct = $unidadeSlct;

        $this->tipoProdutoDAO = $tipoProdutoDAO;
        $this->unidadeDAO = $unidadeDAO;

        $this->add($this->getDescricaoTxtInput());
        $this->add($this->getTipoSlctInput());
        $this->add($this->getUnidadeSlctInput());

        $this->preencherDados();
    }

    public function getDescricaoTxtInput(){
        $descricaoInputFilter = new Input('descricaoTxt');

        $descricaoStringLength = new Validator\StringLength(array('max' => 255,
                                                                  'min' => 3));
        $descricaoStringLength->setMessages(array(
            Validator\StringLength::TOO_SHORT =>
            'A descrição é muito curta, o valor mínimo é de %min% caracteres.',
            Validator\StringLength::TOO_LONG =>
            'A descrição é muito longa, o valor máximo é de %max% caracteres.'
        ));

        $descricaoNotEmpty = new Validator\NotEmpty();
        $descricaoNotEmpty->setMessage('O campo descrição é obrigatório e não ser vazio.');

        $descricaoInputFilter->getValidatorChain()
                ->attach($descricaoStringLength)
                ->attach($descricaoNotEmpty);
        $descricaoInputFilter->getFilterChain()
                ->attach(new Filter\HtmlEntities())
                ->attach(new Filter\StringTrim())
                ->attach(new Filter\StripTags());

        return $descricaoInputFilter;
    }

    public function getTipoSlctInput(){
        $tiposProduto = $this->tipoProdutoDAO->lerTodos()->getResult();
        foreach ($tiposProduto as $tipoProduto) {
            $idTipoProduto[] = $tipoProduto->getIdTipoProduto();
        }

        $tipoProdutoHayStack = new Validator\InArray(array('haystack' => $idTipoProduto));
        $tipoProdutoHayStack->setMessages(array(
            Validator\InArray::NOT_IN_ARRAY => 'Não foi escolhido um tipo de produto válido.'
        ));

        $tipoNotEmpty = new Validator\NotEmpty();
        $tipoNotEmpty->setMessage('O campo tipo é obrigatório e não ser vazio.');

        $tipoInputFilter = new Input('tipoSlct');
        $tipoInputFilter->setRequired(TRUE);
        $tipoInputFilter->getValidatorChain()
                ->attach($tipoProdutoHayStack)
                ->attach($tipoNotEmpty);
        return $tipoInputFilter;
    }

    public function getUnidadeSlctInput(){
        $unidades = $this->unidadeDAO->lerTodos()->getResult();
        foreach ($unidades as $unidade) {
            $idUnidade[] = $unidade->getIdUnidade();
        }
        $unidadeHayStack = new Validator\InArray(array('haystack' => $idUnidade));
        $unidadeHayStack->setMessages(array(
            Validator\InArray::NOT_IN_ARRAY => 'Não foi escolhida uma unidade válida.'
        ));

        $unidadeNotEmpty = new Validator\NotEmpty();
        $unidadeNotEmpty->setMessage('O campo unidade é obrigatório e não ser vazio.');

        $unidadeInputFilter = new Input('unidadeSlct');
        $unidadeInputFilter->setRequired(TRUE);
        $unidadeInputFilter->getValidatorChain()
                ->attach($unidadeHayStack)
                ->attach($unidadeNotEmpty);
        return $unidadeInputFilter;
    }

    public function preencherDados(){
        $this->setData(array(
            'descricaoTxt' => $this->descricaoTxt,
            'tipoSlct' => $this->tipoSlct,
            'unidadeSlct' => $this->unidadeSlct,
        ));
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<webapp>
    <listener>
        <listener-class>fi.nls.oskari.map.servlet.OskariContextInitializer</listener-class>
    </listener>

    <filter>
        <filter-name>oskariRequestFilter</filter-name>
        <filter-class>fi.nls.oskari.map.servlet.OskariRequestFilter</filter-class>
    </filter>
    <filter>
        <filter-name>authenticationFilter</filter-name>
        <filter-class>fi.nls.oskari.map.servlet.PrincipalAuthenticationFilter</filter-class>
    </filter>

    <servlet>
        <servlet-name>default</servlet-name>
        <init-param>
            <param-name>useFileMappedBuffer</param-name>
            <param-value>false</param-value>
        </init-param>
    </servlet>

    <servlet>
        <servlet-name>mapFullServlet</servlet-name>
        <servlet-class>fi.nls.oskari.map.servlet.MapFullServlet</servlet-class>
        <init-param>
            <param-name>version</param-name>
            <param-value>${oskari.client.version}</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>/Oskari/*</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>mapFullServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <filter-mapping>
        <filter-name>oskariRequestFilter</filter-name>
        <servlet-name>mapFullServlet</servlet-name>
    </filter-mapping>

    <filter-mapping>
        <filter-name>authenticationFilter</filter-name>
        <servlet-name>mapFullServlet</servlet-name>
    </filter-mapping>

    <login-config>
        <auth-method>FORM</auth-method>
        <realm-name>OskariRealm</realm-name>
        <form-login-config>
            <form-login-page>/</form-login-page>
            <form-error-page>/?loginState=failed</form-error-page>
        </form-login-config>
    </login-config>
</webapp>


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.application;

import com.yahoo.config.application.api.DeploymentSpec;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.ClusterResources;
import com.yahoo.config.provision.ClusterSpec;
import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.vespa.hosted.controller.Application;
import com.yahoo.vespa.hosted.controller.api.integration.billing.Quota;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

/**
 * Calculates the quota to allocate to a deployment.
 *
 * @author ogronnesby
 * @author andreer
 */
public class DeploymentQuotaCalculator {

    public static Quota calculate(Quota tenantQuota,
                                  List<Application> tenantApps,
                                  ApplicationId deployingApp, ZoneId deployingZone,
                                  DeploymentSpec deploymentSpec)
    {
        if (tenantQuota.budget().isEmpty()) return tenantQuota; // Shortcut if there is no budget limit to care about.
        if (deployingZone.environment().isTest()) return tenantQuota;
        if (deployingZone.environment().isProduction()) return probablyEnoughForAll(tenantQuota, tenantApps, deployingApp, deploymentSpec);
        return getMaximumAllowedQuota(tenantQuota, tenantApps, deployingApp, deployingZone);
    }

    public static QuotaUsage calculateQuotaUsage(com.yahoo.vespa.hosted.controller.api.integration.configserver.Application application) {
        var quotaUsageRate = application.clusters().values().stream()
                .filter(cluster -> ! cluster.type().equals(ClusterSpec.Type.admin))
                .map(cluster -> largestQuotaUsage(cluster.current(), cluster.max()))
                .mapToDouble(resources -> resources.nodes() * resources.nodeResources().cost())
                .sum();
        return QuotaUsage.create(quotaUsageRate);
    }

    private static ClusterResources largestQuotaUsage(ClusterResources a, ClusterResources b) {
        return a.cost() > b.cost() ? a : b;
    }

    /** Just get the maximum quota we are allowed to use. */
    private static Quota getMaximumAllowedQuota(Quota tenantQuota, List<Application> applications,
                                                ApplicationId application, ZoneId zone) {
        var usageOutsideDeployment = applications.stream()
                .map(app -> app.quotaUsage(application, zone))
                .reduce(QuotaUsage::add).orElse(QuotaUsage.none);
        return tenantQuota.subtractUsage(usageOutsideDeployment.rate());
    }

    /**
     * We want to avoid applying a resource change to an instance in production when it seems likely
     * that there will not be enough quota to apply this change to _all_ production instances.
     * <p>
     * To achieve this, we must make the assumption that all production instances will use
     * the same amount of resources, and so equally divide the quota among them.
     */
    private static Quota probablyEnoughForAll(Quota tenantQuota, List<Application> tenantApps,
                                              ApplicationId application, DeploymentSpec deploymentSpec) {

        TenantAndApplicationId deployingAppId = TenantAndApplicationId.from(application);

        var usageOutsideApplication = tenantApps.stream()
                .filter(app -> !app.id().equals(deployingAppId))
                .map(Application::quotaUsage).reduce(QuotaUsage::add).orElse(QuotaUsage.none);

        QuotaUsage manualQuotaUsage = tenantApps.stream()
                .filter(app -> app.id().equals(deployingAppId)).findFirst()
                .map(Application::manualQuotaUsage).orElse(QuotaUsage.none);

        long productionDeployments = Math.max(1, deploymentSpec.instances().stream()
                .flatMap(instance -> instance.zones().stream())
                .filter(zone -> zone.environment().isProduction())
                .count());

        return tenantQuota.withBudget(
                tenantQuota.subtractUsage(usageOutsideApplication.rate() + manualQuotaUsage.rate())
                        .budget().get().divide(BigDecimal.valueOf(productionDeployments),
                        5, RoundingMode.HALF_UP)); // 1/1000th of a cent should be accurate enough
    }
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\modules\setting\models\AccountPostingType */
/* @var $form yii\widgets\ActiveForm */
?>

Form

Subtitle goes here...

Home

FORMS

Form

Create account-posting-type

            <form  name="account-posting-type-form" class="form-horizontal row-border">

                  	Doc type code

					<input type="text" name="Doc_type_code" class="form-control">

                  	Doc type code description

					<input type="text" name="Doc_type_code_description" class="form-control">

                  <button type="submit" class="btn btn-primary">Create</button>
                  <button type="button" class="btn btn-default">Cancel</button>

              </form>

 <?php $form = ActiveForm::begin(); ?>

		   Doc type code

				<?= $form->field($model,'Doc_type_code')->textInput(['maxlength' => true])->label('') ?>

		   Doc type code description

				<?= $form->field($model,'Doc_type_code_description')->textInput(['maxlength' => true])->label('') ?>

        <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
import * as Sequelize from "sequelize";
import {Comment} from "./comment";
import {Landmark} from "./landmark";
import {Route} from "./route";
import {Tag} from "./tag";
import {User} from "./user";
import {Waypoint} from "./waypoint";

export {
  Comment,
  Landmark,
  Route,
  Tag,
  User,
  Waypoint
};

export interface Models {
  comment: Comment.Model;
  landmark: Landmark.Model;
  route: Route.Model;
  tag: Tag.Model;
  user: User.Model;
  waypoint: Waypoint.Model;
}

export function defineAll(db: Sequelize.Sequelize): Models {
  const comment: Comment.Model = Comment.define(db);
  const landmark: Landmark.Model = Landmark.define(db);
  const route: Route.Model = Route.define(db);
  const tag: Tag.Model = Tag.define(db);
  const user: User.Model = User.define(db);
  const waypoint: Waypoint.Model = Waypoint.define(db);

  comment.belongsTo(user, {as: "author"});
  landmark.hasMany(comment, {as: "comments"});
  route.hasMany(comment, {as: "comments"});
  route.hasMany(waypoint, {as: "waypoints"});
  route.belongsTo(user, {as: "author"});

  route.belongsToMany(tag, {as: "Tags", through: "routes_tags"});
  tag.belongsToMany(route, {as: "Routes", through: "routes_tags"});
  route.belongsToMany(user, {as: "Favorites", through: "routes_favorites"});
  user.belongsToMany(route, {as: "FavoriteRoutes", through: "routes_favorites"});
  route.belongsToMany(user, {as: "Likes", through: "routes_likes"});
  user.belongsToMany(route, {as: "LikedRoutes", through: "routes_likes"});
  route.belongsToMany(user, {as: "RecentUsers", through: "routes_recent"});
  user.belongsToMany(route, {as: "RecentRoutes", through: "routes_recent"});

  return {comment, landmark, route, tag, user, waypoint};
}


text:
executable     	= x_echostring.pl
arguments		= job_dagman_abort-final-A-node.cmd $(nodename) OK
universe       	= vanilla
notification   	= NEVER
getenv         	= true
output			= job_dagman_abort-final-A-node.$(nodename).out
error			= job_dagman_abort-final-A-node.$(nodename).err
queue


text:
<?php

namespace Diside\SecurityBundle\Presenter;

use Diside\SecurityComponent\Interactor\Presenter\UserPresenter as UserPresenterInterface;
use Diside\SecurityComponent\Model\User;

class UserPresenter extends BasePresenter implements UserPresenterInterface
{
    private $user;

    public function getUser()
    {
        return $this->user;
    }

    public function setUser(User $user)
    {
        $this->user = $user;
    }
}


text:
START_ATF_NAMESPACE
    struct tagMENUINFO
    {
        unsigned int cbSize;
        unsigned int fMask;
        unsigned int dwStyle;
        unsigned int cyMax;
        HBRUSH__ *hbrBack;
        unsigned int dwContextHelpID;
        unsigned __int64 dwMenuData;
    };
END_ATF_NAMESPACE


text:
.wrapper {
    display: none;
    position: absolute;
    top: 35%;
    width: 100%;
    margin-left: 75px;
}

.cssanimations.csstransforms3d .wrapper {
    display: block;
}

.wrapper * {
    -webkit-transform-style: preserve-3d;
    -moz-transform-style: preserve-3d;
    -ie-transform-style: preserve-3d;
    -o-transform-style: preserve-3d;
    transform-style: preserve-3d;
}

.zoetrope {
    height: 100px;
    width: 100px;
    margin: 0 auto;

    -webkit-perspective: 900;
    -moz-perspective: 900;
    -ie-perspective: 900;
    -o-perspective: 900;
    perspective: 900;

    -webkit-transform: rotateX(-11deg);
    -moz-transform: rotateX(-11deg);
    -ie-transform: rotateX(-11deg);
    -o-transform: rotateX(-11deg);
    transform: rotateX(-11deg);
}

.frames {
    position: relative;
    height: 100px;
    width: 100px;
    margin: 0 auto;
    -webkit-animation-name: spin;
    -webkit-animation-duration: 1200ms;
    -webkit-animation-iteration-count: infinite;
    -webkit-animation-timing-function: linear;

    -moz-animation: spin 1200ms infinite linear;
    -ie-animation: spin 1200ms infinite linear;
    -o-animation: spin 1200ms infinite linear;
    animation: spin 1200ms infinite linear;
}

@keyframes spin {
    from { transform: rotateY(0); }
    to   { transform: rotateY(-360deg); }
}

@-webkit-keyframes spin {
    from { -webkit-transform: rotateY(0); }
    to   { -webkit-transform: rotateY(-360deg); }
}

@-moz-keyframes spin {
    from { -moz-transform: rotateY(0); }
    to   { -moz-transform: rotateY(-360deg); }
}

@-ie-keyframes spin {
    from { -ie-transform: rotateY(0); }
    to   { -ie-transform: rotateY(-360deg); }
}

@-o-keyframes spin {
    from { -o-transform: rotateY(0); }
    to   { -o-transform: rotateY(-360deg); }
}

.frames > div, .frames > div:after, .frames > div:before {
    position: absolute;
    height: 100px;
    width: 100px;
}

.frames > div {
    background-color: white;
    -webkit-backface-visibility: visible;
    -moz-backface-visibility: visible;
    -ie-backface-visibility: visible;
    -o-backface-visibility: visible;
    backface-visibility: visible;
}

.zoetrope.ball .frames > div  {
    background-image: url("../images/balls.jpg");
}

.zoetrope.horse .frames > div {
    background-image: url("../images/muybridge.jpg");
}

.zoetrope.willie .frames > div {
    background-image: url("../images/willie.jpg");
}

.frames > div:before {
    content: "";
    background: black;
    width: 102px;
    /* HACK getting the :after positioned outside the wheel... */
    -webkit-transform: translateZ(1px);
    -moz-transform: translateZ(1px);
    -ie-transform: translateZ(1px);
    -o-transform: translateZ(1px);
    transform: translateZ(1px);
}

.frames > div:after {
    content: "";
    top: -98px;
    width: 102px;
    height: 100px;
    border-left: 35px solid black;
    border-right: 35px solid black;
    border-top: 15px solid black;
    border-bottom: 15px solid black;

    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    -ie-box-sizing: border-box;
    -o-box-sizing: border-box;
    box-sizing: border-box;

    -webkit-transform: translateZ(1px);
    -moz-transform: translateZ(1px);
    -ie-transform: translateZ(1px);
    -o-transform: translateZ(1px);
    transform: translateZ(1px);
}


text:
package in.mansiz.dailyselfie.provider;

import android.net.Uri;

public class SelfieContract {

	public static final String AUTHORITY = "in.mansiz.dailyselfie.provider";
	public static final Uri BASE_URI = Uri
			.parse("content://" + AUTHORITY + "/");

	public static final String SELFIE_TABLE_NAME = "seflie";

	// The URI for this table.
	public static final Uri SELFIE_URI = Uri.withAppendedPath(BASE_URI, SELFIE_TABLE_NAME);

	//Columns for the selfie table
	public static final String SELFIE_COLUMN_ID = "_id";
	public static final String SELFIE_COLUMN_NAME = "name";
	public static final String SELFIE_COLUMN_PATH = "path";
	public static final String SELFIE_COLUMN_THUMB = "thumb";

}


text:
use middle::resolve;
use middle::ty;
use util::nodemap::{NodeMap, NodeSet};

use syntax::codemap::Span;
use syntax::{ast, ast_util};
use syntax::visit;
use syntax::visit::Visitor;

#[deriving(Show)]
pub enum CaptureMode {
    /// Copy/move the value from this llvm ValueRef into the environment.
    CaptureByValue,

    /// Access by reference (used for stack closures).
    CaptureByRef
}

// A vector of defs representing the free variables referred to in a function.
// (The def_upvar will already have been stripped).
#[deriving(Encodable, Decodable)]
pub struct freevar_entry {
    pub def: ast::Def, //< The variable being accessed free.
    pub span: Span     //< First span where it is accessed (there can be multiple)
}
pub type freevar_map = NodeMap<Vec<freevar_entry>>;

struct CollectFreevarsVisitor<'a> {
    seen: NodeSet,
    refs: Vec<freevar_entry>,
    def_map: &'a resolve::DefMap,
}

impl<'a> Visitor<int> for CollectFreevarsVisitor<'a> {
    fn visit_item(&mut self, _: &ast::Item, _: int) {
        // ignore_item
    }

    fn visit_expr(&mut self, expr: &ast::Expr, depth: int) {
        match expr.node {
            ast::ExprFnBlock(..) | ast::ExprProc(..) => {
                visit::walk_expr(self, expr, depth + 1)
            }
            ast::ExprPath(..) => {
                let mut i = 0;
                match self.def_map.borrow().find(&expr.id) {
                    None => fail!("path not found"),
                    Some(&df) => {
                        let mut def = df;
                        while i < depth {
                            match def {
                                ast::DefUpvar(_, inner, _, _) => { def = *inner; }
                                _ => break
                            }
                            i += 1;
                        }
                        if i == depth { // Made it to end of loop
                            let dnum = ast_util::def_id_of_def(def).node;
                            if !self.seen.contains(&dnum) {
                                self.refs.push(freevar_entry {
                                    def: def,
                                    span: expr.span,
                                });
                                self.seen.insert(dnum);
                            }
                        }
                    }
                }
            }
            _ => visit::walk_expr(self, expr, depth)
        }
    }

}

// Searches through part of the AST for all references to locals or
// upvars in this frame and returns the list of definition IDs thus found.
// Since we want to be able to collect upvars in some arbitrary piece
// of the AST, we take a walker function that we invoke with a visitor
// in order to start the search.
fn collect_freevars(def_map: &resolve::DefMap, blk: &ast::Block) -> Vec<freevar_entry> {
    let mut v = CollectFreevarsVisitor {
        seen: NodeSet::new(),
        refs: Vec::new(),
        def_map: def_map,
    };

    v.visit_block(blk, 1);
    v.refs
}

struct AnnotateFreevarsVisitor<'a> {
    def_map: &'a resolve::DefMap,
    freevars: freevar_map,
}

impl<'a> Visitor<()> for AnnotateFreevarsVisitor<'a> {
    fn visit_fn(&mut self, fk: &visit::FnKind, fd: &ast::FnDecl,
                blk: &ast::Block, s: Span, nid: ast::NodeId, _: ()) {
        let vars = collect_freevars(self.def_map, blk);
        self.freevars.insert(nid, vars);
        visit::walk_fn(self, fk, fd, blk, s, nid, ());
    }
}

// Build a map from every function and for-each body to a set of the
// freevars contained in it. The implementation is not particularly
// efficient as it fully recomputes the free variables at every
// node of interest rather than building up the free variables in
// one pass. This could be improved upon if it turns out to matter.
pub fn annotate_freevars(def_map: &resolve::DefMap, krate: &ast::Crate) ->
   freevar_map {
    let mut visitor = AnnotateFreevarsVisitor {
        def_map: def_map,
        freevars: NodeMap::new(),
    };
    visit::walk_crate(&mut visitor, krate, ());

    visitor.freevars
}

pub fn with_freevars<T>(tcx: &ty::ctxt, fid: ast::NodeId, f: |&[freevar_entry]| -> T) -> T {
    match tcx.freevars.borrow().find(&fid) {
        None => fail!("with_freevars: {} has no freevars", fid),
        Some(d) => f(d.as_slice())
    }
}

pub fn get_capture_mode(tcx: &ty::ctxt,
                        closure_expr_id: ast::NodeId)
                        -> CaptureMode
{
    let fn_ty = ty::node_id_to_type(tcx, closure_expr_id);
    match ty::ty_closure_store(fn_ty) {
        ty::RegionTraitStore(..) => CaptureByRef,
        ty::UniqTraitStore => CaptureByValue
    }
}


text:
package org.kiji.schema.layout.impl;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.ConnectionLossException;
import org.apache.zookeeper.KeeperException.NodeExistsException;
import org.apache.zookeeper.KeeperException.SessionExpiredException;
import org.apache.zookeeper.KeeperException.SessionMovedException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.kiji.annotations.ApiAudience;
import org.kiji.schema.KijiIOException;
import org.kiji.schema.RuntimeInterruptedException;
import org.kiji.schema.util.Lock;
import org.kiji.schema.util.LockFactory;
import org.kiji.schema.util.ReferenceCountable;
import org.kiji.schema.util.Time;
import org.kiji.schema.util.ZooKeeperLock;

/**
 * ZooKeeper client interface.
 *
 * @deprecated use a {@link org.apache.curator.framework.CuratorFramework} instead.
 *    Will be removed in KijiSchema 2.0.
 */
@ApiAudience.Private
@Deprecated
public final class ZooKeeperClient implements ReferenceCountable<ZooKeeperClient> {
  private static final Logger LOG = LoggerFactory.getLogger(ZooKeeperClient.class);

  /** Empty byte array used to create ZooKeeper "directory" nodes. */
  private static final byte[] EMPTY_BYTES = new byte[0];

  /** Time interval, in seconds, between ZooKeeper retries on error. */
  private static final double ZOOKEEPER_RETRY_DELAY = 1.0;

  /** Timeout for ZooKeeper sessions, in milliseconds. */
  private static final int SESSION_TIMEOUT = 60 * 1000; // 60 seconds

  /**
   * Cache of existing ZooKeeperClient instances keyed on quorum addresss.
   * Protected by CACHE_MONITOR.
   */
  private static final Map<String, ZooKeeperClient> ZOOKEEPER_CACHE = Maps.newHashMap();

  /**
   * Protects access to ZOOKEEPER_CACHE. Must always be aquired before
   * mMonitor.
   */
  private static final Object CACHE_MONITOR = new Object();

  /**
   * Factory method for retrieving an instance of ZooKeeperClient connected to the provided quorum
   * address.  Will reuse existing connections if possible.  The caller is responsible for
   * releasing the ZooKeeperClient.
   *
   * @param address of ZooKeeper quorum.
   * @return a ZooKeeperClient.
   */
  public static ZooKeeperClient getZooKeeperClient(String address) {
    synchronized (CACHE_MONITOR) {
      final ZooKeeperClient existingClient = ZOOKEEPER_CACHE.get(address);
      if (existingClient == null) {
        final ZooKeeperClient newClient = new ZooKeeperClient(address).open();
        ZOOKEEPER_CACHE.put(address, newClient);
        return newClient.retain();
      } else {
        return existingClient.retain();
      }
    }
  }

  // -----------------------------------------------------------------------------------------------

  /**
   * Watcher for the ZooKeeper session.
   *
   *
 Processes notifications related to the liveness of the ZooKeeper session.

   */
  private class SessionWatcher implements Watcher {
    /** {@inheritDoc} */
    @Override
    public void process(WatchedEvent event) {
      LOG.debug("ZooKeeper client: process({})", event);

      if (event.getType() != Event.EventType.None) {
        LOG.error("Unexpected event: {}", event);
        return;
      }
      if (event.getPath() != null) {
        LOG.error("Unexpected event: {}", event);
        return;
      }

      switch (event.getState()) {
      case SyncConnected: {
        synchronized (mMonitor) {
          if (mState != State.OPEN) {
            LOG.debug("ZooKeeper client session alive notification received while in state {}.",
                mState);
          } else {
            LOG.debug("ZooKeeper client session {} alive.", mZKClient.getSessionId());
          }
          mMonitor.notifyAll();
        }
        break;
      }
      case AuthFailed:
      case ConnectedReadOnly:
      case SaslAuthenticated: {
        LOG.error("Error establishing ZooKeeper client session: {}", event);
        // Nothing to do here.
        break;
      }
      case Disconnected: {
        LOG.warn("ZooKeeper client disconnected.");
        break;
      }
      case Expired: {
        synchronized (mMonitor) {
          LOG.warn("ZooKeeper client session {} expired.", mZKClient.getSessionId());
          if (mState == State.OPEN) {
            createZKClient();
          } else {
            LOG.debug("ZooKeeperClient in state {}; not reopening ZooKeeper session.", mState);
          }
        }
        break;
      }
      default: {
        throw new RuntimeException("Unexpected ZooKeeper event state: " + event);
      }
      }
    }
  }

  // -----------------------------------------------------------------------------------------------

  /** Address of the ZooKeeper quorum to interact with. */
  private final String mZKAddress;

  /** LockFactory which uses this ZooKeeperClient as a connection to ZooKeeper. */
  private final LockFactory mLockFactory = new LockFactory() {
    @Override
    public Lock create(String name) throws IOException {
      return new ZooKeeperLock(ZooKeeperClient.this, new File(name));
    }
  };

  /** States of a ZooKeeper client instance. */
  private static enum State {
    INITIALIZED,
    OPEN,
    CLOSED
  }

  /** Tracks the state of this ZooKeeper client. Access protected by mMonitor. */
  private State mState = State.INITIALIZED;

  /**
   * Represents the number of handles to this ZooKeeperClient. Access protected by
   * mMonitor.
   */
  private int mRetainCount = 1;

  /**
   * Current ZooKeeper session client.  Access protected by mMonitor.
   *
   *

   *
 Null before the client is opened and after the client is closed.

   *
 Set when the client is opened, reset when the client dies.

   *

   *
   *
 Even when this ZooKeeper client session is non null, it might not be established yet or
   *   may be dead.
   *

   */
  private ZooKeeper mZKClient = null;

  /**
   * Protects access to mState, mRetainCount, and mZKClient.
   * If locking both mMonitor and CACHE_MONITOR,
   * CACHE_MONITOR must be aquired first.
   */
  private final Object mMonitor = new Object();

  // -----------------------------------------------------------------------------------------------

  /**
   * Initializes a ZooKeeper client. The new ZooKeeperClient is returned with a retain count of one.
   *
   * @param zkAddress Address of the ZooKeeper quorum, as a comma-separated list of "host:port".
   */
  private ZooKeeperClient(String zkAddress) {
    this.mZKAddress = zkAddress;
    LOG.debug("Created {}", this);
  }

  /**
   * Starts the ZooKeeper client.
   *
   * @return this
   */
  private ZooKeeperClient open() {
    synchronized (mMonitor) {
      Preconditions.checkState(mState == State.INITIALIZED,
          "Cannot open ZooKeeperClient in state %s.", mState);
      mState = State.OPEN;
      Preconditions.checkState(mZKClient == null);
      createZKClient();
    }
    return this;
  }

  /**
   * Returns whether this ZooKeeperClient has been opened and not closed.
   *
   * @return whether this ZooKeeperClient has been opened and not closed.
   */
  public boolean isOpen() {
    synchronized (mMonitor) {
      return mState == State.OPEN;
    }
  }

  /**
   * Factory for ZooKeeper session clients.
   *
   *
 This returns immediately, but the ZooKeeper session is established asynchronously.

   *
   * @throws KijiIOException on I/O error.
   */
  private void createZKClient() {
    LOG.debug("Creating new ZooKeeper client for address {} in {}.", mZKAddress, this);
    try {
      synchronized (mMonitor) {
        mZKClient = new ZooKeeper(mZKAddress, SESSION_TIMEOUT, new SessionWatcher());
      }
    } catch (IOException ioe) {
      throw new KijiIOException(ioe);
    }
  }

  /**
   * Reports the ZooKeeper session client.
   *
   * @param timeout If no ZooKeeper session may be established within the specified timeout,
   *     in seconds, this fails and returns null.
   *     0 or negative means no timeout, ie. potentially wait forever.
   * @return A live ZooKeeper session client, or null.
   */
  public ZooKeeper getZKClient(double timeout) {

    // Absolute deadline, in seconds since the Epoch:
    final double absoluteDeadline = (timeout > 0.0) ? (Time.now() + timeout) : 0.0;

    synchronized (mMonitor) {
      while (absoluteDeadline == 0.0 || absoluteDeadline > Time.now()) {
        Preconditions.checkState(mState == State.OPEN,
            "Cannot get ZKClient %s in state %s.", this, mState);
        if ((mZKClient != null) && mZKClient.getState().isConnected()) {
          return mZKClient;
        } else {
          try {
            if (absoluteDeadline > 0) {
              final double waitTimeout = absoluteDeadline - Time.now();  // seconds
              mMonitor.wait((long) (waitTimeout * 1000.0));
            } else {
              mMonitor.wait();
            }
          } catch (InterruptedException ie) {
            throw new RuntimeInterruptedException(ie);
          }
        }
      }
    }
    return null;
  }

  /**
   * Reports the ZooKeeper session client.
   *
   *
 This may potentially wait forever: no timeout.

   *
   * @return the ZooKeeper session client.
   */
  public ZooKeeper getZKClient() {
    return getZKClient(0.0);
  }

  /** {@inheritDoc} */
  @Override
  public ZooKeeperClient retain() {
    LOG.debug("Retaining {}", this);
    synchronized (mMonitor) {
      Preconditions.checkState(mState == State.OPEN,
          "Cannot retain ZooKeeperClient %s in state %s.", this, mState);
      mRetainCount += 1;
    }
    return this;
  }

  /** {@inheritDoc} */
  @Override
  public void release() throws IOException {
    LOG.debug("Releasing {}", this);
    synchronized (CACHE_MONITOR) {
      synchronized (mMonitor) {
        Preconditions.checkState(mState == State.OPEN,
            "Cannot release ZooKeeperClient %s in state %s.", this, mState);
        mRetainCount -= 1;
        if (mRetainCount == 0) {
          close();
        }
      }
    }
  }

  /**
   * Closes this ZooKeeper client.  Should only be called by {@link #release()} or
   * {@link #finalize()}.
   */
  private void close() {
    LOG.debug("Closing {}", this);
    synchronized (CACHE_MONITOR) {
      synchronized (mMonitor) {
        Preconditions.checkState(mState == State.OPEN,
            "Cannot close ZooKeeperClient %s in state %s.", this, mState);
        mState = State.CLOSED;
        ZOOKEEPER_CACHE.remove(mZKAddress);
        if (mZKClient == null) {
          // Nothing to close:
          return;
        }
        try {
          mZKClient.close();
          mZKClient = null;
        } catch (InterruptedException ie) {
          throw new RuntimeInterruptedException(ie);
        }
      }
    }
  }

  /**
   * See {@link ZooKeeper#create(String, byte[], List, CreateMode)}.
   *
   * @param path to desired node.
   * @param data the desired node should contain by default.
   * @param acl is the Access Control List the desired node will use.
   * @param createMode specifies whether the node to be created is ephemeral and/or sequential.
   * @return the actual path of the created node.
   * @throws KeeperException on ZooKeeper errors.
   *     Connection related errors are handled by retrying the operations.
   */
  public File create(
      File path,
      byte[] data,
      List<ACL> acl,
      CreateMode createMode)
      throws KeeperException {

    while (true) {
      try {
        return new File(getZKClient().create(path.toString(), data, acl, createMode));
      } catch (InterruptedException ie) {
        throw new RuntimeInterruptedException(ie);
      } catch (ConnectionLossException ke) {
        LOG.debug("ZooKeeper connection lost.", ke);
      } catch (SessionExpiredException see) {
        LOG.debug("ZooKeeper session expired.", see);
      } catch (SessionMovedException sme) {
        LOG.debug("ZooKeeper session moved.", sme);
      }
      Time.sleep(ZOOKEEPER_RETRY_DELAY);
      LOG.debug("Retrying create({}, {}, {}, {}).",
          path, Bytes.toStringBinary(data), acl, createMode);
    }
  }

  /**
   * See {@link ZooKeeper#exists(String, boolean)}.
   *
   * @param path of a node.
   * @return the stat of the node; null if the node does not exist.
   * @throws KeeperException on ZooKeeper errors.
   *     Connection related errors are handled by retrying the operations.
   */
  public Stat exists(File path) throws KeeperException {
    while (true) {
      try {
        return getZKClient().exists(path.toString(), false);
      } catch (InterruptedException ie) {
        throw new RuntimeInterruptedException(ie);
      } catch (ConnectionLossException ke) {
        LOG.debug("ZooKeeper connection lost.", ke);
      } catch (SessionExpiredException see) {
        LOG.debug("ZooKeeper session expired.", see);
      } catch (SessionMovedException sme) {
        LOG.debug("ZooKeeper session moved.", sme);
      }
      Time.sleep(ZOOKEEPER_RETRY_DELAY);
      LOG.debug("Retrying exists({}).", path);
    }
  }

  /**
   * See {@link ZooKeeper#exists(String, Watcher)}.
   *
   * @param path of a node.
   * @param watcher triggered by a successful operation that sets data on the node or
   *     creates/deletes the node.
   * @return the stat of the node.
   * @throws KeeperException on ZooKeeper errors.
   *     Connection related errors are handled by retrying the operations.
   */
  public Stat exists(File path, Watcher watcher) throws KeeperException {
    while (true) {
      try {
        return getZKClient().exists(path.toString(), watcher);
      } catch (InterruptedException ie) {
        throw new RuntimeInterruptedException(ie);
      } catch (ConnectionLossException ke) {
        LOG.debug("ZooKeeper connection lost.", ke);
      } catch (SessionExpiredException see) {
        LOG.debug("ZooKeeper session expired.", see);
      } catch (SessionMovedException sme) {
        LOG.debug("ZooKeeper session moved.", sme);
      }
      Time.sleep(ZOOKEEPER_RETRY_DELAY);
      LOG.debug("Retrying exists({}).", path);
    }
  }

  /**
   * See {@link ZooKeeper#getData(String, Watcher, Stat)}.
   *
   * @param path of a node.
   * @param watcher triggered by a successful operation that sets data on the node or
   *     deletes the node.
   * @param stat of the node.
   * @return the data contained within the node.
   * @throws KeeperException on ZooKeeper errors.
   *     Connection related errors are handled by retrying the operations.
   */
  public byte[] getData(File path, Watcher watcher, Stat stat)
      throws KeeperException {
    while (true) {
      try {
        return getZKClient().getData(path.toString(), watcher, stat);
      } catch (InterruptedException ie) {
        throw new RuntimeInterruptedException(ie);
      } catch (ConnectionLossException ke) {
        LOG.debug("ZooKeeper connection lost.", ke);
      } catch (SessionExpiredException see) {
        LOG.debug("ZooKeeper session expired.", see);
      } catch (SessionMovedException sme) {
        LOG.debug("ZooKeeper session moved.", sme);
      }
      Time.sleep(ZOOKEEPER_RETRY_DELAY);
      LOG.debug("Retrying getData({}).", path);
    }
  }

  /**
   * See {@link ZooKeeper#setData(String, byte[], int)}.
   *
   * @param path of a node.
   * @param data to set.
   * @param version of the node.
   * @return the stat of the node.
   * @throws KeeperException on ZooKeeper errors.
   *     Connection related errors are handled by retrying the operations.
   */
  public Stat setData(File path, byte[] data, int version) throws KeeperException {
    while (true) {
      try {
        return getZKClient().setData(path.toString(), data, version);
      } catch (InterruptedException ie) {
        throw new RuntimeInterruptedException(ie);
      } catch (ConnectionLossException ke) {
        LOG.debug("ZooKeeper connection lost.", ke);
        LOG.debug("Retrying setData({}, {}, {}).", path, Bytes.toStringBinary(data), version);
      } catch (SessionExpiredException see) {
        LOG.debug("ZooKeeper session expired.", see);
      } catch (SessionMovedException sme) {
        LOG.debug("ZooKeeper session moved.", sme);
      }
      Time.sleep(ZOOKEEPER_RETRY_DELAY);
    }
  }

  /**
   * See {@link ZooKeeper#getChildren(String, Watcher, Stat)}.
   *
   * @param path of a parent node.
   * @param watcher to trigger upon parent node deletion or creation/deletion of a child node.
   * @param stat of the provided parent node.
   * @return an unordered array of the parent node's children.
   * @throws KeeperException on ZooKeeper errors.
   *     Connection related errors are handled by retrying the operations.
   */
  public List<String> getChildren(File path, Watcher watcher, Stat stat)
      throws KeeperException {
    while (true) {
      try {
        return getZKClient().getChildren(path.toString(), watcher, stat);
      } catch (InterruptedException ie) {
        throw new RuntimeInterruptedException(ie);
      } catch (ConnectionLossException ke) {
        LOG.debug("ZooKeeper connection lost.", ke);
      } catch (SessionExpiredException see) {
        LOG.debug("ZooKeeper session expired.", see);
      } catch (SessionMovedException sme) {
        LOG.debug("ZooKeeper session moved.", sme);
      }
      Time.sleep(ZOOKEEPER_RETRY_DELAY);
      LOG.debug("Retrying getChildren({}).", path);
    }
  }

  /**
   * See {@link ZooKeeper#delete(String, int)}.
   *
   * @param path of the node to delete.
   * @param version of the node to delete.
   * @throws KeeperException on ZooKeeper errors.
   *     Connection related errors are handled by retrying the operations.
   */
  public void delete(File path, int version) throws KeeperException {
    while (true) {
      try {
        getZKClient().delete(path.toString(), version);
        return;
      } catch (InterruptedException ie) {
        throw new RuntimeInterruptedException(ie);
      } catch (ConnectionLossException ke) {
        LOG.debug("ZooKeeper connection lost.", ke);
      } catch (SessionExpiredException see) {
        LOG.debug("ZooKeeper session expired.", see);
      } catch (SessionMovedException sme) {
        LOG.debug("ZooKeeper session moved.", sme);
      }
      Time.sleep(ZOOKEEPER_RETRY_DELAY);
      LOG.debug("Retrying delete({}, {}).", path, version);
    }
  }

  /**
   * Creates a ZooKeeper node and all its parents, if necessary.
   *
   * @param path of the node to create.
   * @throws KeeperException on I/O error.
   */
  public void createNodeRecursively(File path)
      throws KeeperException {

    if (exists(path) != null) {
      return;
    }

    if (path.getPath().equals("/")) {
      // No need to create the root node "/" :
      return;
    }
    final File parent = path.getParentFile();
    if (parent != null) {
      createNodeRecursively(parent);
    }
    try {
      LOG.debug("Creating ZooKeeper node: {}", path);
      final File createdPath =
          this.create(path, EMPTY_BYTES, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
      Preconditions.checkState(createdPath.equals(path));
    } catch (NodeExistsException exn) {
      LOG.debug("ZooKeeper node already exists: {}", path);
    }
  }

  /**
   * Return a LockFactory implementation which utilizes this ZooKeeperClient.
   *
   * @return a LockFactory which uses this ZooKeeperClient.
   */
  public LockFactory getLockFactory() {
    return mLockFactory;
  }

  /**
   * Removes a ZooKeeper node and all of its children, if necessary.
   *
   * @param path of the node to remove.
   * @throws KeeperException on I/O error.
   */
  public void deleteNodeRecursively(File path) throws KeeperException {
    Stat stat = exists(path);  // Race condition if someone else updates the znode in the meantime

    if (stat == null) {
      return;
    }

    List<String> children = getChildren(path, null, null);
    for (String child : children) {
      deleteNodeRecursively(new File(path, child));
    }
    delete(path, stat.getVersion());
  }

  /**
   * Returns a string representation of this object.
   * @return A string representation of this object.
   */
  public String toString() {
    synchronized (mMonitor) {
      return Objects.toStringHelper(getClass())
          .add("this", System.identityHashCode(this))
          .add("zk_address", mZKAddress)
          .add("retain_count", mRetainCount)
          .toString();
    }
  }

  /** {@inheritDoc} */
  @Override
  protected void finalize() throws Throwable {
    synchronized (CACHE_MONITOR) {
      synchronized (mMonitor) {
        if (mState != State.CLOSED) {
          LOG.warn("Finalizing unreleased ZooKeeperClient {}.", this);
          close();
        }
      }
    }
    super.finalize();
  }
}


text:
<!DOCTYPE html>

	<title>Portfolio</title>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0" />
	<link rel="stylesheet" type="text/css" href="css/reset.css">
	<link rel="stylesheet" type="text/css" href="css/main.css">

DChen101

Home

About

Blog

Contact

About

Linkedin: https://www.linkedin.com/in/dchen101

 Looking to be a part of meaningful company. My hope is to learn and grow with a great team, and in the process better myself and those around me.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Concordion.Integration;

namespace Concordion.Spec.Concordion.Command.AssertEquals
{
    [ConcordionTest]
    public class SupportedElementsTest
    {
        public string process(string snippet)
        {
            long successCount = new TestRig()
                .WithStubbedEvaluationResult("Fred")
                .ProcessFragment(snippet)
                .SuccessCount;

            return successCount == 1 ? snippet : "Did not work";
        }
    }
}


text:
<?php

/**
 * This is the model class for table "{{news}}".
 *
 * The followings are the available columns in table '{{news}}':
 * @property integer $id
 * @property string $title
 * @property string $alias
 * @property string $image
 * @property string $description
 * @property string $content
 * @property integer $priority
 * @property integer $is_published
 * @property string $create_time
 * @property string $update_time
 *  @property string $news_time
 *
 * The followings are the available model relations:
 * @property NewsMiddle[] $newsMiddles
 */
class News extends CActiveRecord
{
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{news}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('title', 'required'),
			array('priority, is_published', 'numerical', 'integerOnly'=>true),
			array('title, image', 'length', 'max'=>128),
			array('alias', 'length', 'max'=>64),
			array('description, content, create_time, update_time, news_time', 'safe'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, title, alias, image, description, content, priority, is_published, create_time, update_time, news_time', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'newsMiddles' => array(self::HAS_MANY, 'NewsMiddle', 'news_id'),
			'categories'=>array(self::MANY_MANY, 'NewsCategories','sd_news_middle(news_id, category_id)'),
		);
	}
	public function behaviors(){
		return array(
			'CTimestampBehavior' => array(
				'class' => 'zii.behaviors.CTimestampBehavior',
				'createAttribute' => 'create_time',
				'updateAttribute' => 'update_time',
			),
			'SlugBehavior' => array(
				'class' => 'application.models.behaviors.SlugBehavior',
				'slug_col' => 'alias',
				'title_col' => 'title',
				//'max_slug_chars' => 125,
			)
    );
	}
	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'title' => 'Title',
			'alias' => 'Alias',
			'image' => 'Image',
			'description' => 'Description',
			'content' => 'Content',
			'priority' => 'Priority',
			'is_published' => 'Is Published',
			'create_time' => 'Create Time',
			'update_time' => 'Update Time',
			'news_time' => 'News Time',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('title',$this->title,true);
		$criteria->compare('alias',$this->alias,true);
		$criteria->compare('image',$this->image,true);
		$criteria->compare('description',$this->description,true);
		$criteria->compare('content',$this->content,true);
		$criteria->compare('priority',$this->priority);
		$criteria->compare('is_published',$this->is_published);
		$criteria->compare('create_time',$this->create_time,true);
		$criteria->compare('update_time',$this->update_time,true);
		$criteria->compare('news_time',$this->news_time,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
			'sort'=>array(
				'defaultOrder'=>'priority ASC',
				'multiSort' =>true,
				'attributes' => array(
					'rating'=> array(
						'DESC' => 'create_time'
					)
				)
			),
		));
	}
	public function searchByCategory($category_id)
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;
		$criteria->with=array('categories');
        $criteria->together = true;
		$criteria->compare('id',$this->id);
		$criteria->compare('title',$this->title,true);
		$criteria->compare('alias',$this->alias,true);
		$criteria->compare('image',$this->image,true);
		$criteria->compare('description',$this->description,true);
		$criteria->compare('content',$this->content,true);
		$criteria->compare('priority',$this->priority);
	//	$criteria->compare('categories.category_id',$category_id,true);
		$criteria->compare('is_published',$this->is_published);
		$criteria->compare('create_time',$this->create_time,true);
		$criteria->compare('update_time',$this->update_time,true);
		$criteria->compare('news_time',$this->news_time,true);
		//$criteria->compare('categories.name', NewsCategories::model()->name);
		//$criteria->compare('categories.alias', NewsCategories::model()->alias);
		//$criteria->addCondition('`categories`.`id` = :id');
		//$criteria->params = array(':id' => $category_id);
		$criteria->compare("'categories'.'id'", $category_id);
		//$criteria->addCondition('sd_news_categories.id = '.$category_id);
		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return News the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
}


text:
<!--Form for adding new dancies.-->
<gz-Dance-form dancies="vm.dancies"></gz-Dance-form>


text:
import styles from './styles';
import combineStyles from '../internal/combine-styles';

const root = (type, overrideStyle) => (
  combineStyles(combineStyles(styles.root, styles[type]), overrideStyle)
);

export default {
  root
};


text:
class AdminUser < ApplicationRecord
  has_secure_password

  validates :first_name, :last_name, presence: true
  validates :email, presence: true, email: true, uniqueness: true
  validates :password, length: { minimum: 8 }, allow_nil: true
end


text:
name: "\U0001F4DA Documentation"
about: Did you find errors, problems, or anything unintelligible in the docs (https://pendulum.eustace.io/docs)?
title: ''
labels: 'Documentation'
assignees: ''

---

<!--
  Hi there! Thank you for discovering and submitting an issue with our documentation.

  Before you submit this; let's make sure of a few things.
  Please make sure the following boxes are ticked if they are correct.
  If not, please try and fulfill these first.
-->

<!-- Checked checkbox should look like this: [x] -->
- [ ] I have searched the [issues](https://github.com/sdispater/pendulum/issues) of this repo and believe that this is not a duplicate.

## Issue
<!-- Now feel free to write your issue, but please be descriptive! Thanks again 🙌 ❤ -->


text:
package org.jgroups.util;

import org.jgroups.annotations.Experimental;

import java.util.function.Consumer;

/**
 * Ref-counted implementation; can be used by message implementations.

 * Note that this class is experimental and may get removed without notice. The point of it is to get experience with
 * ref counted messages and see if they're needed or not.

 * See https://issues.redhat.com/browse/JGRP-2417 for details
 * @author Bela Ban
 * @since  5.1.0
 */
@Experimental
public class RefcountImpl<T> {
    protected byte        refcount;
    protected Consumer<T> release_code;

    public RefcountImpl() {
    }

    public RefcountImpl(Consumer<T> c) {
        this.release_code=c;
    }

    public synchronized byte getRefcount() {
        return refcount;
    }

    public synchronized RefcountImpl<T> incr() {
        refcount++;
        return this;
    }

    public synchronized RefcountImpl<T> decr(T t) {
        byte tmp=--refcount;
        if(tmp == 0)
            release(t);
        else if(tmp < 0)
            refcount=0;
        return this;
    }

    public RefcountImpl<T> onRelease(Consumer<T> rc) {
        release_code=rc;
        return this;
    }

    @Override
    public String toString() {
        return String.format("%s (refcnt=%d)", super.toString(), refcount);
    }

    protected void release(T t) {
        if(release_code != null)
            release_code.accept(t);
    }
}


text:
/*
 *
 */
package net.community.chest.ui.helpers;

import org.w3c.dom.Element;

/**
 *
Copyright 2008 as per GPLv2

 *
 *
Also provides "sections" definitions sub-{@link Element}-s

 * @author Lyor G.
 * @since Dec 11, 2008 3:30:26 PM
 */
public interface XmlContainerComponentInitializer extends XmlElementComponentInitializer {
    /**
     * @return A {@link java.util.Map} of sections (may be null/empty) - key=section name,
     * value=section definition {@link Element}
     */
    SectionsMap getSectionsMap ();
    // CAVEAT EMPTOR may be too late if called after "layoutSection"
    void setSectionsMap (SectionsMap sectionsMap);
    /**
     * @param name Name of section to be added (ignored if null/empty)
     * @param elem Section definition {@link Element} (ignored if null)
     * @return Previous definition (null if none)
     */
    // CAVEAT EMPTOR may be too late if called after "layoutSection"
    Element addSection (String name, Element elem);
    /**
     * @param name Section name in the sections map
     * @return The section XML {@link Element} (null if none)
     * @see #getSectionsMap()
     */
    Element getSection (String name);
    /**
     * Invoked by {@link #getSection(Enum)} in order to resolve the section
     * name
     * @param <E> The {@link Enum} type being used
     * @param v The value
     * @return The {@link String} to use for {@link #getSection(String)} call.
     * Default={@link Enum#toString()}
     */
    <E extends Enum<E>> String getSectionName (E v);
    <E extends Enum<E>> Element getSection (E v);
    /**
     * @param name Section name
     * @param elem Section XML {@link Element}
     * @throws RuntimeException If failed to layout the section
     */
    void layoutSection (String name, Element elem) throws RuntimeException;
}


text:
package com.floreysoft.jmte;

import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Callable;

import com.floreysoft.jmte.token.Token;

/**
 * Default implementation of the model adapter.
 *

 * Does the object traversal using the "." operator. Resolved value will be
 * checked if it is either a {@link Processor} or a {@link Callable} in which
 * case the final resolved value is computed by calling those executable
 * objects.
 *

 *
 *

 * Inherit from this adapter if you want a slight change of this behavior and
 * set your new adaptor on the engine
 * {@link Engine#setModelAdaptor(ModelAdaptor)} .
 *

 */
public class DefaultModelAdaptor implements ModelAdaptor {

	protected Map<Class<?>, Map<String, Member>> cache = new HashMap<Class<?>, Map<String, Member>>();

	@Override
	@SuppressWarnings("rawtypes")
	public Object getValue(TemplateContext context, Token token,
			List<String> segments, String expression) {
		Object value = traverse(segments, context.model, context.errorHandler, token);
		// if value implements both, we use the more specialized implementation
		if (value instanceof Processor) {
			value = ((Processor) value).eval(context);
		} else if (value instanceof Callable) {
			try {
				value = ((Callable) value).call();
			} catch (Exception e) {
			}
		}
		return value;
	}

	protected Object traverse(List<String> segments, Map<String, Object> model,
			ErrorHandler errorHandler, Token token) {
		if (segments.size() == 0) {
			return null;
		}
		String objectName = segments.get(0);
		Object value = model.get(objectName);

		value = traverse(value, segments, 1, errorHandler, token);
		return value;
	}

	protected Object traverse(Object o, List<String> attributeNames, int index,
			ErrorHandler errorHandler, Token token) {
		Object result;
		if (index >= attributeNames.size()) {
			result = o;
		} else {
			if (o == null) {
				return null;
			}
			String attributeName = attributeNames.get(index);
			Object nextStep = nextStep(o, attributeName, errorHandler, token);
			result = traverse(nextStep, attributeNames, index + 1,
					errorHandler, token);
		}
		return result;
	}

	@SuppressWarnings("rawtypes")
	protected Object nextStep(Object o, String attributeName,
			ErrorHandler errorHandler, Token token) {
		Object result;
		if (o instanceof String) {
			errorHandler.error("no-call-on-string", token, new ModelBuilder(
					"receiver", o.toString()).build());
			return o;
		} else if (o instanceof Map) {
			Map map = (Map) o;
			result = map.get(attributeName);
		} else {
			try {
				result = getPropertyValue(o, attributeName);
			} catch (Exception e) {
				errorHandler.error("property-access-error", token,
						new ModelBuilder("property", attributeName, "object",
								o, "exception", e).build());
				result = "";
			}
		}
		return result;
	}

	@SuppressWarnings("rawtypes")
	protected Object getPropertyValue(Object o, String propertyName) {
		try {
			// XXX this is so strange, can not call invoke on key and value for
			// Map.Entry, so we have to get this done like this:
			if (o instanceof Map.Entry) {
				final Map.Entry entry = (Entry) o;
				if (propertyName.equals("key")) {
					final Object result = entry.getKey();
					return result;
				} else if (propertyName.equals("value")) {
					final Object result = entry.getValue();
					return result;
				}

			}
			boolean valueSet = false;
			Object value = null;
			Member member = null;
			final Class<?> clazz = o.getClass();
			Map<String, Member> members = cache.get(clazz);
			if (members == null) {
				members = new HashMap<String, Member>();
				cache.put(clazz, members);
			} else {
				member = members.get(propertyName);
				if (member != null) {
					if (member.getClass() == Method.class)
						return ((Method) member).invoke(o);
					if (member.getClass() == Field.class)
						return ((Field) member).get(o);
				}
			}

			final String suffix = Character.toUpperCase(propertyName.charAt(0))
					+ propertyName.substring(1);
			final Method[] declaredMethods = clazz.getMethods();
			for (Method method : declaredMethods) {
				if (Modifier.isPublic(method.getModifiers())
						&& (method.getName().equals("get" + suffix) || method
								.getName().equals("is" + suffix))) {
					value = method.invoke(o, (Object[]) null);
					valueSet = true;
					member = method;
					break;

				}
			}
			if (!valueSet) {
				final Field field = clazz.getField(propertyName);
				if (Modifier.isPublic(field.getModifiers())) {
					value = field.get(o);
					member = field;
					valueSet = true;
				}
			}
			if (valueSet) {
				members.put(propertyName, member);
			}
			return value;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}


text:
package me.pjq.jacocoandroid;

import android.graphics.Bitmap;
import android.support.v4.app.FragmentActivity;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

/**
 * Created by pengjianqing on 7/21/14.
 */
public class VolleyActivity extends FragmentActivity{

    public void volley(){
        RequestQueue requestQueue  = Volley.newRequestQueue(getApplicationContext());

        String url = "";
        JsonObjectRequest request = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        requestQueue.add(request);

        ImageRequest imageRequest = new ImageRequest(url, new Response.Listener<Bitmap>() {
            @Override
            public void onResponse(Bitmap response) {

            }
        }, 1024, 1024, null, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        requestQueue.add(imageRequest);
    }
}


text:
package com.idea4j.framework.mvc;

import com.idea4j.framework.FrameworkConstant;
import com.idea4j.framework.InstanceFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 前端控制器
 *
 * @author andaicheng
 */
@WebServlet(urlPatterns = "/*", loadOnStartup = 0)
public class DispatcherServlet extends HttpServlet {

    private static final long serialVersionUID = 6111456799058930128L;
    private static final Logger LOGGER = LoggerFactory.getLogger(DispatcherServlet.class);

    private static final String FORWARD_SLASH = "/";
    private static final String BACK_SLASH = "\\";
    private final transient HandlerInvoker handlerInvoker = InstanceFactory.getHandlerInvoker();
    private final transient HandlerMapping handlerMapping = InstanceFactory.getHandlerMapping();
    private final transient HandlerExceptionResolver exceptionResolver = InstanceFactory.getHandlerExceptionResolver();

    @Override
    public void init() throws ServletException {
        LOGGER.info("{IDEA} inited");
        super.init();
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        long start = System.currentTimeMillis();
        // 设置请求编码方式
        request.setCharacterEncoding(FrameworkConstant.UTF_8);
        // 获取当前请求相关数据
        String currentRequestMethod = request.getMethod();
        String currentRequestPath = WebUtil.getRequestPath(request);
        LOGGER.debug("[Idea] {}:{}", currentRequestMethod, currentRequestPath);

        // 将"/"请求重定向到首页
        if (FORWARD_SLASH.equals(currentRequestPath)) {
            WebUtil.redirectRequest(FrameworkConstant.HOME_PAGE, request, response);
            return;
        }

        // 去掉当前请求路径末尾的"/"
        if (currentRequestPath.endsWith(FORWARD_SLASH)) {
            currentRequestPath = currentRequestPath.substring(0, currentRequestPath.length() - 1);
        }

        // 获取 Handler
        Handler handler = handlerMapping.getHandler(currentRequestMethod, currentRequestPath);
        // 若未找到 Action,则跳转到 404 页面
        if (handler == null) {
            LOGGER.error("{} handler not found.", currentRequestPath);
            WebUtil.sendError(HttpServletResponse.SC_NOT_FOUND, "", response);
            return;
        }

        // 初始化 DataContext
        DataContext.init(request, response);
        try {
            // 调用 Handler
            handlerInvoker.invokeHandler(request, response, handler);
        } catch (Exception e) {
            LOGGER.error("invokeHandler error", e);
            // 处理 Action 异常
            exceptionResolver.resolveHandlerException(request, response, e);
        } finally {
            // 销毁 DataContext
            DataContext.destroy();
            LOGGER.debug("service timing: {}", System.currentTimeMillis() - start);
        }
    }

    @Override
    public void destroy() {
        LOGGER.info("{IDEA} destroyed");
        super.destroy();
    }

}


text:
package clarence.test_driver;

import java.util.ArrayList;

import clarence.key_file.KeywordFile;
import clarence.key_reader.CommandEntry;

public class CommandOptionsState implements ApplicationState{

	private int commandIndex;
	private KeywordFile file;
	private KeyFileEditorView view;

	public CommandOptionsState(KeyFileEditorView view, KeywordFile file, int commandIndex) {
		this.view = view;
		this.file = file;
		this.commandIndex = commandIndex;
		showMessage();
	}

	private void showMessage() {
		view.clearPrompt();
		CommandEntry command = file.getCommand(commandIndex);
		view.appendPrompt(("SELECT OPTION FOR COMMAND " + command.name() ));
		view.appendPrompt(("1. PRINT COMMAND SUMMARY") );
		view.appendPrompt("2. LIST KEYWORDS" );
		view.appendPrompt("3. VIEW KEYWORD FORMATTED" );
		view.appendPrompt("4. VIEW KEYWORD RAW" );
		view.appendPrompt("5. ADD KEYWORD" );
		view.appendPrompt("6. EDIT KEYWORD" );
		view.appendPrompt("7. BACK" );
	}

	@Override
	public void command(String command) throws InvalidCommandException{
		try {
			int option = Integer.parseInt(command);
			if (option == 1) {
				view.clearOutput();
				view.appendOutput(file.commandSummary(commandIndex));
				reload();
			} else if (option == 2) {
				view.clearOutput();
				view.appendOutput("KEYWORD NAMES" );
				ArrayList<String> names = file.keywordNames(commandIndex);
				for (int i = 0; i < names.size(); i++) {
					view.appendOutput(((i + 1) + ": " + names.get(i) ));
				}
				reload();
			} else if (option == 3) {
				view.setApplicationState(new KeywordFormattedState(view,file,commandIndex));
			} else if (option == 4) {
				view.setApplicationState(new KeywordRawState(view,file,commandIndex));
			} else if (option == 5) {
				view.setApplicationState(new AddKeywordOptionsState(view,file,commandIndex));
			} else if (option == 6) {

			} else if (option == 7) {
				view.setApplicationState(new RootApplicationState(view,file));
			} else {
				throw new InvalidCommandException();
			}
		} catch (NumberFormatException e) {
			throw new InvalidCommandException();
		}

	}

	@Override
	public void reload() {
		showMessage();
	}

}


text:
describe("shared object storage", () => {
  beforeEach(() => {
    cy.elektraLogin(
      Cypress.env("TEST_DOMAIN"),
      Cypress.env("TEST_USER"),
      Cypress.env("TEST_PASSWORD")
    )
  })

  it("open object storage and see that I need one of the respective roles", () => {
    cy.visit(`/${Cypress.env("TEST_DOMAIN")}/test/object-storage/`)
    cy.contains('[data-test=page-title]','Object Storage')
    cy.contains('Object Storage can only be used when your user account has the admin or objectstore_admin or objectstore_viewer role for this project.')
  })

})


text:
"""
    Taken from the python documentation, distributed under
    that same license
"""

import collections

class OrderedClass(type):
    """
    Metaclass that stores class attributes in a member called
    'members'. If you subclass something that uses this metaclass,
    the base class members will be listed before the subclass
    """

    # TODO: this isn't required in Python 3.6 due to PEP 520

    @classmethod
    def __prepare__(metacls, name, bases, **kwds):
        return collections.OrderedDict()

    def __new__(cls, name, bases, namespace, **kwds):
        result = type.__new__(cls, name, bases, dict(namespace))

        members = []
        members.extend(getattr(result, "members", ()))

        # because of the potential of multiple inheritance/mixins, need
        # to grab members list from all bases
        for base in bases:
            members.extend(getattr(base, "members", ()))

        members.extend(namespace)

        seen = set()
        result.members = tuple(m for m in members if not (m in seen or seen.add(m)))
        return result