text:
import PropTypes from 'prop-types';
/* eslint-disable no-shadow */
import React from 'react';
import Flexbox from 'flexbox-react';
import getContext from 'recompose/getContext';
import Container from './Container';
import Content from './Content';
import FormError from './FormError';
import Header from './components/header';
import Avatar from './components/avatar';
import PasswordField from './components/password';
import SubmitButton from './components/submitButton';

const ResetPasswordFields = ({ children }) =>
  <Flexbox flexDirection="column" justifyContent="center" alignItems="center">
    {children}
  </Flexbox>;

ResetPasswordFields.propTypes = {
  children: PropTypes.node,
};

const LoginButton = getContext({
  setFormType: PropTypes.func,
})(({ setFormType, ...otherProps }) =>
  <Flexbox>
    <a
      href="#/"
      style={{
        fontFamily: 'Roboto',
        textDecoration: 'none',
        fontSize: 16,
      }}
      onClick={() => setFormType('login')}
      {...otherProps}
    >
      Log in
    </a>
  </Flexbox>);

const Footer = ({ ...otherProps }) =>
  <LoginButton {...otherProps} />;

Footer.propTypes = {
  SignupButton: PropTypes.node,
};

export default {
  Container,
  Content,
  Avatar,
  ResetPasswordFields,
  ResetPasswordPasswordField: PasswordField,
  ResetPasswordPasswordConfirmField: PasswordField,
  ResetPasswordButton: SubmitButton,
  Header,
  Footer,
  FormError,
};


text:
/**
 * @fileoverview Complete helper functions for generating PHP for
 *     blocks.  This is the entrypoint for php_compressed.js.
 * @suppress {extraRequire}
 */
'use strict';

goog.module('Blockly.PHP.all');

const moduleExports = goog.require('Blockly.PHP');
goog.require('Blockly.PHP.colour');
goog.require('Blockly.PHP.lists');
goog.require('Blockly.PHP.logic');
goog.require('Blockly.PHP.loops');
goog.require('Blockly.PHP.math');
goog.require('Blockly.PHP.procedures');
goog.require('Blockly.PHP.texts');
goog.require('Blockly.PHP.variables');
goog.require('Blockly.PHP.variablesDynamic');

exports = moduleExports;

redpajama_set_name: RedPajamaGithub


text:
@charset "utf-8";

.gallery .wrapper {
  position: relative;
  z-idnex: 1;
  overflow: hidden;
}
.gallery .viewport {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  list-style-type: none;
  padding: 0;
  margin: 0;
}
.gallery .viewport .item {
  display: none;
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
}
.gallery .viewport .item img {
  display: block;
  max-width: 100%;
  margin: 0 auto;
}
.gallery .viewport .item.active {
  display: block;
}
.gallery .viewport .item:first-child {
  display: block;
}
.gallery .trigger-next, .gallery .trigger-previous {
  position: absolute;
  top: 50%;
  z-index: 101;
  margin: 0;
  font-size: 12px;
  line-height: 12px;
  margin-top: -10px;
  background: rgba(0, 0, 0, 0.6);
}
.gallery .trigger-next {
  right: 0;
}
.gallery .trigger-previous {
  left: 0;
}
.gallery .trigger-next a, .gallery .trigger-previous a {
  display: none;
  float: left;
  padding: 4px;
}
.gallery .trigger-next a:hover, .gallery .trigger-previous a:hover {
  color: white;
}
.gallery nav {
  text-align: center;
  padding-top: 15px;
}
.gallery nav a {
  display: none;
  font-size: 11px;
  line-height: 11px;
  padding: 3px 6px 4px 6px;
  display: -moz-inline-stack;
  display: inline-block;
  vertical-align: middle;
  *vertical-align: auto;
  zoom: 1;
  *display: inline;
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
  -ms-border-radius: 10px;
  -o-border-radius: 10px;
  border-radius: 10px;
  border: 1px solid #e5e5e5;
  background: #fff;
}
.gallery nav a:hover {
  background: #f9f9f9;
}
.gallery nav .active {
  color: #fff !important;
  border-color: #39c !important;
  background: #39c !important;
}
.gallery .item-content {
  padding: 70px 100px 25px;
  background: white;
}


text:
/**
 * Special options passed to Repository#remove method.
 */
export interface RemoveOptions {

    /**
     * Additional data to be passed with remove method.
     * This data can be used in subscribers then.
     */
    data?: any;

}


text:
<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Language Lines
    |--------------------------------------------------------------------------
    |
    | The following language lines are used during authentication for various
    | messages that we need to display to the user. You are free to modify
    | these language lines according to your application's requirements.
    |
    */

    'failed'        => 'Brukernavn eller passord stemmer ikke.',
    'general_error' => 'Du har ikke tilgang til at utføre denne handling.',
    'password_used' => 'You can not set a password that you have previously used.',
    'socialite'     => [
        'unacceptable' => ':provider kan ikke brukes som login.',
    ],
    'throttle' => 'For mange mislykkede forsøk. Prøv igen om :seconds sekunder.',
    'unknown'  => 'Det oppstod en ukjent feil.',
];


text:
'use strict';

declare const angular: any;

import babelTestMsg from './to-import';
console.log(babelTestMsg);

angular.module('test', [])
	.controller('testCtrl', function($scope) {

	})
	.factory('testFactory', function($cacheFactory) {
		return {};
	})
	.service('testNotAnnotated', function() {
		return {};
	})
	.directive('testDirective', function ($timeout) {
		return {
			restrict: 'E',
			controller: function($scope) {

			}
		};
	})
	.controller('someCtrl', someCtrl);

function toAnnotate($scope) {
  	'ngInject';
	console.log('hi'); // should be function body, otherwise babel remove directive prologue
}

class someCtrl {
	constructor($scope) {
		this.doSomething();
	}

	doSomething() {

	}
}

console.log('after annotated function');


text:
import datetime

class datedelta:

    __slots__ = ["_years", "_months", "_days"]

    def __init__(self, *, years=0, months=0, days=0):
        int_years = int(years)
        int_months = int(months)
        int_days = int(days)

        if int_years != years:
            raise ValueError("years must be an integer value")
        if int_months != months:
            raise ValueError("months must be an integer value")
        if int_days != days:
            raise ValueError("days must be an integer value")

        self._years = int_years
        self._months = int_months
        self._days = int_days

    # datedelta must be immutable to be hashable.

    @property
    def years(self):
        return self._years

    @property
    def months(self):
        return self._months

    @property
    def days(self):
        return self._days

    def __repr__(self):
        args = []
        if self._years != 0:
            args.append(f"years={self._years}")
        if self._months != 0:
            args.append(f"months={self._months}")
        if self._days != 0:
            args.append(f"days={self._days}")
        return f"datedelta.datedelta({', '.join(args)})"

    def __str__(self):
        bits = []
        if self._years != 0:
            bits.append(f"{self._years} year{_s(self._years)}")
        if self._months != 0:
            bits.append(f"{self._months} month{_s(self._months)}")
        if self._days != 0:
            bits.append(f"{self._days} day{_s(self._days)}")
        return ", ".join(bits) or "0 days"

    def __eq__(self, other):
        if isinstance(other, datedelta):
            return (
                self._years == other._years
                and self._months == other._months
                and self._days == other._days
            )

        return NotImplemented

    def __ne__(self, other):
        if isinstance(other, datedelta):
            return (
                self._years != other._years
                or self._months != other._months
                or self._days != other._days
            )

        return NotImplemented

    def __hash__(self):
        return hash((self._years, self._months, self._days))

    def __add__(self, other):
        if isinstance(other, datedelta):
            if (
                self._years * other._years >= 0
                and self._months * other._months >= 0
                and self._days * other._days >= 0
            ):
                return self.__class__(
                    years=self._years + other._years,
                    months=self._months + other._months,
                    days=self._days + other._days,
                )
            else:
                raise ValueError("cannot add datedeltas with opposite signs")

        return NotImplemented

    def __sub__(self, other):
        if isinstance(other, datedelta):
            if (
                self._years * other._years <= 0
                and self._months * other._months <= 0
                and self._days * other._days <= 0
            ):
                return self.__class__(
                    years=self._years - other._years,
                    months=self._months - other._months,
                    days=self._days - other._days,
                )
            else:
                raise ValueError("cannot subtract datedeltas with same signs")

        return NotImplemented

    def __mul__(self, other):
        if isinstance(other, int):
            return self.__class__(
                years=self._years * other,
                months=self._months * other,
                days=self._days * other,
            )

        return NotImplemented

    def __radd__(self, other):
        # This also matches subclasseses such as datetime.datetime. We leave it
        # up to users to figure out whether that makes sense in their use case.
        if isinstance(other, datetime.date):
            year = other.year
            month = other.month
            day = other.day

            # Add years.
            if self._years:
                year += self._years
                # Adjust the month and day if the target day doesn't exist.
                if day > _days_in_month(year, month):
                    # This branch is never taken when month == 12 because day is
                    # always in 1..31 and because December has 31 days.
                    month += 1
                    day = 1

            # Add months.
            if self._months:
                month += self._months
                # Adjust the year if the target month isn't in 1..12.
                dyear, month0 = divmod(month - 1, 12)
                year += dyear
                month = month0 + 1
                # Adjust the month and day if the target day doesn't exist.
                if day > _days_in_month(year, month):
                    # This branch is never taken when month == 12 because day is
                    # always in 1..31 and because December has 31 days.
                    month += 1
                    day = 1

            result = other.replace(year, month, day)

            # Add days.
            if self._days:
                result += datetime.timedelta(days=self._days)

            return result

        return NotImplemented

    def __rsub__(self, other):
        # This also matches subclasseses such as datetime.datetime. We leave it
        # up to users to figure out whether that makes sense in their use case.
        if isinstance(other, datetime.date):
            year = other.year
            month = other.month
            day = other.day

            # Subtract years.
            if self._years:
                year -= self._years
                # Adjust the month and day if the target day doesn't exist.
                if day > _days_in_month(year, month):
                    # This branch is never taken when month == 12 because day is
                    # always in 1..31 and because December has 31 days.
                    month += 1
                    day = 1

            # Subtract months.
            if self._months:
                month -= self._months
                # Adjust the year if the target month isn't in 1..12.
                dyear, month0 = divmod(month - 1, 12)
                year += dyear
                month = month0 + 1
                # Adjust the month and day if the target day doesn't exist.
                if day > _days_in_month(year, month):
                    # This branch is never taken when month == 12 because day is
                    # always in 1..31 and because December has 31 days.
                    month += 1
                    day = 1

            result = other.replace(year, month, day)

            # Subtract days.
            if self._days:
                result -= datetime.timedelta(days=self._days)

            return result

        return NotImplemented

    __rmul__ = __mul__

    def __neg__(self):
        return self.__class__(
            years=-self._years,
            months=-self._months,
            days=-self._days,
        )

    def __pos__(self):
        return self

    # Optimize pickling.

    def __getstate__(self):
        return self._years, self._months, self._days

    def __setstate__(self, state):
        self._years, self._months, self._days = state

# Public constants for convenience.

YEAR = datedelta(years=1)

MONTH = datedelta(months=1)

WEEK = datedelta(days=7)

DAY = datedelta(days=1)

# There's a private implementation of the same logic in the datetime module.

_DAYS_IN_MONTH = [None, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

def _days_in_month(year, month):
    assert 1 <= month <= 12
    # Inline definition of calendar.isleap(year) for clarity and performance.
    if month == 2 and (year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)):
        return 29
    return _DAYS_IN_MONTH[month]

def _s(value):
    return "" if abs(value) == 1 else "s"


text:
package net.dirtyfilthy.bouncycastle.asn1.cmp;

import net.dirtyfilthy.bouncycastle.asn1.ASN1Encodable;
import net.dirtyfilthy.bouncycastle.asn1.ASN1Sequence;
import net.dirtyfilthy.bouncycastle.asn1.DERInteger;
import net.dirtyfilthy.bouncycastle.asn1.DERObject;

public class PollReqContent
    extends ASN1Encodable
{
    private ASN1Sequence content;

    private PollReqContent(ASN1Sequence seq)
    {
        content = seq;
    }

    public static PollReqContent getInstance(Object o)
    {
        if (o instanceof PollReqContent)
        {
            return (PollReqContent)o;
        }

        if (o instanceof ASN1Sequence)
        {
            return new PollReqContent((ASN1Sequence)o);
        }

        throw new IllegalArgumentException("Invalid object: " + o.getClass().getName());
    }

    public DERInteger[][] getCertReqIds()
    {
        DERInteger[][] result = new DERInteger[content.size()][];

        for (int i = 0; i != result.length; i++)
        {
            result[i] = seqenceToDERIntegerArray((ASN1Sequence)content.getObjectAt(i));
        }

        return result;
    }

    private DERInteger[] seqenceToDERIntegerArray(ASN1Sequence seq)
    {
         DERInteger[] result = new DERInteger[seq.size()];

        for (int i = 0; i != result.length; i++)
        {
            result[i] = DERInteger.getInstance(seq.getObjectAt(i));
        }

        return result;
    }

    /**
     * <pre>
     * PollReqContent ::= SEQUENCE OF SEQUENCE {
     *                        certReqId              INTEGER
     * }
     * </pre>
     * @return a basic ASN.1 object representation.
     */
    public DERObject toASN1Object()
    {
        return content;
    }
}


text:
<?php
/* @var $this PERSONNEL_UNEMPLOYMENT_DETAILController */
/* @var $model PERSONNEL_UNEMPLOYMENT_DETAIL */

$this->breadcrumbs=array(
	'Personnel  Unemployment  Details'=>array('index'),
	$model->PUD_UNIT_CODE=>array('view','id'=>$model->PUD_UNIT_CODE),
	'Update',
);

$this->menu=array(
	array('label'=>'List PERSONNEL_UNEMPLOYMENT_DETAIL', 'url'=>array('index')),
	array('label'=>'Create PERSONNEL_UNEMPLOYMENT_DETAIL', 'url'=>array('create')),
	array('label'=>'View PERSONNEL_UNEMPLOYMENT_DETAIL', 'url'=>array('view', 'id'=>$model->PUD_UNIT_CODE)),
	array('label'=>'Manage PERSONNEL_UNEMPLOYMENT_DETAIL', 'url'=>array('admin')),
);
?>

Update PERSONNEL_UNEMPLOYMENT_DETAIL <?php echo $model->PUD_UNIT_CODE; ?>

<?php echo $this->renderPartial('_form', array('model'=>$model)); ?>


text:
<?php
namespace Grav\Common;

use DateTime;
use DateTimeZone;
use Grav\Common\Helpers\Truncator;
use RocketTheme\Toolbox\Event\Event;

/**
 * Misc utilities.
 *
 * @package Grav\Common
 */
abstract class Utils
{
    use GravTrait;

    /**
     * @param  string $haystack
     * @param  string $needle
     *
     * @return bool
     */
    public static function startsWith($haystack, $needle)
    {
        if (is_array($needle)) {
            $status = false;
            foreach ($needle as $each_needle) {
                $status = $status || ($each_needle === '' || strpos($haystack, $each_needle) === 0);
                if ($status) {
                    return $status;
                }
            }

            return $status;
        }

        return $needle === '' || strpos($haystack, $needle) === 0;
    }

    /**
     * @param  string $haystack
     * @param  string $needle
     *
     * @return bool
     */
    public static function endsWith($haystack, $needle)
    {
        if (is_array($needle)) {
            $status = false;
            foreach ($needle as $each_needle) {
                $status = $status || ($each_needle === '' || substr($haystack, -strlen($each_needle)) === $each_needle);
                if ($status) {
                    return $status;
                }
            }

            return $status;
        }

        return $needle === '' || substr($haystack, -strlen($needle)) === $needle;
    }

    /**
     * @param  string $haystack
     * @param  string $needle
     *
     * @return bool
     */
    public static function contains($haystack, $needle)
    {
        return $needle === '' || strpos($haystack, $needle) !== false;
    }

    /**
     * Merge two objects into one.
     *
     * @param  object $obj1
     * @param  object $obj2
     *
     * @return object
     */
    public static function mergeObjects($obj1, $obj2)
    {
        return (object)array_merge((array)$obj1, (array)$obj2);
    }

    public static function dateFormats()
    {
        $now = new DateTime();

        $date_formats = [
            'd-m-Y H:i' => 'd-m-Y H:i (e.g. '.$now->format('d-m-Y H:i').')',
            'Y-m-d H:i' => 'Y-m-d H:i (e.g. '.$now->format('Y-m-d H:i').')',
            'm/d/Y h:i a' => 'm/d/Y h:i (e.g. '.$now->format('m/d/Y h:i a').')',
            'H:i d-m-Y' => 'H:i d-m-Y (e.g. '.$now->format('H:i d-m-Y').')',
            'h:i a m/d/Y' => 'h:i a m/d/Y (e.g. '.$now->format('h:i a m/d/Y').')',
            ];
        $default_format = self::getGrav()['config']->get('system.pages.dateformat.default');
        if ($default_format) {
            $date_formats = array_merge([$default_format => $default_format.' (e.g. '.$now->format($default_format).')'], $date_formats);
        }
        return $date_formats;
    }

    /**
     * Truncate text by number of characters but can cut off words.
     *
     * @param  string $string
     * @param  int $limit Max number of characters.
     * @param  bool $up_to_break truncate up to breakpoint after char count
     * @param  string $break Break point.
     * @param  string $pad Appended padding to the end of the string.
     * @return string
     */
    public static function truncate($string, $limit = 150, $up_to_break = false, $break = " ", $pad = "…")
    {
        // return with no change if string is shorter than $limit
        if (mb_strlen($string) <= $limit) {
            return $string;
        }

        // is $break present between $limit and the end of the string?
        if ($up_to_break && false !== ($breakpoint = mb_strpos($string, $break, $limit))) {
            if ($breakpoint < mb_strlen($string) - 1) {
                $string = mb_substr($string, 0, $breakpoint) . $break;
            }
        } else {
            $string = mb_substr($string, 0, $limit) . $pad;
        }

        return $string;
    }

    /**
     * Truncate text by number of characters in a "word-safe" manor.
     *
     * @param $string
     * @param int $limit
     * @return string
     */
    public static function safeTruncate($string, $limit = 150)
    {
        return static::truncate($string, $limit, true);
    }

    /**
     * Truncate HTML by number of characters. not "word-safe"!
     *
     * @param  string $text
     * @param  int    $length
     *
     * @return string
     */
    public static function truncateHtml($text, $length = 100)
    {
        return Truncator::truncate($text, $length, array('length_in_chars' => true));
    }

    /**
     * Truncate HTML by number of characters in a "word-safe" manor.
     *
     * @param  string $text
     * @param  int    $length
     *
     * @return string
     */
    public static function safeTruncateHtml($text, $length = 100)
    {
        return Truncator::truncate($text, $length, array('length_in_chars' => true, 'word_safe' => true));
    }

    /**
     * Generate a random string of a given length
     *
     * @param int $length
     *
     * @return string
     */
    public static function generateRandomString($length = 5)
    {
        return substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
    }

    /**
     * Provides the ability to download a file to the browser
     *
     * @param      $file            the full path to the file to be downloaded
     * @param bool $force_download  as opposed to letting browser choose if to download or render
     */
    public static function download($file, $force_download = true)
    {
        if (file_exists($file)) {
            // fire download event
            self::getGrav()->fireEvent('onBeforeDownload', new Event(['file' => $file]));

            $file_parts = pathinfo($file);
            $filesize = filesize($file);

            // check if this function is available, if so use it to stop any timeouts
            if (function_exists('set_time_limit')) {
                set_time_limit(0);
            }

            ignore_user_abort(false);

            if ($force_download) {
                header('Content-Description: File Transfer');
                header('Content-Type: application/octet-stream');
                header('Content-Disposition: attachment; filename=' . $file_parts['basename']);
                header('Content-Transfer-Encoding: binary');
                header('Expires: 0');
                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                header('Pragma: public');
            } else {
                header("Content-Type: " . Utils::getMimeType($file_parts['extension']));
            }
            header('Content-Length: ' . $filesize);

            // 8kb chunks for now
            $chunk = 8 * 1024;

            $fh = fopen($file, "rb");

            if ($fh === false) {
                return;
            }

            // Repeat reading until EOF
            while (!feof($fh)) {
                echo fread($fh, $chunk);

                ob_flush();  // flush output
                flush();
            }

            exit;
        }
    }

    /**
     * Return the mimetype based on filename
     *
     * @param $extension Extension of file (eg .txt)
     *
     * @return string
     */
    public static function getMimeType($extension)
    {
        $extension = strtolower($extension);

        switch ($extension) {
            case "js":
                return "application/x-javascript";

            case "json":
                return "application/json";

            case "jpg":
            case "jpeg":
            case "jpe":
                return "image/jpg";

            case "png":
            case "gif":
            case "bmp":
            case "tiff":
                return "image/" . $extension;

            case "css":
                return "text/css";

            case "xml":
                return "application/xml";

            case "doc":
            case "docx":
                return "application/msword";

            case "xls":
            case "xlt":
            case "xlm":
            case "xld":
            case "xla":
            case "xlc":
            case "xlw":
            case "xll":
                return "application/vnd.ms-excel";

            case "ppt":
            case "pps":
                return "application/vnd.ms-powerpoint";

            case "rtf":
                return "application/rtf";

            case "pdf":
                return "application/pdf";

            case "html":
            case "htm":
            case "php":
                return "text/html";

            case "txt":
                return "text/plain";

            case "mpeg":
            case "mpg":
            case "mpe":
                return "video/mpeg";

            case "mp3":
                return "audio/mpeg3";

            case "wav":
                return "audio/wav";

            case "aiff":
            case "aif":
                return "audio/aiff";

            case "avi":
                return "video/msvideo";

            case "wmv":
                return "video/x-ms-wmv";

            case "mov":
                return "video/quicktime";

            case "zip":
                return "application/zip";

            case "tar":
                return "application/x-tar";

            case "swf":
                return "application/x-shockwave-flash";

            default:
                return "application/octet-stream";
        }
    }

    /**
     * Normalize path by processing relative `.` and `..` syntax and merging path
     *
     * @param $path
     *
     * @return string
     */
    public static function normalizePath($path)
    {
        $root = ($path[0] === '/') ? '/' : '';

        $segments = explode('/', trim($path, '/'));
        $ret = array();
        foreach ($segments as $segment) {
            if (($segment == '.') || empty($segment)) {
                continue;
            }
            if ($segment == '..') {
                array_pop($ret);
            } else {
                array_push($ret, $segment);
            }
        }

        return $root . implode('/', $ret);
    }

    public static function timezones()
    {
        $timezones = \DateTimeZone::listIdentifiers(\DateTimeZone::ALL);
        $offsets = [];
        $testDate = new \DateTime;

        foreach ($timezones as $zone) {
            $tz = new \DateTimeZone($zone);
            $offsets[$zone] = $tz->getOffset($testDate);
        }

        asort($offsets);

        $timezone_list = array();
        foreach ($offsets as $timezone => $offset) {
            $offset_prefix = $offset < 0 ? '-' : '+';
            $offset_formatted = gmdate('H:i', abs($offset));

            $pretty_offset = "UTC${offset_prefix}${offset_formatted}";

            $timezone_list[$timezone] = "(${pretty_offset}) $timezone";
        }

        return $timezone_list;

    }

    public static function arrayFilterRecursive(Array $source, $fn)
    {
        $result = array();
        foreach ($source as $key => $value)
        {
            if (is_array($value))
            {
                $result[$key] = static::arrayFilterRecursive($value, $fn);
                continue;
            }
            if ($fn($key, $value))
            {
                $result[$key] = $value; // KEEP
                continue;
            }
        }
        return $result;
    }

    public static function pathPrefixedByLangCode($string)
    {
        $languages_enabled = self::getGrav()['config']->get('system.languages.supported', []);

        if ($string[0] == '/' && $string[3] == '/' && in_array(substr($string, 1, 2), $languages_enabled)) {
            return true;
        }

        return false;
    }

    public static function date2timestamp($date)
    {
        $config = self::getGrav()['config'];
        $default_dateformat = $config->get('system.pages.dateformat.default');

        // try to use DateTime and default format
        if ($default_dateformat) {
            $datetime = DateTime::createFromFormat($default_dateformat, $date);
        } else {
            $datetime = new DateTime($date);
        }

        // fallback to strtotime if DateTime approach failed
        if ($datetime !== false) {
            return $datetime->getTimestamp();
        } else {
            return strtotime($date);
        }
    }

}


text:
package org.apache.asterix.test.ioopcallbacks;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.dataflow.common.data.accessors.PermutingTupleReference;
import org.apache.hyracks.storage.am.common.api.IExtendedModificationOperationCallback;
import org.apache.hyracks.storage.am.common.impls.NoOpOperationCallback;
import org.apache.hyracks.storage.am.common.ophelpers.IndexOperation;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMComponent;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMDiskComponent;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMIOOperation;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMIndex;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMIndexOperationContext;
import org.apache.hyracks.storage.common.ISearchOperationCallback;
import org.apache.hyracks.storage.common.ISearchPredicate;
import org.apache.hyracks.storage.common.MultiComparator;

public class TestLSMIndexOperationContext implements ILSMIndexOperationContext {

    private final ILSMIndex index;
    private final List<ILSMComponent> componentHolder = new ArrayList<>();
    private final List<ILSMDiskComponent> componentsToBeMerged = new ArrayList<>();
    private final List<ILSMDiskComponent> componentsToBeReplicated = new ArrayList<>();
    private boolean isAccessingComponents;
    private IndexOperation op;
    private ILSMIOOperation ioOperation;
    private Map<String, Object> map;
    private boolean filterSkip = false;
    private boolean isRecovery = false;

    public TestLSMIndexOperationContext(ILSMIndex index) {
        this.index = index;
    }

    @Override
    public void setOperation(IndexOperation newOp) throws HyracksDataException {
        this.op = newOp;
    }

    @Override
    public IndexOperation getOperation() {
        return op;
    }

    @Override
    public void reset() {
        op = null;
        componentHolder.clear();
        componentsToBeMerged.clear();
        componentsToBeReplicated.clear();
        isAccessingComponents = false;
    }

    @Override
    public void destroy() throws HyracksDataException {
    }

    @Override
    public List<ILSMComponent> getComponentHolder() {
        return componentHolder;
    }

    @Override
    public List<ILSMDiskComponent> getComponentsToBeMerged() {
        return componentsToBeMerged;
    }

    @Override
    public ISearchOperationCallback getSearchOperationCallback() {
        return NoOpOperationCallback.INSTANCE;
    }

    @Override
    public IExtendedModificationOperationCallback getModificationCallback() {
        return NoOpOperationCallback.INSTANCE;
    }

    @Override
    public void setCurrentMutableComponentId(int currentMutableComponentId) {
    }

    @Override
    public void setSearchPredicate(ISearchPredicate searchPredicate) {
        throw new UnsupportedOperationException();
    }

    @Override
    public ISearchPredicate getSearchPredicate() {
        throw new UnsupportedOperationException();
    }

    @Override
    public List<ILSMDiskComponent> getComponentsToBeReplicated() {
        return componentsToBeReplicated;
    }

    @Override
    public boolean isAccessingComponents() {
        return isAccessingComponents;
    }

    @Override
    public void setAccessingComponents(boolean accessingComponents) {
        this.isAccessingComponents = accessingComponents;
    }

    @Override
    public PermutingTupleReference getIndexTuple() {
        throw new UnsupportedOperationException();
    }

    @Override
    public PermutingTupleReference getFilterTuple() {
        return null;
    }

    @Override
    public MultiComparator getFilterCmp() {
        return null;
    }

    @Override
    public ILSMIndex getIndex() {
        return index;
    }

    @Override
    public void logPerformanceCounters(int tupleCount) {
    }

    @Override
    public void incrementEnterExitTime(long increment) {
    }

    @Override
    public boolean isTracingEnabled() {
        return false;
    }

    @Override
    public boolean isFilterSkipped() {
        return filterSkip;
    }

    @Override
    public void setFilterSkip(boolean skip) {
        this.filterSkip = skip;
    }

    @Override
    public boolean isRecovery() {
        return isRecovery;
    }

    @Override
    public void setRecovery(boolean recovery) {
        this.isRecovery = recovery;

    }

    @Override
    public ILSMIOOperation getIoOperation() {
        return ioOperation;
    }

    @Override
    public void setIoOperation(ILSMIOOperation ioOperation) {
        this.ioOperation = ioOperation;
    }

    @Override
    public void setParameters(Map<String, Object> map) {
        this.map = map;
    }

    @Override
    public Map<String, Object> getParameters() {
        return map;
    }

}


text:
package gudusoft.gsqlparser.sql2xml.model;

public class sql_prefix
{

}


text:
module HBF.PrgmIO
( PrgmIO(..)
, Val
) where

import HBF.Types (Val)

class (Functor s, Monad s) => PrgmIO s where
    prgmRead :: s Val
    prgmWrite :: Val -> s ()


text:
const config = require('../config.json')
const storage = require('../util/storage.js')
const currentGuilds = storage.currentGuilds
const TEST_OPTIONS = {split: {prepend: '```md\n', append: '```'}}
const log = require('../util/logger.js')
const debugFeeds = require('../util/debugFeeds.js').list
const translate = require('../rss/translator/translate.js')
const deletedFeeds = storage.deletedFeeds

class ArticleMessage {
  constructor (article, isTestMessage, skipFilters) {
    this.article = article
    this.isTestMessage = isTestMessage
    this.skipFilters = skipFilters || isTestMessage
    this.channelId = article.discordChannelId
    this.channel = storage.bot.channels.get(article.discordChannelId)
    if (!this.channel) return
    this.guildRss = currentGuilds.get(this.channel.guild.id)
    this.webhook = undefined
    this.sendFailed = 1
    this.rssName = article.rssName
    this.valid = true
    if (!this.guildRss) {
      this.valid = false
      return log.general.error(`${this.rssName} Unable to initialize an ArticleMessage due to missing guild profile`, this.channel.guild)
    }
    this.source = this.guildRss ? this.guildRss.sources[this.rssName] : undefined
    if (!this.source) {
      this.valid = false
      return log.general.error(`${this.rssName} Unable to initialize an ArticleMessage due to missing source`, this.channel.guild, this.channel)
    }
    this.toggleRoleMentions = this.source.toggleRoleMentions === true
    this.split = this.source.splitMessage // The split options if the message exceeds the character limit. If undefined, do not split, otherwise it is an object with keys char, prepend, append
    this._translate()
  }

  _resolveChannel (callback) {
    if (((config.advanced._restrictWebhooks === true && storage.vipServers[this.channel.guild.id] && storage.vipServers[this.channel.guild.id].benefactor.allowWebhooks) || !config.advanced._restrictWebhooks) && this.source && typeof this.source.webhook === 'object') {
      if (!this.channel.guild.me.permissionsIn(this.channel).has('MANAGE_WEBHOOKS')) return callback()
      this.channel.fetchWebhooks().then(hooks => {
        const hook = hooks.get(this.source.webhook.id)
        if (!hook) return callback()
        const guildId = this.channel.guild.id
        const guildName = this.channel.guild.name
        this.webhook = hook
        this.webhook.guild = { id: guildId, name: guildName }
        let name = this.source.webhook.name ? this.parsedArticle.convertKeywords(this.source.webhook.name) : undefined
        if (name && name.length > 32) name = name.slice(0, 29) + '...'
        if (name && name.length < 2) name = undefined
        this.webhook.name = name
        this.webhook.avatar = this.source.webhook.avatar ? this.parsedArticle.convertImgs(this.source.webhook.avatar) : undefined
        callback()
      }).catch(err => {
        log.general.warning(`Cannot fetch webhooks for ArticleMessage webhook initialization to send message`, this.channel, err, true)
        callback()
      })
    } else callback()
  }

  _translate (ignoreLimits, callback) {
    const results = translate(this.guildRss, this.rssName, this.article, this.isTestMessage, ignoreLimits)
    this.parsedArticle = results.parsedArticle
    this.subscriptionIds = this.parsedArticle.subscriptionIds
    this.passedFilters = results.passedFilters
    this.testDetails = results.testDetails
    this.embed = results.embed
    this.text = results.text
    if (callback) callback()
  }

  send (callback) {
    if (!this.source) return callback(new Error('Missing feed source'))
    if (!this.channel) return callback(new Error('Missing channel'))
    this._resolveChannel(() => {
      if (!this.valid) return callback(new Error(`Missing ArticleMessage initialization data`))
      if (!this.skipFilters && !this.passedFilters) {
        if (config.log.unfiltered === true) log.general.info(`'${this.article.link ? this.article.link : this.article.title}' did not pass filters and was not sent`, this.channel)
        return callback()
      }
      if (deletedFeeds.includes(this.rssName)) return callback(new Error(`${this.rssName} for channel ${this.channel.id} was deleted during cycle`))

      // Set up the send options
      const textContent = this.isTestMessage ? this.testDetails : this.text.length > 1950 && !this.split ? `Error: Feed Article could not be sent for ${this.article.link} due to a single message's character count >1950.` : this.text.length === 0 && !this.embed ? `Unable to send empty message for feed article <${this.article.link}>.` : this.text
      const options = this.isTestMessage ? TEST_OPTIONS : {}
      if (this.webhook) {
        options.username = this.webhook.name
        options.avatarURL = this.webhook.avatar
      }
      if (!this.isTestMessage && this.embed) {
        if (this.webhook) options.embeds = [this.embed]
        else options.embed = this.embed
      }
      if (!this.isTestMessage) options.split = this.split

      // Send the message, and repeat attempt if failed
      const medium = this.webhook ? this.webhook : this.channel
      medium.send(textContent, options)
      .then(m => {
        if (this.isTestMessage) {
          this.isTestMessage = false
          this.send(callback)
        } else callback()
      })
      .catch(err => {
        if (this.split && err.message.includes('2000 or fewer in length')) {
          delete this.split
          this._translate(false)
          return this.send(callback)
        }
        if (this.split && err.message.includes('no split characters')) {
          this._translate(false) // Retranslate with the character limits for individual placeholders again
          return this.send(callback)
        }
        if (err.code === 50013 || this.sendFailed++ === 4) { // 50013 = Missing Permissions
          if (debugFeeds.includes(this.rssName)) log.debug.error(`${this.rssName}: Message has been translated but could not be sent (TITLE: ${this.article.title})`, err)
          return callback(err)
        }
        setTimeout(() => this.send.bind(this)(callback), 500)
      })
    })
  }
}

module.exports = ArticleMessage


text:
set -x  # print executed commands
set -e  # exit immediately on errors

# Make execution errors visible.
function check_result {
  [ "$?" == "0" ] || echo "HALTED: program execution failed" 1>&2
}
trap check_result EXIT

# Shortcut for binary bas path.
BINDIR=../../../../../seqan-git-build/debug/bin

# Shortcuts for binaries.
GENOME=${BINDIR}/mason_genome
METHYLATION=${BINDIR}/mason_methylation
VARIATOR=${BINDIR}/mason_variator
MATERIALIZER=${BINDIR}/mason_materializer
SIMULATOR=${BINDIR}/mason_simulator

# ============================================================
# mason_genome
# ============================================================

${GENOME} -l 1000 -o genome.test1.fasta >genome.test1.stdout 2>genome.test1.stderr
${GENOME} -s 1 -l 1000 -l 100 -o genome.test2.fasta >genome.test2.stdout 2>genome.test2.stderr

# ============================================================
# mason_methylation
# ============================================================

${METHYLATION} --seed 33 -i random.fasta -o random_meth1.fasta 1>methylation.test1.stdout 2>methylation.test2.stderr

# ============================================================
# mason_variator
# ============================================================

# Generating methylation in variator.
${VARIATOR} -n 2 -ir random.fasta -ov random_var1.vcf -of random_var1.fasta --snp-rate 0.001 --small-indel-rate 0.001 --sv-indel-rate 0.001 --sv-inversion-rate 0.001 --sv-translocation-rate 0.001 --sv-duplication-rate 0.001 --min-sv-size 50 --max-sv-size 100 --methylation-levels --meth-fasta-out random_var1_meth.fasta --out-breakpoints random_var1_bp.txt >random_var1.vcf.stdout 2>random_var1.vcf.stderr

# Loading methylation into variator.
${VARIATOR} -n 2 -ir random.fasta -ov random_var2.vcf -of random_var2.fasta --snp-rate 0.001 --small-indel-rate 0.001 --sv-indel-rate 0.001 --sv-inversion-rate 0.001 --sv-translocation-rate 0.001 --sv-duplication-rate 0.001 --min-sv-size 50 --max-sv-size 100 --methylation-levels --meth-fasta-in random_meth1.fasta --meth-fasta-out random_var2_meth.fasta --out-breakpoints random_var2_bp.txt >random_var2.vcf.stdout 2>random_var2.vcf.stderr

# Variation without methylation.
${VARIATOR} -n 2 -ir random.fasta -ov random_var3.vcf -of random_var3.fasta --snp-rate 0.001 --small-indel-rate 0.001 --sv-indel-rate 0.001 --sv-inversion-rate 0.001 --sv-translocation-rate 0.001 --sv-duplication-rate 0.001 --min-sv-size 50 --max-sv-size 100 --out-breakpoints random_var3_bp.txt >random_var3.vcf.stdout 2>random_var3.vcf.stderr

# Variation that crashed previously.
${VARIATOR} -ir adeno_virus.fa -ov random_var9.vcf -of random_var9.fasta --sv-indel-rate 0.01 --sv-inversion-rate 0.01 --sv-duplication-rate 0.01 --min-sv-size 20  --max-sv-size 300 >random_var9.vcf.stdout 2>random_var9.vcf.stderr

# Variation with variation library.
${VARIATOR} -it variants.var10.tsv -ir adeno_virus.fa -ov random_var10.vcf -of random_var10.fasta >random_var10.vcf.stdout 2>random_var10.vcf.stderr

# ============================================================
# mason_materializer
# ============================================================

# Without methylation levels.
${MATERIALIZER} -ir random.fasta -iv random_var1.vcf -o materializer.random_var1.fasta >materializer.random_var1.stdout 2>materializer.random_var1.stderr
rm -f materializer.random_var1.fasta  # we'll compare against variator output
# With methylation levels.
${MATERIALIZER} -ir random.fasta -iv random_var2.vcf -o materializer.random_var2.fasta --meth-fasta-in random_meth1.fasta --meth-fasta-out materializer.random_meth2.fasta >materializer.random_var2.stdout 2>materializer.random_var2.stderr
rm -f materializer.random_var2.fasta materializer.random_meth2.fasta  # we'll compare against variator output

# ============================================================
# mason_simulator
# ============================================================

# ------------------------------------------------------------
# Illumina Tests
# ------------------------------------------------------------

# Without VCF variants, FASTQ output, with SAM alignments, paired-end
${SIMULATOR} -n 1000 -ir random.fasta -o simulator.left1.fq -or simulator.right1.fq -oa simulator.out1.sam >simulator.out1.stdout 2>simulator.out1.stderr

# With VCF variants, FASTQ output, with SAM alignment, paired-end
${SIMULATOR} -n 1000 -ir random.fasta -iv random_var1.vcf -o simulator.left2.fq -or simulator.right2.fq -oa simulator.out2.sam >simulator.out2.stdout 2>simulator.out2.stderr

# With VCF variants, FASTA output, with SAM alignments, single-end
${SIMULATOR} -n 1000 -ir random.fasta -iv random_var1.vcf -o simulator.left7.fa -oa simulator.out7.sam  >simulator.out7.stdout 2>simulator.out7.stderr

# Without VCF variants, FASTA output, no SAM alignments, paired-end
${SIMULATOR} -n 1000 -ir random.fasta -o simulator.left3.fa -or simulator.right3.fa >simulator.out3.stdout 2>simulator.out3.stderr

# Without VCF variants, FASTA output, no SAM alignments, single-end
${SIMULATOR} -n 1000 -ir random.fasta -o simulator.left4.fa -oa simulator.out4.sam >simulator.out4.stdout 2>simulator.out4.stderr

# Without VCF variants, FASTQ output, no SAM alignment, paired-end, BS-seq.
${SIMULATOR} -n 1000 -ir random.fasta --meth-fasta-in random_meth1.fasta --methylation-levels --enable-bs-seq -o simulator.left5.fq -or simulator.right5.fq >simulator.out5.stdout 2>simulator.out5.stderr

# Without VCF variants, FASTQ output, no SAM alignment, paired-end, BS-seq.
${SIMULATOR} -n 1000 -ir random.fasta --meth-fasta-in random_meth1.fasta -iv random_var1.vcf --methylation-levels --enable-bs-seq -o simulator.left6.fq -or simulator.right6.fq >simulator.out6.stdout 2>simulator.out6.stderr

# ------------------------------------------------------------
# 454 Tests
# ------------------------------------------------------------

# Without VCF variants, FASTQ output, with SAM alignments, paired-end
${SIMULATOR} -v --seq-technology 454 -n 1000 -ir random.fasta -o simulator.left8.fq -oa simulator.out8.sam --fragment-mean-size 800 --454-read-length-mean 200 --454-read-length-stddev 20 >simulator.out8.stdout 2>simulator.out8.stderr


text:
package com.navercorp.pinpoint.plugin.json_lib;

import static com.navercorp.pinpoint.bootstrap.plugin.test.Expectations.*;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.junit.Test;
import org.junit.runner.RunWith;

import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier;
import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifierHolder;
import com.navercorp.pinpoint.test.plugin.Dependency;
import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;

/**
 *@author Sangyoon Lee
 */
@RunWith(PinpointPluginTestSuite.class)
@Dependency({"net.sf.json-lib:json-lib:jar:jdk15:(,)"})
public class JsonLibJSONObjectIT {

    private static final String SERVICE_TYPE = "JSON-LIB";
    private static final String ANNOTATION_KEY = "json-lib.json.length";

    @Test
    public void jsonToBeanTest() throws Exception {
        String json = "{'string':'JSON'}";

        JSONObject jsonObject = JSONObject.fromObject(json);
        JSONObject.toBean(jsonObject);

        PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
        verifier.printCache();

        Method fromObject = JSONObject.class.getMethod("fromObject", Object.class);
        Method toBean = JSONObject.class.getMethod("toBean", JSONObject.class);

        verifier.verifyTrace(event(SERVICE_TYPE, fromObject, annotation(ANNOTATION_KEY, json.length())));
        verifier.verifyTrace(event(SERVICE_TYPE, toBean));

        verifier.verifyTraceCount(0);
    }

    @Test
    public void mapToJsonTest() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("name", "pinpoint");
        map.put("lib", "json-lib");

        JSONObject jsonObject = JSONObject.fromObject(map);
        String json = jsonObject.toString();

        PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
        verifier.printCache();

        Method fromObject = JSONObject.class.getMethod("fromObject", Object.class);
        Method toString  = JSONObject.class.getMethod("toString");

        verifier.verifyTrace(event(SERVICE_TYPE, fromObject));
        verifier.verifyTrace(event(SERVICE_TYPE, toString, annotation(ANNOTATION_KEY, json.length())));

        verifier.verifyTraceCount(0);
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace Colours
{
    /// <summary>
    /// Represents a color palette, using the Adobe's color tables format as
    /// the backend.
    /// </summary>
    /// <remarks>
    /// See Adobe's documentation:
    /// http://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#50577411_pgfId-1070626
    /// </remarks>
    [DataContract]
    public class ActPalette : IPalette
    {
        /// <summary>
        /// Gets or sets a list of colors.
        /// </summary>
        [DataMember]
        public List<PaletteColor> Colors { get; set; }

        /// <summary>
        /// Gets or sets the index of the colour to use for transparency.
        /// </summary>
        [DataMember]
        public ushort? TransparentIndex { get; set; }

        ActPalette()
        {
            Colors = new List<PaletteColor>();
        }

        /// <summary>
        /// Creates a palette from a colour table.
        /// </summary>
        /// <param name="file">The file as a byte array.</param>
        /// <remarks>
        /// Note that the resulting color can be truncated by a directive
        /// after the first 768 bytes.
        /// </remarks>
        public ActPalette(byte[] file) : this()
        {
            if (file.Length > 772 || file.Length < 768)
                throw new PaletteException("Not a valid colour table length.");

            var metadata = file.Length == 772;
            using (var s = new MemoryStream(file))
            {
                using (var sr = new BinaryReader(s))
                {
                    for (int i = 0; i < 256; i++)
                        Colors.Add(
                            new PaletteColor(
                                new RgbColor(sr.ReadByte(), sr.ReadByte(), sr.ReadByte())
                                )
                                );

                    if (metadata)
                    {
                        var truncateTo = sr.ReadUInt16BE();

                        Colors = Colors.Take(truncateTo).ToList();

                        // Because the transparency index is also included by
                        // count of colours, use that to validate that index
                        var index = sr.ReadUInt16BE();
                        if (index <= truncateTo)
                            TransparentIndex = index;
                    }
                }
            }
        }

        /// <summary>
        /// Creates a new palette from an existing one.
        /// </summary>
        /// <param name="p">The palette to convert from.</param>
        public ActPalette(IPalette p) : this()
        {
            foreach (var pc in p.Colors)
                Colors.Add(pc);
        }

        /// <summary>
        /// Creates a colour table from a palette.
        /// </summary>
        /// <returns>The colour table, as a byte stream.</returns>
        /// <remarks>
        /// If the length of the palette is exactly 256, then no metadata will
        /// be appended.
        /// </remarks>
        public byte[] ToFile()
        {
            using (var s = new MemoryStream())
            {
                using (var sw = new BinaryWriter(s))
                {
                    var l = Colors.Take(256).Select(x => x.Color).ToArray();

                    const byte defaultChannel = 0xFF;
                    for (int i = 0; i < 256; i++)
                    {
                        if (l.Length <= i)
                        {
                            // when in doubt, white?
                            sw.Write(defaultChannel);
                            sw.Write(defaultChannel);
                            sw.Write(defaultChannel);
                        }
                        else
                        {
                            sw.Write(l[i].ToRgb().R8);
                            sw.Write(l[i].ToRgb().G8);
                            sw.Write(l[i].ToRgb().B8);
                        }
                    }

                    // if there's less than 256, truncate
                    // or if there's a transparency index
                    if (TransparentIndex != null || l.Length != 256)
                    {
                        sw.WriteUInt16BE(Convert.ToUInt16(l.Length));

                        // fallback to a clearly bogus value
                        sw.WriteUInt16BE(TransparentIndex ?? ushort.MaxValue);
                    }

                    s.Position = 0;
                    using (var sr = new BinaryReader(s))
                    {
                        return sr.ReadBytes((int)s.Length);
                    }
                }
            }
        }

        /// <summary>
        /// Creates a new palette with properties identical to the old one.
        /// </summary>
        /// <remarks>
        /// This is intended for changing the properties of a palette, while
        /// preserving the old version's properties, due to changing the
        /// reference.
        /// </remarks>
        /// <returns>The new palette.</returns>
        public IPalette Clone()
        {
            var p = new ActPalette();
            p.Colors = new List<PaletteColor>();
            foreach (var c in Colors)
                p.Colors.Add(c);
            return p;
        }
    }
}


text:
from __future__ import absolute_import

import enum

from zope.interface import Interface, Attribute

__all__ = ["IRegistry", "IRestorator",
           "ISnapshotable", "ISerializable", "IVersionAdapter",
           "IExternal", "IInstance", "IReference", "IDereference",
           "IExternalizer", "Capabilities", "IFreezer", "IConverter"]

class Capabilities(enum.Enum):
    (int_values,
     enum_values,
     long_values,
     float_values,
     bytes_values,
     unicode_values,
     bool_values,
     none_values,
     tuple_values,
     list_values,
     set_values,
     dict_values,
     instance_values,
     external_values,
     type_values,
     function_values,
     method_values,
     builtin_values,
     int_keys,
     enum_keys,
     long_keys,
     float_keys,
     str_keys,
     unicode_keys,
     bool_keys,
     none_keys,
     type_keys,
     tuple_keys,
     circular_references,
     new_style_types,
     meta_types) = range(31)

class IRegistry(Interface):
    '''Register factories to unserialize object.'''

    def clone():
        """returns a new registry with the same restorators.
        registering new restorator to the new registry will
        not add it to the original registry."""

    def register(restorator):
        '''Register L{IRestorer}'''

    def lookup(type_name):
        '''Gives a L{IRestorer} for specified type name
        or None if not found.'''

class IExternalizer(Interface):
    '''Used with converters to substitute instances by references
    externally managed.'''

    def identify(self, instance):
        '''Returns the external identifier for the instance or None.'''

    def lookup(self, identifier):
        '''Returns the instance with specified identifier or None.'''

class IRestorator(Interface):
    '''Knows how to restore a snapshot for a type name.
    Should be registered to a L{IUnserializer}.'''

    type_name = Attribute('')

    def prepare():
        '''For mutable types, creates and prepares an instance for
        being recovered. For immutable types returns None, and restore()
        should be used instead.
        It returns an empty instance implementing L{ISerializable}.
        The returned instance's method recover() should be called
        with a snapshot to finish the restoration.
        This methods will create an instance without calling __init__().'''

    def restore(snapshot):
        '''For mutable types, equivalent of calling prepare() and then
        the instance recover() method with the specified snapshot.'''

class ISnapshotable(Interface):
    '''Only know how to extract a snapshot of its state,
    there is no guarantee of recoverability.'''

    referenceable = Attribute("If reference should be tracked. WARNING: "
                              "instance not referenceable should not contain "
                              "any circular references.")

    def snapshot():
        '''Called to retrieve the current state of an object.
        It should return only structures of basic python types
        or instances implementing L{ISnapshot}.'''

class ISerializable(ISnapshotable):
    '''Knows how to serialize itself and know it's type name.
    The type name will be used to know which L{IUnserializer}
    to use in order to restore a snapshot.
    When restored, __init__() will not be called on the instance,
    instead recover() will be called with a snapshot.'''

    type_name = Attribute('')

    def recover(snapshot):
        '''Called for the instance to recover its state from a snapshot.
        The mutable values of the snapshot should not be used because
        they may not be initialized yet because of circular references.
        To perform initialization relying on snapshot items being restored
        restored() should be used.
        NOTE: when this method is called __init__() has not been called
        and will never be called, restoration of parent class should be done
        there or in the later call to restored().'''

    def restored():
        '''Called when all unserialized items have been restored.
        Only MUTABLE types are called.
        WARNING: It doesn't mean all restored() functions have been called.'''

class IVersionAdapter(Interface):

    def adapt_version(snapshot, source_ver, target_ver):
        """Adapt a snapshot from a version to another."""

    def set_migrated():
        """Called by unserializer to inform the object that it's snanshot
        has been migrated"""

    def store_version(snapshot, version, version_atom):
        """Store the final version into the snapshot."""

    has_migrated = Attribute('C{bool} flag saying that the object has been'
                             ' migrated')

class IExternal(Interface):
    '''Used by some converter to represent an external reference.'''

    identifier = Attribute("External reference identifier")

class IInstance(Interface):
    '''Used by some converter to represent ISerializable instances.'''

    type_name = Attribute('Name of the instance type')
    snapshot = Attribute('Snapshot of the instance')

class IReference(Interface):
    '''Used by some converter to represent a reference on a value.'''

    refid = Attribute('Reference identifier')
    value = Attribute('Reference value')

class IDereference(Interface):
    '''Used by some converter to represent a dereference
    of a referenced value.'''

    refid = Attribute('Reference identifier')

class IFreezer(Interface):
    '''Knows how to convert something from a format to another.
    Only knows about basic python types and instances implementing
    L{ISnapshot}. The result of calling freeze() is most probably
    not unserializable. Used for one-way conversion.
    The only guarantee is that multiple call to freeze() will
    have always the same result.'''

    freezer_capabilities = Attribute("Set of L{Capabilities} value.")

    def freeze(data):
        '''One-way converts a format to another format.
        Only work with python basic types and instances implementing
        L{ISnapshotable}. Even if one-way, the result is consistent
        over multiple calls, it gives always the same output for
        the same input.'''

class IConverter(Interface):
    '''Knows how to convert something from a format to another.
    Only knows about basic python types and instances implementing
    L{ISerializable} for which a L{IRestorator} must be registered.
    Converters are normally bidirectional with a serializer and
    an unserializer.'''

    converter_capabilities = Attribute("Set of L{Capabilities} value.")

    def convert(data):
        '''Converts a format to another format, usually the output
        can be converted back to the original value.
        Only work with python basic types and instances implementing
        L{ISerializable}. The result is consistent over multiple calls,
        it gives always the same output for the same input.'''


text:
<!DOCTYPE html>

		<title>three.js webgl - camera cinematic</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
		<link type="text/css" rel="stylesheet" href="main.css">

			three.js webgl - interactive cubes


text:
import sys

if 2 != sys.version_info[0]:
    unicode = str

def add(*types):
    """Select a (list of) to be added objects(s)

    >>> add("registrationid1", "registrationid2")
    {'add': ['registrationid1', 'registrationid2']}
    >>> add("tag1", "tag2")
    {'add': ['tag1', 'tag2']}
    >>> add("alias1", "alias2")
    {'add': ['alias1', 'alias2']}
    """
    vadd = [v for v in types]
    return {"add": vadd}

def remove(*types):
    """Select a (list of) to be removed objects(s)

    >>> remove("registrationid1", "registrationid2")
    {'remove': ['registrationid1', 'registrationid2']}
    >>> remove("tag1", "tag2")
    {'remove': ['tag1', 'tag2']}
    >>> remove("alias1", "alias2")
    {'remove': ['alias1', 'alias2']}
    """
    vremove = [v for v in types]
    return {"remove": vremove}

def device_tag(*types):
    """Get a tag object

    >>> device_tag("")
    {'tags': ''}
    >>> device_tag("tag1")
    {'tags': 'tag1'}
    >>> device_tag(add("tag1", "tag2"), remove("tag3", "tag4"))
    {'tags': {'add': ['tag1', 'tag2'], 'remove': ['tag3', 'tag4']}}
    """
    tag = {}
    if 1 == len(types) and isinstance(types[0], (str, unicode)):
        tag["tags"] = types[0]
        return tag
    tag["tags"] = {}
    for t in types:
        for key in t:
            if key not in ('add', 'remove'):
                raise ValueError("Invalid tag '%s'" % t)
            tag["tags"][key] = t[key]
    return tag

def device_mobile(device_mobile):
    mobile={}
    mobile["mobile"]=device_mobile
    return mobile

def device_alias(*types):
    """Get an alias object

    >>> device_alias("")
    {'alias': ''}
    >>> device_alias("alias1")
    {'alias': 'alias1'}
    >>> device_alias(add("alias1", "alias2"), remove("alias3", "alias4"))
    {'alias': {'add': ['alias1', 'alias2'], 'remove': ['alias3', 'alias4']}}
    """
    alias = {}
    if 1 == len(types) and isinstance(types[0], (str, unicode)):
        alias["alias"] = types[0]
        return alias
    alias["alias"] = {}
    for t in types:
        for key in t:
            if key not in ('add', 'remove'):
                raise ValueError("Invalid alias '%s'" % t)
            alias["alias"][key] = t[key]
    return alias

def device_regid(*types):
    """Get a registration_id object

    >>> device_regid("")
    {'registration_ids': ''}
    >>> device_regid("registration_id1")
    {'registration_ids': 'registration_id1'}
    >>> device_regid(add("registration_id1", "registration_id2"), remove("registration_id3", "registration_id4"))
    {'registration_ids': {'add': ['registration_id1', 'registration_id2'], 'remove': ['registration_id3', 'registration_id4']}}
    """
    registration_id = {}
    if 1 == len(types) and isinstance(types[0], (str, unicode)):
        registration_id["registration_ids"] = types[0]
        return registration_id
    registration_id["registration_ids"] = {}
    for t in types:
        for key in t:
            if key not in ('add', 'remove'):
                raise ValueError("Invalid registration_id '%s'" % t)
            registration_id["registration_ids"][key] = t[key]
    return registration_id

if "__main__" == __name__:
    print (add("1", "2"))
    print (device_tag(add("a", "b"), remove('1', '2')))


text:
package com.abhijitvalluri.android.fitnotifications;

import org.junit.Test;

import static org.junit.Assert.*;

/**
 * To work on unit tests, switch the Test Artifact in the Build Variants view.
 */
public class ExampleUnitTest {
    @Test
    public void addition_isCorrect() throws Exception {
        assertEquals(4, 2 + 2);
    }
}


text:
package org.zstack.header.identity;

import org.zstack.header.configuration.PythonClassInventory;
import org.zstack.header.identity.AccountConstant.StatementEffect;
import org.zstack.header.query.ExpandedQueries;
import org.zstack.header.query.ExpandedQuery;
import org.zstack.header.query.ExpandedQueryAlias;
import org.zstack.header.query.ExpandedQueryAliases;
import org.zstack.header.rest.SDK;
import org.zstack.header.search.Inventory;
import org.zstack.utils.gson.JSONObjectUtil;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Inventory(mappingVOClass = PolicyVO.class)
@PythonClassInventory
@ExpandedQueries({
        @ExpandedQuery(expandedField = "account", inventoryClass = AccountInventory.class,
                foreignKey = "accountUuid", expandedInventoryKey = "uuid"),
        @ExpandedQuery(expandedField = "groupRef", inventoryClass = UserGroupPolicyRefInventory.class,
                foreignKey = "uuid", expandedInventoryKey = "policyUuid", hidden = true),
        @ExpandedQuery(expandedField = "userRef", inventoryClass = UserPolicyRefInventory.class,
                foreignKey = "uuid", expandedInventoryKey = "policyUuid", hidden = true)
})
@ExpandedQueryAliases({
        @ExpandedQueryAlias(alias = "group", expandedField = "groupRef.group"),
        @ExpandedQueryAlias(alias = "user", expandedField = "userRef.user")
})
public class PolicyInventory {
    @SDK(sdkClassName = "PolicyStatement")
    public static class Statement {
        private String name;
        private StatementEffect effect;
        private List<String> principals;
        private List<String> actions;
        private List<String> resources;

        public String getName() {
            return name;
        }

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

        public StatementEffect getEffect() {
            return effect;
        }

        public void setEffect(StatementEffect effect) {
            this.effect = effect;
        }

        public List<String> getPrincipals() {
            return principals;
        }

        public void setPrincipals(List<String> principals) {
            this.principals = principals;
        }

        public List<String> getActions() {
            return actions;
        }

        public void setActions(List<String> actions) {
            this.actions = actions;
        }

        public List<String> getResources() {
            return resources;
        }

        public void setResources(List<String> resources) {
            this.resources = resources;
        }

        public void addAction(String a) {
            if (actions == null) {
                actions = new ArrayList<String>();
            }
            actions.add(a);
        }
    }

    public static PolicyInventory valueOf(PolicyVO vo) {
        PolicyInventory inv = new PolicyInventory();
        inv.setName(vo.getName());
        inv.setUuid(vo.getUuid());
        inv.setStatements(JSONObjectUtil.toCollection(vo.getData(), ArrayList.class, Statement.class));
        inv.setAccountUuid(vo.getAccountUuid());
        return inv;
    }

    public static List<PolicyInventory> valueOf(Collection<PolicyVO> vos) {
        List<PolicyInventory> invs = new ArrayList<PolicyInventory>();
        for (PolicyVO vo : vos) {
            invs.add(valueOf(vo));
        }
        return invs;
    }

    private List<Statement> statements;
    private String name;
    private String uuid;
    private String accountUuid;

    public String getAccountUuid() {
        return accountUuid;
    }

    public void setAccountUuid(String accountUuid) {
        this.accountUuid = accountUuid;
    }

    public void addStatement(Statement s) {
        if (statements == null) {
            statements = new ArrayList<Statement>();
        }

        statements.add(s);
    }

    public void addStatement(List<Statement> s) {
        if (statements == null) {
            statements = new ArrayList<Statement>();
        }

        statements.addAll(s);
    }

    public List<Statement> getStatements() {
        return statements;
    }

    public void setStatements(List<Statement> statements) {
        this.statements = statements;
    }

    public String getName() {
        return name;
    }

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

    public String getUuid() {
        return uuid;
    }

    public void setUuid(String uuid) {
        this.uuid = uuid;
    }
}


text:
package org.globus.util.http;

import java.io.InputStream;
import java.io.IOException;

public class HTTPChunkedInputStream extends InputStream {

    protected byte[] _buf;
    protected int _index;
    protected int _max;
    protected boolean _eof;
    protected InputStream _in;

    public HTTPChunkedInputStream(InputStream in) {
	_in = in;
	// initial buf size - will adjust automatically
	_buf = new byte[2048];
	_index = 0;
	_max = 0;
	_eof = false;
    }

    /* only called when the buffer is empty */
    private void readChunk()
	throws IOException {

	String line = readLine(_in).trim();
	int length  = Integer.parseInt(line, 16);

	if (length > 0) {

	    // make sure the chunk will fit into the buffer

	    if (length > _buf.length) {
		_buf = new byte[length];
	    }

	    int bytesLeft = length;
	    int reqBytes = 0;
	    int off = 0;
	    int read = 0;

	    /*  multiple reads might be necessary to load
		the entire chunk */
	    while (bytesLeft != 0) {
		reqBytes = bytesLeft;
		read = _in.read(_buf, off, reqBytes);
		if (read == -1) break;
		bytesLeft -= read;
		off += read;
	    }

	    _max = off;
	    _index = 0;

	} else {
	    // end of data indicated
	    _eof = true;
	}

	_in.read(); // skip CR
	_in.read(); // skip LF

    }

    /**
     * Read a line of text from the given Stream and return it
     * as a String.  Assumes lines end in CRLF.
     */
    private String readLine(InputStream in) throws IOException {
	StringBuffer buf = new StringBuffer();
	int c, length = 0;

	while(true) {
	    c = in.read();
	    if (c == -1 || c == '\n' || length > 512) {
		break;
	    } else if (c == '\r') {
		in.read();
		return buf.toString();
	    } else {
		buf.append((char)c);
		length++;
	    }

	}
	return buf.toString();
    }

    public int read(byte [] buffer, int off, int len)
	throws IOException {
	if (_eof) return -1;
	if (_max == _index) readChunk();

	if (_index + len <= _max) {
	    // that's easy
	    System.arraycopy(_buf, _index, buffer, off, len);
	    _index += len;
	    return len;
	} else {
	    int maximum = _max - _index;
	    System.arraycopy(_buf, _index, buffer, off, maximum);
	    _index += maximum;
	    int read = read(buffer, off+maximum, len-maximum);
	    if (read == -1) {
		return maximum;
	    } else {
		return maximum + read;
	    }
	}
    }

    public int read()
	throws IOException {
	if (_eof) return -1;
	if (_max == _index) readChunk();
	return _buf[_index++] & 0xff;
    }

    public int available()
        throws IOException {
        return _in.available();
    }

    public void close()
	throws IOException {
	_in.close();
    }

}


text:
package com.bjorktech.cayman.idea.corejava.io.aio;

/**
 * User: sheshan
 * Date: 2018/8/9
 * content:
 */
public class GenericAIOServer {
}


text:
  Lhuys est
       un village
       situé dans le département de l'Aisne en Picardie. Elle comptait 137 habitants en 2008.

À coté de Lhuys sont situées les villes de
Mareuil-en-Dôle localisée à 4 km, 218 habitants,
Limé localisée à 4 km, 175 habitants,
Lesges à 4 km, 83 habitants,
Bruys localisée à 1 km, 20 habitants,
Jouaignes localisée à 2 km, 164 habitants,
Mont-Notre-Dame à 2 km, 645 habitants,
 entre autres. De plus, Lhuys est située à seulement 19 km de Soissons.

Si vous pensez emmenager à Lhuys, vous pourrez facilement trouver une maison à acheter.

Le nombre de logements, à Lhuys, était réparti en 2011 en quatre appartements et 60 maisons soit
 un marché plutôt équilibré.


text:
This is a standard compliant Standard Delay Format (SDF 2.1) parser. The library reads SDF file and produces
an Abstract Syntax Tree (AST) that downstream tools can use to query information in the SDF.

See http://www.eda.org/sdf/sdf_2.1.pdf for more information about the SDF syntax.

# INSTALLATION

Follow the standard cabal installation procedure:

> cabal install

# TEST

Unit tests are provided and can be executed like this:

> cabal configure --enable-tests
> cabal test

# USAGE

See the package `Text.SDF.V2p1.Parser.SDFParser` for the exposed methods for parsing and accessing the AST.


text:
This is an example program showing how to use the native MySQL connections from Google App Engine to [Google Cloud SQL](https://cloud.google.com/sql).

Refer to the [App Engine Samples README](../README.md) for information on how to run and deploy this sample.

## Setup

1. You will need to create a [Cloud SQL instance](https://cloud.google.com/sql/docs/create-instance).

2. Edit the `CLOUDSQL_INSTANCE` and `CLOUDSQL_PROJECT` values in `main.py`.

3. To run locally, you will need to be running a local instance of MySQL. You may need to update the connection code in `main.py` with the appropriate local username and password.


text:
using namespace clang::ast_matchers;

namespace clang {
namespace tidy {
namespace openmp {

void UseDefaultNoneCheck::registerMatchers(MatchFinder *Finder) {
  // Don't register the check if OpenMP is not enabled; the OpenMP pragmas are
  // completely ignored then, so no OpenMP entires will be present in the AST.
  if (!getLangOpts().OpenMP)
    return;

  Finder->addMatcher(
      ompExecutableDirective(
          allOf(isAllowedToContainClauseKind(OMPC_default),
                anyOf(unless(hasAnyClause(ompDefaultClause())),
                      hasAnyClause(ompDefaultClause(unless(isNoneKind()))
                                       .bind("clause")))))
          .bind("directive"),
      this);
}

void UseDefaultNoneCheck::check(const MatchFinder::MatchResult &Result) {
  const auto *Directive =
      Result.Nodes.getNodeAs<OMPExecutableDirective>("directive");
  assert(Directive != nullptr && "Expected to match some directive.");

  if (const auto *Clause = Result.Nodes.getNodeAs<OMPDefaultClause>("clause")) {
    diag(Directive->getBeginLoc(),
         "OpenMP directive '%0' specifies 'default(%1)' clause, consider using "
         "'default(none)' clause instead")
        << getOpenMPDirectiveName(Directive->getDirectiveKind())
        << getOpenMPSimpleClauseTypeName(Clause->getClauseKind(),
                                         Clause->getDefaultKind());
    diag(Clause->getBeginLoc(), "existing 'default' clause specified here",
         DiagnosticIDs::Note);
    return;
  }

  diag(Directive->getBeginLoc(),
       "OpenMP directive '%0' does not specify 'default' clause, consider "
       "specifying 'default(none)' clause")
      << getOpenMPDirectiveName(Directive->getDirectiveKind());
}

} // namespace openmp
} // namespace tidy
} // namespace clang


text:
package io.coala.xml;

import javax.xml.stream.XMLStreamReader;

/**
 * {@link StAXEventType}
 *
 * @version $Id$
 * @author Rick van Krevelen
 */
public enum StAXEventType
{
	/**
	 * Indicates an event is a start element
	 *
	 * @see javax.xml.stream.XMLStreamConstants#START_ELEMENT
	 * @see javax.xml.stream.events.StartElement
	 */
	START_ELEMENT,

	/**
	 * Indicates an event is an end element
	 *
	 * @see javax.xml.stream.XMLStreamConstants#END_ELEMENT
	 * @see javax.xml.stream.events.EndElement
	 */
	END_ELEMENT,

	/**
	 * Indicates an event is a processing instruction
	 *
	 * @see javax.xml.stream.XMLStreamConstants#PROCESSING_INSTRUCTION
	 * @see javax.xml.stream.events.ProcessingInstruction
	 */
	PROCESSING_INSTRUCTION,

	/**
	 * Indicates an event is characters
	 *
	 * @see javax.xml.stream.XMLStreamConstants#CHARACTERS
	 * @see javax.xml.stream.events.Characters
	 */
	CHARACTERS,

	/**
	 * Indicates an event is a comment
	 *
	 * @see javax.xml.stream.XMLStreamConstants#COMMENT
	 * @see javax.xml.stream.events.Comment
	 */
	COMMENT,

	/**
	 * The characters are white space (see [XML], 2.10 "White Space Handling").
	 * Events are only reported as SPACE if they are ignorable white space.
	 * Otherwise they are reported as CHARACTERS.
	 *
	 * @see javax.xml.stream.XMLStreamConstants#SPACE
	 * @see javax.xml.stream.events.Characters
	 */
	SPACE,

	/**
	 * Indicates an event is a start document
	 *
	 * @see javax.xml.stream.XMLStreamConstants#START_DOCUMENT
	 * @see javax.xml.stream.events.StartDocument
	 */
	START_DOCUMENT,

	/**
	 * Indicates an event is an end document
	 *
	 * @see javax.xml.stream.XMLStreamConstants#END_DOCUMENT
	 * @see javax.xml.stream.events.EndDocument
	 */
	END_DOCUMENT,

	/**
	 * Indicates an event is an entity reference
	 *
	 * @see javax.xml.stream.XMLStreamConstants#ENTITY_REFERENCE
	 * @see javax.xml.stream.events.EntityReference
	 */
	ENTITY_REFERENCE,

	/**
	 * Indicates an event is an attribute
	 *
	 * @see javax.xml.stream.XMLStreamConstants#ATTRIBUTE
	 * @see javax.xml.stream.events.Attribute
	 */
	ATTRIBUTE,

	/**
	 * Indicates an event is a DTD
	 *
	 * @see javax.xml.stream.XMLStreamConstants#DTD
	 * @see javax.xml.stream.events.DTD
	 */
	DTD,

	/**
	 * Indicates an event is a CDATA section
	 *
	 * @see javax.xml.stream.XMLStreamConstants#CDATA
	 * @see javax.xml.stream.events.Characters
	 */
	CDATA,

	/**
	 * Indicates the event is a namespace declaration
	 *
	 * @see javax.xml.stream.XMLStreamConstants#NAMESPACE
	 * @see javax.xml.stream.events.Namespace
	 */
	NAMESPACE,

	/**
	 * Indicates a Notation
	 *
	 * @see javax.xml.stream.XMLStreamConstants#NOTATION_DECLARATION
	 * @see javax.xml.stream.events.NotationDeclaration
	 */
	NOTATION_DECLARATION,

	/**
	 * Indicates a Entity Declaration
	 *
	 * @see javax.xml.stream.XMLStreamConstants#ENTITY_DECLARATION
	 * @see javax.xml.stream.events.NotationDeclaration
	 */
	ENTITY_DECLARATION,

	//
	;

	/**
	 * @param xmlReader
	 * @return
	 */
	public static StAXEventType valueOf( final XMLStreamReader xmlReader )
	{
		return xmlReader == null ? null : valueOf( xmlReader.getEventType() );
	}

	/**
	 * @param eventType
	 * @return
	 */
	public static StAXEventType valueOf( final int eventType )
	{
		if( eventType > values().length ) throw new IllegalArgumentException();
		return values()[eventType - 1];
	}
}


text:
package me.thekey.android.localbroadcast;

import androidx.annotation.RestrictTo;

import static androidx.annotation.RestrictTo.Scope.LIBRARY;

@RestrictTo(LIBRARY)
final class Constants {
    static final String ACTION_LOGIN = "thekey.action_login";
    static final String ACTION_LOGOUT = "thekey.action_logout";
    static final String ACTION_CHANGE_DEFAULT_SESSION = "thekey.action_change_default_session";
    static final String ACTION_ATTRIBUTES_LOADED = "thekey.action_attributes_loaded";

    static final String EXTRA_GUID = "guid";
    static final String EXTRA_CHANGING_USER = "changing_user";
}


text:
typedef int AVAILABLE_10_12 new_int; // expected-note + {{marked partial here}}

int func_10_11() AVAILABLE_10_11; // expected-note 8 {{'func_10_11' has been explicitly marked partial here}}

#ifdef OBJCPP
// expected-note@+2 6 {{marked partial here}}
#endif
int func_10_12() AVAILABLE_10_12; // expected-note 7 {{'func_10_12' has been explicitly marked partial here}}

int func_10_0() AVAILABLE_10_0;

void use_func() {
  func_10_11(); // expected-warning{{'func_10_11' is only available on macOS 10.11 or newer}} expected-note{{enclose 'func_10_11' in an @available check to silence this warning}}

  if (@available(macos 10.11, *))
    func_10_11();
  else
    func_10_11(); // expected-warning{{'func_10_11' is only available on macOS 10.11 or newer}} expected-note{{enclose 'func_10_11' in an @available check to silence this warning}}
}

void defn_10_11() AVAILABLE_10_11;

void defn_10_11() {
  func_10_11();
}

void nested_ifs() {
  if (@available(macos 10.12, *)) {
    if (@available(macos 10.10, *)) {
      func_10_12();
    } else {
      func_10_12();
    }
  } else {
    func_10_12(); // expected-warning{{'func_10_12' is only available on macOS 10.12 or newer}} expected-note{{enclose 'func_10_12' in an @available check to silence this warning}}
  }
}

void star_case() {
  if (@available(ios 9, *)) {
    func_10_11(); // expected-warning{{'func_10_11' is only available on macOS 10.11 or newer}} expected-note{{enclose 'func_10_11' in an @available check to silence this warning}}
    func_10_0();
  } else
    func_10_11(); // expected-warning{{'func_10_11' is only available on macOS 10.11 or newer}} expected-note{{enclose 'func_10_11' in an @available check to silence this warning}}

  if (@available(macOS 10.11, *)) {
    if (@available(ios 8, *)) {
      func_10_11();
      func_10_12(); // expected-warning{{'func_10_12' is only available on macOS 10.12 or newer}} expected-note{{enclose}}
    } else {
      func_10_11();
      func_10_12(); // expected-warning{{'func_10_12' is only available on macOS 10.12 or newer}} expected-note{{enclose}}
    }
  }
}

typedef int int_10_11 AVAILABLE_10_11; // expected-note {{'int_10_11' has been explicitly marked partial here}}
#ifdef OBJCPP
// expected-note@+2 {{marked partial here}}
#endif
typedef int int_10_12 AVAILABLE_10_12; // expected-note 2 {{'int_10_12' has been explicitly marked partial here}}

void use_typedef() {
  int_10_11 x; // expected-warning{{'int_10_11' is only available on macOS 10.11 or newer}} expected-note{{enclose 'int_10_11' in an @available check to silence this warning}}
}

__attribute__((objc_root_class))
AVAILABLE_10_11 @interface Class_10_11 { // expected-note{{annotate 'Class_10_11' with an availability attribute to silence}}
  int_10_11 foo;
  int_10_12 bar; // expected-warning {{'int_10_12' is only available on macOS 10.12 or newer}}
}
- (void)method1;
- (void)method2;
@end

@implementation Class_10_11
- (void) method1 {
  func_10_11();
  func_10_12(); // expected-warning{{'func_10_12' is only available on macOS 10.12 or newer}} expected-note{{enclose 'func_10_12' in an @available check to silence this warning}}
}

- (void)method2 AVAILABLE_10_12 {
  func_10_12();
}

@end

int protected_scope() {
  if (@available(macos 10.20, *)) { // expected-note 2 {{jump enters controlled statement of if available}}
  label1:
    return 0;
  } else {
  label2:
    goto label1; // expected-error{{cannot jump from this goto statement to its label}}
  }

  goto label2; // expected-error{{cannot jump from this goto statement to its label}}
}

struct S {
  int m1;
  int m2 __attribute__((availability(macos, introduced = 10.12))); // expected-note{{marked partial here}}

  struct Nested {
    int nested_member __attribute__((availability(macos, introduced = 10.12))); // expected-note{{marked partial here}}
  } n;
};

int test_members() {
  struct S s;
  (void)s.m1;
  (void)s.m2; // expected-warning{{'m2' is only available on macOS 10.12 or newer}} expected-note{{@available}}

  (void)s.n.nested_member; // expected-warning{{'nested_member' is only available on macOS 10.12 or newer}} expected-note{{@available}}
}

void test_blocks() {
  (void) ^{
    func_10_12(); // expected-warning{{'func_10_12' is only available on macOS 10.12 or newer}} expected-note{{@available}}
  };
}

void test_params(int_10_12 x); // expected-warning {{'int_10_12' is only available on macOS 10.12 or newer}} expected-note{{annotate 'test_params' with an availability attribute to silence this warning}}

void test_params2(int_10_12 x) AVAILABLE_10_12; // no warn

void (^topLevelBlockDecl)() = ^ {
  func_10_12(); // expected-warning{{'func_10_12' is only available on macOS 10.12 or newer}} expected-note{{@available}}
  if (@available(macos 10.12, *))
    func_10_12();
};

AVAILABLE_10_12
__attribute__((objc_root_class))
@interface InterWithProp // expected-note 2 {{marked partial here}}
@property(class) int x;
+ (void) setX: (int)newX AVAILABLE_10_12; // expected-note{{marked partial here}}
@end
void test_property(void) {
  int y = InterWithProp.x; // expected-warning{{'InterWithProp' is only available on macOS 10.12 or newer}} expected-note{{@available}}
  InterWithProp.x = y; // expected-warning{{'InterWithProp' is only available on macOS 10.12 or newer}} expected-note{{@available}} expected-warning{{'setX:' is only available on macOS 10.12 or newer}} expected-note{{@available}}
}

__attribute__((objc_root_class))
@interface Subscriptable
- (id)objectAtIndexedSubscript:(int)sub AVAILABLE_10_12; // expected-note{{marked partial here}}
@end

void test_at(Subscriptable *x) {
  id y = x[42]; // expected-warning{{'objectAtIndexedSubscript:' is only available on macOS 10.12 or newer}} expected-note{{@available}}
}

void uncheckAtAvailable() {
  if (@available(macOS 10.12, *) || 0) // expected-warning {{@available does not guard availability here; use if (@available) instead}}
    func_10_12(); // expected-warning {{'func_10_12' is only available on macOS 10.12 or newer}}
  // expected-note@-1 {{enclose 'func_10_12' in an @available check to silence this warning}}
}

void justAtAvailable() {
  int availability = @available(macOS 10.12, *); // expected-warning {{@available does not guard availability here; use if (@available) instead}}
}

#ifdef OBJCPP

int f(char) AVAILABLE_10_12;
int f(int);

template <class T> int use_f() {
  // FIXME: We should warn here!
  return f(T());
}

int a = use_f<int>();
int b = use_f<char>();

template <class> int use_at_available() {
  if (@available(macos 10.12, *))
    return func_10_12();
  else
    return func_10_12(); // expected-warning {{'func_10_12' is only available on macOS 10.12 or newer}} expected-note{{enclose}}
}

int instantiate_template() {
  if (@available(macos 10.12, *)) {
    use_at_available<char>();
  } else {
    use_at_available<float>();
  }
}

template <class>
int with_availability_attr() AVAILABLE_10_11 { // expected-note 2 {{marked partial here}}
  return 0;
}

int instantiate_with_availability_attr() {
  if (@available(macos 10.12, *))
    with_availability_attr<char>();
  else
    with_availability_attr<int>(); // expected-warning {{'with_availability_attr<int>' is only available on macOS 10.11 or newer}} expected-note {{enclose}}
}

int instantiate_availability() {
  if (@available(macOS 10.12, *))
    with_availability_attr<int_10_12>();
  else
    with_availability_attr<int_10_12>(); // expected-warning{{'with_availability_attr<int>' is only available on macOS 10.11 or newer}} expected-warning{{'int_10_12' is only available on macOS 10.12 or newer}} expected-note 2 {{enclose}}
}

auto topLevelLambda = [] () {
  func_10_12(); // expected-warning{{'func_10_12' is only available on macOS 10.12 or newer}} expected-note{{@available}}
  if (@available(macos 10.12, *))
    func_10_12();
};

void functionInFunction() {
  func_10_12(); // expected-warning{{'func_10_12' is only available on macOS 10.12 or newer}} expected-note{{@available}}
  struct DontWarnTwice {
    void f() {
      func_10_12(); // expected-warning{{'func_10_12' is only available on macOS 10.12 or newer}} expected-note{{@available}}
    }
  };
  void([] () {
    func_10_12(); // expected-warning{{'func_10_12' is only available on macOS 10.12 or newer}} expected-note{{@available}}
  });
  (void)(^ {
    func_10_12(); // expected-warning{{'func_10_12' is only available on macOS 10.12 or newer}} expected-note{{@available}}
  });
}

#endif

struct InStruct { // expected-note{{annotate 'InStruct' with an availability attribute to silence}}
  new_int mem; // expected-warning{{'new_int' is only available on macOS 10.12 or newer}}

  struct { new_int mem; } anon; // expected-warning{{'new_int' is only available on macOS 10.12 or newer}} expected-note{{annotate anonymous struct with an availability attribute to silence}}
};

#ifdef OBJCPP
static constexpr int AVAILABLE_10_12 SomeConstexprValue = 2; // expected-note{{marked partial here}}
typedef enum { // expected-note{{annotate anonymous enum with an availability attribute}}
  SomeValue = SomeConstexprValue // expected-warning{{'SomeConstexprValue' is only available on macOS 10.12 or newer}}
} SomeEnum;
#endif

@interface InInterface
-(new_int)meth; // expected-warning{{'new_int' is only available on macOS 10.12 or newer}} expected-note{{annotate 'meth' with an availability attribute}}
@end

@interface Proper // expected-note{{annotate 'Proper' with an availability attribute}}
@property (class) new_int x; // expected-warning{{'new_int' is only available}}
@end

void with_local_struct() {
  struct local { // expected-note{{annotate 'local' with an availability attribute}}
    new_int x; // expected-warning{{'new_int' is only available}}
  };
}

// rdar://33156429:
// Avoid the warning on protocol requirements.

AVAILABLE_10_12
@protocol NewProtocol // expected-note {{'NewProtocol' has been explicitly marked partial here}}
@end

@protocol ProtocolWithNewProtocolRequirement <NewProtocol> // expected-note {{annotate 'ProtocolWithNewProtocolRequirement' with an availability attribute to silence}}

@property(copy) id<NewProtocol> prop; // expected-warning {{'NewProtocol' is only available on macOS 10.12 or newer}}

@end

@interface BaseClass
@end

@interface ClassWithNewProtocolRequirement : BaseClass <NewProtocol>

@end

@interface BaseClass (CategoryWithNewProtocolRequirement) <NewProtocol>

@end

typedef enum {
  AK_Dodo __attribute__((availability(macos, deprecated=10.3))), // expected-note 3 {{marked deprecated here}}
  AK_Cat __attribute__((availability(macos, introduced=10.4))),
  AK_CyborgCat __attribute__((availability(macos, introduced=10.12))), // expected-note {{marked partial here}}
} Animals;

void switchAnimals(Animals a) {
  switch (a) {
  case AK_Dodo: break; // expected-warning{{'AK_Dodo' is deprecated}}
  case AK_Cat: break;
  case AK_Cat|AK_CyborgCat: break; // expected-warning{{case value not in enum}}
  case AK_CyborgCat: break; // no warn
  }

  switch (a) {
  case AK_Dodo...AK_CyborgCat: // expected-warning {{'AK_Dodo' is depr}}
    break;
  }

  (void)AK_Dodo; // expected-warning{{'AK_Dodo' is deprecated}}
  (void)AK_Cat; // no warning
  (void)AK_CyborgCat; // expected-warning{{'AK_CyborgCat' is only available on macOS 10.12 or newer}} expected-note {{@available}}
}

// test static initializers has the same availability as the deployment target and it cannot be overwritten.
@interface HasStaticInitializer : BaseClass
+ (void)load AVAILABLE_10_11; // expected-warning{{ignoring availability attribute on '+load' method}}
@end

@implementation HasStaticInitializer
+ (void)load {
  func_10_11(); // expected-warning{{'func_10_11' is only available on macOS 10.11 or newer}} expected-note{{enclose 'func_10_11' in an @available check to silence this warning}}
}
@end

// test availability from interface is ignored when checking the unguarded availability in +load method.
AVAILABLE_10_11
@interface HasStaticInitializer1 : BaseClass
+ (void)load;
+ (void)load: (int)x; // no warning.
@end

@implementation HasStaticInitializer1
+ (void)load {
  func_10_11(); // expected-warning{{'func_10_11' is only available on macOS 10.11 or newer}} expected-note{{enclose 'func_10_11' in an @available check to silence this warning}}
}
+ (void)load: (int)x {
  func_10_11(); // no warning.
}
@end

__attribute__((constructor))
void is_constructor();

AVAILABLE_10_11 // expected-warning{{ignoring availability attribute with constructor attribute}}
void is_constructor() {
  func_10_11(); // expected-warning{{'func_10_11' is only available on macOS 10.11 or newer}} expected-note{{enclose 'func_10_11' in an @available check to silence this warning}}
}

AVAILABLE_10_11 // expected-warning{{ignoring availability attribute with destructor attribute}}
__attribute__((destructor))
void is_destructor() {
  func_10_11(); // expected-warning{{'func_10_11' is only available on macOS 10.11 or newer}} expected-note{{enclose 'func_10_11' in an @available check to silence this warning}}
}


text:
``` dart
Number
String
Boolean
List
Set
Map
Rune
Symbol
```

## constructor function

``` dart
class ClassName {
    int a;
    int b;
    ClassName(this.a, this.b);
}
```

## fat arrow function

``` dart
int funcName() => 42;
```

## get and set function

``` dart
class myClass {
  String name;
  String get getName => name;
  set setName(String aValue) => name = aValue;
}

var myObject = myClass();
myObject.setName = "Sanjib";
print(myObject.getName);
```

## override
@override is not a must tag, with it can enhances the code reading.

``` dart
@override
void hello() {
    return "world";
}
```

## mixin

``` dart
class A extends B with C
// Use A class all methods and the methods that B class does not cover
class T = A with B;
```
A can inheritance B class and use C class functions.

## null check

``` dart
x ??= 3;
```

## Cascades

``` dart
"String".length.toString(); // 6
"String"..length.toString(); // "String"
```

## type

``` dart
var type_string = <String> ['a', 'b', 'c'];
print(type_string);
print("hello" + "world");
print("hello" * 2);
```

## Set, StringBuffer data type

``` dart
Set mySet = {1, 2, 3};
mySet.lookup(2);

StringBuffer stringBuffer = StringBuffer('test string');
stringBuffer.write(' append string');
```

## Future class

``` dart
import 'dart:async';

void main(){

  print("The main UI thread is starting on here.");
  Future<String> displayingNewsHeadlines = Future.delayed(Duration(seconds: 1), (){
      return "The latest headlines are displayed here after 1 second.";
  });

  displayingNewsHeadlines.then((displayString){
      print("Displaying news headlines here: $displayingNewsHeadlines, the displayString : $displayString");
  });
  print("The main UI thread ends.");

}

```
the output:

```
The main UI thread is starting on here.
The main UI thread ends.
Displaying news headlines here: Instance of 'Future<String>', the displayString : The latest headlines are displayed here after 1 second.
```
It is noted that, the Future object still runs after the end of the main function.
Some methods:

``` dart
catchError(Function onError, {bool test(Object error)}) → Future<T>
then<R>(FutureOr<R> onValue(T value), {Function onError}) → Future<R>
timeout(Duration timeLimit, {FutureOr<T> onTimeout()}) → Future<T>
whenComplete(FutureOr action()) → Future<T>
```

## runZonedGuarded function

``` dart
// 这样就可以处理所有未处理的异常了。
void main() async {
  runZonedGuarded(() => runApp(const App()));
 }
```
copy from [Flutter runZonedGuarded捕捉不到未处理错误问题的原因](https://segmentfault.com/a/1190000022892971)

## Isolate

``` dart
Isolate.spawn<T>(void entryPoint(T message), T message, {bool paused: false, bool errorsAreFatal, SendPort onExit, SendPort onError, String debugName}) → Future<Isolate>
Isolate.kill({int priority: beforeNextEvent}) → void
```

## async, await

``` dart
main() {
    getData();
    print("continue...");
}

getData() async {
    var data = await "data string";
    print(data);
}
```

## ~/ operator

``` dart
5 ~/ 2 == 2;
7 ~/ 4 == 2;
```