text:
<?php

/**
 * Base class for Multipart parsers.
 *
 * @package Mail
 * @version 1.7beta1
 * @access private
 */
abstract class ezcMailMultipartParser extends ezcMailPartParser
{
    /**
     * The boundary separator string.
     *
     * @var string
     */
    private $boundary = null;

    /**
     * The headers for the multipart.
     *
     * @var ezcMailHeadersHolder
     */
    protected $headers = null;

    /**
     * The headers for the current subpart.
     *
     * @var ezcMailHeadersHolder
     */
    private $currentPartHeaders = null;

    /**
     * The current part.
     *
     * @var ezcMailPartParser
     */
    private $currentPartParser = null;

    /**
     * This state is used prior to hitting the first part.
     */
    const PARSE_STATE_PRE_FIRST = 1;

    /**
     * This state is used when the parser is parsing headers.
     */
    const PARSE_STATE_HEADERS = 2;

    /**
     * This state is used when the parser is parsing the body.
     */
    const PARSE_STATE_BODY = 3;

    /**
     * This state is set after the last of the parts is closed.
     */
    const PARSE_STATE_POST_LAST = 4;

    /**
     * Stores the state of the parser.
     *
     * @var int
     */
    private $parserState = self::PARSE_STATE_PRE_FIRST;

    /**
     * Constructs a new Multipart parser.
     *
     * @param ezcMailHeadersHolder $headers
     */
    public function __construct( ezcMailHeadersHolder $headers )
    {
        $this->headers = $headers;

        // get the boundary
        preg_match( '/\s*boundary="?([^;"]*);?/i',
                    $this->headers['Content-Type'],
                    $parameters );
        if ( count( $parameters ) > 0 )
        {
            $this->boundary = trim( $parameters[1], '"' );
        }
        else
        {
            // no boundary?!? Houston, we have a problem.
            // todo: try to detect the boundary by scanning for --lines
        }
    }

    /**
     * Parses a multipart body.
     *
     * @throws ezcBaseFileNotFoundException
     *         if a neccessary temporary file could not be opened.
     * @param string $origLine
     */
    public function parseBody( $origLine )
    {
        if ( $this->parserState == self::PARSE_STATE_POST_LAST )
        {
            return;
        }

        $line = rtrim( $origLine, "\r\n" );

        // check if we hit any of the boundaries
        $newPart = false;
        $endOfMultipart = false;
        if ( strlen( $line ) > 0 && $line[0] == "-" )
        {
            if ( strcmp( trim( $line ), '--' . $this->boundary ) === 0 )
            {
                $newPart = true;
            }
            else if ( strcmp( trim( $line ), '--' . $this->boundary . '--' ) === 0 )
            {
                $endOfMultipart = true;
            }
        }

        // actions to do when starting or finishing a part
        if ( $newPart || $endOfMultipart )
        {
            if ( $this->parserState != self::PARSE_STATE_BODY )
            {
                // something is b0rked, we got a new separator before getting a body
                // we'll skip this part and continue to the next
                $this->currentPartParser = null;
                $this->currentPartHeaders = new ezcMailHeadersHolder();
                $this->parserState = $newPart ? self::PARSE_STATE_HEADERS : self::PARSE_STATE_POST_LAST;
            }
            else
            {
                // complete the work on the current part if there was any
                if ( $this->currentPartParser !== null )
                {
                    $part = $this->currentPartParser->finish();
                    if ( $part !== null ) // parsing failed
                    {
                        $this->partDone( $part );
                    }
                }

                // prepare for a new part if any
                $this->currentPartParser = null;
                $this->parserState =self::PARSE_STATE_POST_LAST;
                if ( $newPart )
                {
                    $this->parserState = self::PARSE_STATE_HEADERS;
                    $this->currentPartHeaders = new ezcMailHeadersHolder();
                }
            }
        }
        // normal data, pass to headers or current body
        else
        {
            if ( $this->parserState == self::PARSE_STATE_HEADERS && $line == '' )
            {
                $this->currentPartParser = self::createPartParserForHeaders( $this->currentPartHeaders );
                $this->parserState = self::PARSE_STATE_BODY;
            }
            else if ( $this->parserState == self::PARSE_STATE_HEADERS )
            {
                $this->parseHeader( $line, $this->currentPartHeaders );
            }
            else if ( $this->parserState == self::PARSE_STATE_BODY )
            {
                if ( $this->currentPartParser ) // we may have none if the part type was unknown
                {
                    // send body data to the part
                    $this->currentPartParser->parseBody( $origLine );
                }
            }
            // we are done parsing the multipart, ignore anything else pushed to us.
        }
    }

    /**
     * Completes the parsing of the multipart and returns the corresponding part.
     *
     * This method should not be overriden. Use finishMultipart() instead.
     *
     * @return ezcMailMultipart
     */
    public function finish()
    {
        if ( $this->parserState != self::PARSE_STATE_POST_LAST )
        {
            // this should never happen
            // let's give the last parser a chance to clean up after himself
            if ( $this->currentPartParser !== null )
            {
                $part = $this->currentPartParser->finish();
                $this->partDone( $part );
                $this->currentPartParser = null;
            }
        }
        $multipart = $this->finishMultipart();
        ezcMailPartParser::parsePartHeaders( $this->headers, $multipart );
        $multipart->boundary = $this->boundary;
        return $multipart;
    }

    /**
     * This function will be called every time a part has been parsed.
     *
     * Implementors should put the part into the correct multitype part.
     * @param ezcMailPart $part
     */
    abstract public function partDone( ezcMailPart $part );

    /**
     * Returns the multipart part corresponding to the parsed object.
     *
     * This method is called by finish() when all parts have been parsed.
     *
     * @return ezcMailMultipart
     */
    abstract public function finishMultipart();
}
?>


text:
<?php

namespace CallStaticMethods;

class Foo
{

	public static function test()
	{
		Bar::protectedMethodFromChild();
	}

	protected static function baz()
	{

	}

	public function loremIpsum()
	{

	}

	private static function dolor()
	{

	}

}

class Bar extends Foo
{

	public static function test()
	{
		Foo::test();
		Foo::baz();
		parent::test();
		parent::baz();
		Foo::bar(); // nonexistent
		self::bar(); // nonexistent
		parent::bar(); // nonexistent
		Foo::loremIpsum(); // instance
		Foo::dolor();
	}

	public function loremIpsum()
	{
		parent::loremIpsum();
	}

	protected static function protectedMethodFromChild()
	{

	}

}

class Ipsum
{

	public static function ipsumTest()
	{
		parent::lorem(); // does not have a parent
		Foo::test();
		Foo::test(1);
		Foo::baz(); // protected and not from a parent
		UnknownStaticMethodClass::loremIpsum();
	}

}

class ClassWithConstructor
{

	private function __construct($foo)
	{

	}

}

class CheckConstructor extends ClassWithConstructor
{

	public function __construct()
	{
		parent::__construct();
	}

}

function () {
	self::someStaticMethod();
	static::someStaticMethod();
	parent::someStaticMethod();
	Foo::test();
	Foo::baz();
	Foo::bar();
	Foo::loremIpsum();
	Foo::dolor();

	\Locale::getDisplayLanguage('cs_CZ'); // OK
	\Locale::getDisplayLanguage('cs_CZ', 'en'); // OK
	\Locale::getDisplayLanguage('cs_CZ', 'en', 'foo'); // should report 3 parameters given, 1-2 required
};

interface SomeInterface
{

}

function (Foo $foo) {
	if ($foo instanceof SomeInterface) {
		$foo::test();
		$foo::test(1, 2, 3);
	}

	/** @var string|int $stringOrInt */
	$stringOrInt = doFoo();
	$stringOrInt::foo();
};

function (FOO $foo)
{
	$foo::test(); // do not report case mismatch

	FOO::unknownMethod();
	FOO::loremIpsum();
	FOO::dolor();
	FOO::test(1, 2, 3);
	FOO::TEST();
	FOO::test();
};

function (string $className) {
	$className::foo();
};

class CallingNonexistentParentConstructor extends Foo
{

	public function __construct()
	{
		parent::__construct();
	}

}

class Baz extends Foo
{

	public function doFoo()
	{
		parent::nonexistent();
	}

	public static function doBaz()
	{
		parent::nonexistent();
		parent::loremIpsum();
	}

}

class ClassOrString
{

	public function doFoo()
	{
		/** @var self|string $class */
		$class = doFoo();
		$class::calledMethod();
		$class::calledMethod(1);
		Self::calledMethod();
	}

	private static function calledMethod()
	{

	}

}

redpajama_set_name: RedPajamaGithub


text:
// *****************************************************
// CIXReader
// StyleController.cs
//
// Author: Steve Palmer (spalmer@cix)
//
// Created: 15/05/2015 16:44
//
// Copyright (C) 2013-2015 CIX Online Ltd. All Rights Reserved.
// *****************************************************

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using CIXClient;
using CIXClient.Tables;
using CommonMark;

namespace CIXReader.Utilities
{
    public sealed class StyleController
    {
        // Styles path mappings is global across all instances
        private static Dictionary<string, string> _stylePathMappings;

        private readonly string _styleName;

        private bool _inited;
        private string _htmlTemplate;
        private string _cssStyleSheet;
        private string _jsScript;

        // Smiley emoticons as constants
        private const string emoSmiley = ":-)";
        private const string emoLaugh = ":-D";
        private const string emoFrown = ":-(";
        private const string emoWink = ";-)";
        private const string emoShades = "8-)";
        private Dictionary<string, string> _emoticonDictionary;

        ///
        /// Initialise the template and stylesheet for the specified display style if it can be
        /// found. Otherwise the existing template and stylesheet are not changed.
        ///
        /// <param name="styleName">Name of the style to use</param>
        public StyleController(string styleName)
        {
            _styleName = styleName;
            _inited = false;
        }

        ///
        /// Load the styles map from the styles folder.
        ///
        public static void LoadStyleMap()
        {
            if (_stylePathMappings == null)
            {
                _stylePathMappings = new Dictionary<string, string>();

                string appPath = Path.GetDirectoryName(Application.ExecutablePath);
                if (appPath != null)
                {
                    string stylesFolder = Path.Combine(appPath, "Styles");
                    LoadMapFromPath(stylesFolder, _stylePathMappings);
                }

                if (CIX.HomeFolder != null)
                {
                    string stylesFolder = Path.Combine(CIX.HomeFolder, "Styles");
                    if (Directory.Exists(stylesFolder))
                    {
                        LoadMapFromPath(stylesFolder, _stylePathMappings);
                    }
                }
            }
        }

        ///
        /// Return a list of all available styles.
        ///
        public static IEnumerable<string> AllStyles
        {
            get
            {
                LoadStyleMap();
                return _stylePathMappings.Keys.ToList();
            }
        }

        ///
        /// Initialise the template and stylesheet for the specified display style if it can be
        /// found. Otherwise the existing template and stylesheet are not changed.
        ///
        public void LoadStyle()
        {
            LoadStyleMap();
            if (!_inited)
            {
                string path;
                if (_stylePathMappings.TryGetValue(_styleName, out path))
                {
                    try
                    {
                        string filePath = Path.Combine(path, "template.html");
                        string templateString = File.ReadAllText(filePath);

                        if (!string.IsNullOrWhiteSpace(templateString))
                        {
                            _htmlTemplate = templateString;
                            _cssStyleSheet = Path.Combine(path, "stylesheet.css");

                            string javaScriptPath = Path.Combine(path, "script.js");
                            if (File.Exists(javaScriptPath))
                            {
                                _jsScript = javaScriptPath;
                            }

                            // Make sure template is valid
                            string firstLine = _htmlTemplate.FirstNonBlankLine().ToLower();
                            if (firstLine.StartsWith("") || firstLine.StartsWith("<!doctype"))
                            {
                                _htmlTemplate = null;
                                _cssStyleSheet = null;
                                _jsScript = null;
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        LogFile.WriteLine("Failed to read style {0} : {1}", _styleName, e.Message);
                    }
                }
                _inited = true;
            }
        }

        ///
        /// Get or set the text that is highlighted in the body of the message
        ///
        public string Highlight { get; set; }

        ///
        /// Get or set a flag which specifies whether or not markup is enabled.
        ///
        public bool DisableMarkup { get; set; }

        ///
        /// Get or set a flag which specifies whether inline images are expanded.
        ///
        public bool ExpandInlineImages { get; set; }

        public string ImageFromTag(string tag)
        {
            return string.Format("mugshot:{0}", tag);
        }

        public string StringFromTag(string tag)
        {
            return string.IsNullOrEmpty(tag) ? string.Empty : tag;
        }

        public string DateFromTag(DateTime tag)
        {
            return tag.FriendlyString(true);
        }

        public string HtmlFromTag(string tag)
        {
            string text = tag;
            if (!String.IsNullOrEmpty(text))
            {
                Regex r;

                // If text contains explicit XML, temporarily disable markup for this message
                bool localDisableMarkup = DisableMarkup || (text.Contains("?xml"));

                // Make sure all invalid HTML characters are converted to entities.
                if (localDisableMarkup)
                {
                    text = text.EscapeXml();
                }

                if (Highlight != null)
                {
                    r = new Regex(string.Format("({0})", Highlight), RegexOptions.Multiline | RegexOptions.IgnoreCase);
                    text = r.Replace(text, "$1");
                }

                // Replace hard newlines with break tags.
                text = localDisableMarkup ? text.Replace("\n", "
") : CommonMarkConverter.Convert(text);

                // Hack to convert

 and

 because HtmlRenderer doesn't yet render these properly.
                text = text.Replace("
\r\n
", "
");
                text = text.Replace("
\r\n
", "
");

                // Convert HTTP:// (etc) and www / ftp (etc) links to actual links.
                const string regexlink = @"(((http|https|ftp|news|file)+\:\/\/|www\.|ftp\.)[_.a-z0-9-]+\.[a-z0-9\/_:@=.+?,#!_%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])";
                r = new Regex(regexlink, RegexOptions.IgnoreCase);
                text = r.Replace(text, "$1").Replace("href=\"www", "href=\"http://www");

                // Make cix: links into links. These have slightly odder syntax than http
                // so we handle these especially.
                const string cixRegex = @"(cix\:[a-z0-9._\-:/]*[a-z0-9]+)";
                r = new Regex(cixRegex, RegexOptions.IgnoreCase);
                text = r.Replace(text, "$1");

                // Look for image links and replace with img tags
                // Only HTTP links are used for now.
                if (ExpandInlineImages)
                {
                    const string imgRegex = "()(.*)()";
                    r = new Regex(imgRegex, RegexOptions.IgnoreCase);
                    text = r.Replace(text, "$1$3");
                    text = text.Replace("image:http://", "image:");
                }

                // Make cixfile: links into links. These are converted to:
                //
                //  http://forums.cix.co.uk/secure/cixfile.aspx?forum={forum}&topic={topic}&file={filename}
                //
                const string cixfileRegex = @"cixfile\:([a-z0-9._\-]+)/([a-z0-9._\-]+):([a-z0-9\/_:@=.+?,#_%&~-]+)";
                r = new Regex(cixfileRegex, RegexOptions.IgnoreCase);
                text = r.Replace(text, "cixfile:$1/$2:$3");

                // Do Smiley replacement
                if (!DisableMarkup)
                {
                    text = ReplaceEmoticons(text);
                }
            }
            return text;
        }

        ///
        /// Convert any emoticons in the string to references to their actual file in the resources.
        ///
        public string ReplaceEmoticons(string source)
        {
            if (_emoticonDictionary == null)
            {
                _emoticonDictionary = new Dictionary<string, string>();
                _emoticonDictionary[emoSmiley] = "smiley";
                _emoticonDictionary[emoLaugh] = "laugh";
                _emoticonDictionary[emoFrown] = "frown";
                _emoticonDictionary[emoShades] = "shades";
                _emoticonDictionary[emoWink] = "wink";
            }

            // Always assume that emoticon is in the dictionary. It is an error otherwise.
            string assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            return _emoticonDictionary.Keys.Aggregate(source, (current, emoticon) =>
                current.Replace(emoticon, ""));
        }

        ///
        /// Return an NSString containing the tagged item collection formatted as HTML
        ///
        /// This method iterates over the items in the collection and creates an NSString that contains
        /// the items using the specified style template if one was specified.
        ///
        public string StyledTextForCollection(IEnumerable<CIXMessage> array)
        {
            LoadStyle();

            StringBuilder htmlText = new StringBuilder("<!DOCTYPE html><meta charset=\"UTF-8\" />");
            if (_cssStyleSheet != null)
            {
                htmlText.Append("<link rel=\"stylesheet\" type=\"text/css\" href=\"");
                htmlText.Append(_cssStyleSheet);
                htmlText.Append("\"/>");
            }
            if (_jsScript != null)
            {
                htmlText.Append("");
            }
            htmlText.Append("<meta http-equiv=\"Pragma\" content=\"no-cache\">");
            htmlText.Append("");

            int index = 0;
            foreach (CIXMessage message in array)
            {
                StringBuilder htmlMessage = new StringBuilder();

                if (_htmlTemplate == null)
                {
                    htmlMessage.Append(message.UnformattedText());
                }
                else
                {
                    Scanner scanner = new Scanner(_htmlTemplate);
                    bool stripIfEmpty = false;
                    string theString = null;

                    while (!scanner.IsAtEnd)
                    {
                        if (scanner.ScanUpToString("", ref commentTag) && commentTag != null)
                            {
                                commentTag = commentTag.Trim();
                                if (commentTag == "cond:noblank")
                                {
                                    stripIfEmpty = true;
                                }
                                if (commentTag == "end")
                                {
                                    stripIfEmpty = false;
                                }
                                scanner.ScanString("-->", ref theString);
                            }
                        }
                    }
                }

                // Separate each message with a horizontal divider line
                if (index > 0)
                {
                    htmlText.Append("

");
                }
                htmlText.Append(htmlMessage);
                ++index;
            }

            htmlText.Append("");
            return htmlText.ToString();
        }

        ///
        /// Expands recognised tags in theString based on the object values.
        ///
        private string ExpandTags(string theString, CIXMessage message, bool cond)
        {
            bool hasOneTag = false;
            int tagStartIndex = 0;

            while ((tagStartIndex = theString.IndexOf('$', tagStartIndex)) >= 0)
            {
                int tagEndIndex = theString.IndexOf('$', tagStartIndex + 1);
                if (tagEndIndex < 0)
                {
                    break;
                }
                int tagLength = (tagEndIndex - tagStartIndex) + 1;
                string tagName = theString.Substring(tagStartIndex + 1, tagLength - 2);
                string tagSelName = string.Format("tag{0}", tagName);

                Type messageType = typeof(TaggedMessage);
                MethodInfo method = messageType.GetMethod(tagSelName);
                string replacementString = (string) method.Invoke(message, new object[]{ message, this });

                if (replacementString == null)
                {
                    theString = theString.Substring(0, tagStartIndex) + theString.Substring(tagEndIndex + 1);
                }
                else
                {
                    theString = theString.Substring(0, tagStartIndex) + replacementString + theString.Substring(tagEndIndex + 1);
                    hasOneTag = true;

                    if (!string.IsNullOrEmpty(replacementString))
                    {
                        cond = false;
                    }

                    tagStartIndex += replacementString.Length;
                }
            }
            return (cond && hasOneTag) ? string.Empty : theString;
        }

        ///
        /// Read all files from the specified path and construct a mapping of name to
        /// the actual paths and store in the mappings dictionary supplied.
        ///
        private static void LoadMapFromPath(string path, Dictionary<string, string> mappings)
        {
            IEnumerable<string> directories = Directory.EnumerateDirectories(path);
            foreach (string directory in directories)
            {
                string name = Path.GetFileNameWithoutExtension(directory);
                if (name != null)
                {
                    mappings[name] = directory;
                }
            }
        }
    }
}


text:
package exceptions;

public class IDInexistenteException extends ControllerException {

	private static final long serialVersionUID = 1L;

	public IDInexistenteException (String mensagem) {
		super("Não existe esse ID de " + mensagem);
	}

}


text: Hazelcast Image CI


text:
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-2.0.xsd">

	<changeSet id="merge-data-query-and-data-error-query" author="ricci" dbms="postgresql">
		<comment>Add columns to the data error report table</comment>

		<createSequence sequenceName="ofc_data_query_type_id_seq" />

	    <createTable tableName="ofc_data_query_type">
			<column name="id" type="INTEGER">
				<constraints nullable="false" primaryKey="true"
					primaryKeyName="ofc_data_query_type_pkey" />
			</column>
			<column name="uuid" type="VARCHAR(50)" />
			<column name="survey_id" type="INTEGER">
				<constraints nullable="false"
					foreignKeyName="ofc_data_query_type_survey_fkey"
					references="ofc_survey(id)" />
			</column>
			<column name="code" type="VARCHAR(255)">
				<constraints nullable="false" />
			</column>
			<column name="label" type="VARCHAR(255)" />
			<column name="description" type="VARCHAR(255)" />
			<column name="creation_date" type="TIMESTAMP" />
			<column name="modified_date" type="TIMESTAMP" />
		</createTable>

		<sql>
			INSERT INTO collect.ofc_data_query_type (id, uuid, survey_id, code, label, description, creation_date, modified_date)
				SELECT t.id, t.uuid, t.survey_id, t.code, t.label, t.description, t.creation_date, t.modified_date
				FROM collect.ofc_data_error_type t;
		</sql>

		<addColumn tableName="ofc_data_query">
			<column name="type_id" type="INTEGER">
				<constraints
					foreignKeyName="ofc_data_query_type_fkey"
					references="ofc_data_query_type(id)" />
			</column>
			<column name="severity" type="CHAR(1)" defaultValue="n" />
	    </addColumn>

		<sql>
	    	UPDATE collect.ofc_data_query
	    	SET type_id = (
	    		SELECT deq.error_type_id
	    		FROM collect.ofc_data_error_query deq
	    		WHERE deq.query_id = collect.ofc_data_query.id
	    	);

	    	UPDATE collect.ofc_data_query
	    	SET severity = (
	    		SELECT deq.severity
	    		FROM collect.ofc_data_error_query deq
	    		WHERE deq.query_id = collect.ofc_data_query.id
	    	);

	    	UPDATE collect.ofc_data_query
	    	SET severity = 'n'
	    	WHERE severity is null;
		</sql>

		<createSequence sequenceName="ofc_data_query_group_id_seq" />

		<createTable tableName="ofc_data_query_group">
			<column name="id" type="INTEGER">
				<constraints nullable="false" primaryKey="true"
					primaryKeyName="ofc_data_query_group_pkey" />
			</column>
			<column name="uuid" type="VARCHAR(50)" />
			<column name="survey_id" type="INTEGER">
				<constraints nullable="false"
					foreignKeyName="ofc_data_query_group_survey_fkey"
					references="ofc_survey(id)" />
			</column>
			<column name="title" type="VARCHAR(255)">
				<constraints nullable="false" />
			</column>
			<column name="description" type="VARCHAR(255)" />
			<column name="creation_date" type="TIMESTAMP" />
			<column name="modified_date" type="TIMESTAMP" />
		</createTable>

		<createTable tableName="ofc_data_query_group_query">
			<column name="group_id" type="INTEGER">
				<constraints nullable="false"
					foreignKeyName="ofc_data_query_group_group_fkey"
					references="ofc_data_query_group(id)" />
			</column>
			<column name="query_id" type="INTEGER">
				<constraints nullable="false"
					foreignKeyName="ofc_data_query_group_query_fkey"
					references="ofc_data_query(id)" />
			</column>
			<column name="sort_order" type="INTEGER">
				<constraints nullable="false" />
			</column>
		</createTable>

		<addPrimaryKey
			tableName="ofc_data_query_group_query"
			columnNames="group_id, query_id"
            constraintName="ofc_data_query_group_query_pkey" />

        <sql>
        	INSERT INTO collect.ofc_data_query_group (id, uuid, survey_id, title, description, creation_date, modified_date)
        		SELECT deqg.id, deqg.uuid, deqg.survey_id, deqg.title, deqg.description, deqg.creation_date, deqg.modified_date
        		FROM collect.ofc_data_error_query_group deqg
        	;

        	INSERT INTO collect.ofc_data_query_group_query (group_id, query_id, sort_order)
        		SELECT deqgq.group_id, deq.query_id, deqgq.sort_order
        		FROM collect.ofc_data_error_query_group_query deqgq
        			JOIN collect.ofc_data_error_query deq ON deq.id = deqgq.query_id
        	;
        </sql>

        <createSequence sequenceName="ofc_data_report_id_seq" />

		<createTable tableName="ofc_data_report">
			<column name="id" type="INTEGER">
				<constraints nullable="false" primaryKey="true"
					primaryKeyName="ofc_data_report_pkey" />
			</column>
			<column name="uuid" type="VARCHAR(50)" />
			<column name="query_group_id" type="INTEGER">
				<constraints nullable="false"
					foreignKeyName="ofc_data_report_query_group_fkey"
					references="ofc_data_query_group(id)" />
			</column>
			<column name="record_step" type="int4" />
			<column name="dataset_size" type="int4" />
			<column name="last_record_modified_date" type="TIMESTAMP" />
			<column name="creation_date" type="TIMESTAMP" />
		</createTable>

		<createSequence sequenceName="ofc_data_report_item_id_seq" />

		<createTable tableName="ofc_data_report_item">
			<column name="id" type="INTEGER">
				<constraints nullable="false" primaryKey="true"
					primaryKeyName="ofc_data_report_item_pkey" />
			</column>
			<column name="uuid" type="VARCHAR(50)" />
			<column name="report_id" type="INTEGER">
				<constraints nullable="false"
					foreignKeyName="ofc_data_report_item_report_fkey"
					references="ofc_data_report(id)" />
			</column>
			<column name="query_id" type="INTEGER">
				<constraints nullable="false"
					foreignKeyName="ofc_data_report_item_query_fkey"
					references="ofc_data_query(id)" />
			</column>
			<column name="record_id" type="INTEGER">
				<constraints nullable="false"
					foreignKeyName="ofc_data_report_item_record_fkey"
					references="ofc_record(id)" />
			</column>
			<column name="parent_entity_id" type="INTEGER">
				<constraints nullable="false" />
			</column>
			<column name="node_index" type="INTEGER" />
			<column name="value" type="VARCHAR(255)" />
			<column name="status" type="CHAR(1)" />
		</createTable>

		<createIndex
	            indexName="ofc_data_report_item_report_record_idx"
	            tableName="ofc_data_report_item">
        	<column name="report_id" type="INTEGER"/>
        	<column name="record_id" type="INTEGER"/>
       </createIndex>

       <sql>
       		INSERT INTO collect.ofc_data_report (id, uuid, query_group_id, record_step, creation_date, dataset_size, last_record_modified_date)
       			SELECT r.id, r.uuid, r.query_group_id, r.record_step, r.creation_date, dataset_size, last_record_modified_date
       			FROM collect.ofc_data_error_report r
       		;

       		INSERT INTO collect.ofc_data_report_item (id, uuid, report_id, query_id, record_id, parent_entity_id, node_index, value, status)
       			SELECT ri.id, ri.uuid, ri.report_id, deq.query_id, ri.record_id, ri.parent_entity_id, ri.node_index, ri.value, ri.status
       			FROM collect.ofc_data_error_report_item ri
       				JOIN collect.ofc_data_error_query deq ON deq.id = ri.query_id
       		;
       </sql>

       <dropTable tableName="ofc_data_error_report_item" />
       <dropTable tableName="ofc_data_error_report" />
       <dropTable tableName="ofc_data_error_query_group_query" />
       <dropTable tableName="ofc_data_error_query_group" />
       <dropTable tableName="ofc_data_error_query" />
       <dropTable tableName="ofc_data_error_type" />

       <dropSequence sequenceName="ofc_data_error_type_id_seq" />
       <dropSequence sequenceName="ofc_data_error_query_id_seq" />
       <dropSequence sequenceName="ofc_data_error_query_group_id_seq" />
       <dropSequence sequenceName="ofc_data_error_report_id_seq" />
       <dropSequence sequenceName="ofc_data_error_report_item_id_seq" />

       <sql>
       		SELECT setval('collect.ofc_data_query_type_id_seq', (SELECT max(id) + 1 FROM collect.ofc_data_query_type));
       		SELECT setval('collect.ofc_data_query_id_seq', (SELECT max(id) + 1 FROM collect.ofc_data_query));
       		SELECT setval('collect.ofc_data_query_group_id_seq', (SELECT max(id) + 1 FROM collect.ofc_data_query_group));
       		SELECT setval('collect.ofc_data_report_id_seq', (SELECT max(id) + 1 FROM collect.ofc_data_report));
       		SELECT setval('collect.ofc_data_report_item_id_seq', (SELECT max(id) + 1 FROM collect.ofc_data_report_item));
       </sql>
	</changeSet>

</databaseChangeLog>


text:
MediaType
=========

.. automodule:: yael.mediatype
    :members:
    :private-members:


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.8"/>
<title>BlackBone: blackbone::_LDR_DDAG_NODE Struct Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

BlackBone

Windows memory hacking library

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

 All Classes Functions

Public Attributes |
List of all members

blackbone::_LDR_DDAG_NODE Struct Reference

Public Attributes

_LIST_ENTRY 	Modules

struct _LDR_SERVICE_TAG_RECORD * 	ServiceTagList

unsigned long 	LoadCount

unsigned long 	ReferenceCount

unsigned long 	DependencyCount

_SINGLE_LIST_ENTRY 	RemovalLink

void * 	IncomingDependencies

_LDR_DDAG_STATE 	State

struct _SINGLE_LIST_ENTRY 	CondenseLink

unsigned long 	PreorderNumber

unsigned long 	LowestLink

The documentation for this struct was generated from the following file:

C:/Users/Ton/Documents/Visual Studio 2013/Projects/BlackBone/src/BlackBone/Include/Win8Specific.h

blackbone

_LDR_DDAG_NODE

Generated on Tue Sep 23 2014 11:46:48 for BlackBone by

     1.8.8


text: div{blah:url(//some/absolute/path);blee:url(/*looks-like-a*/comment)}


text:
<!doctype html>
<!--
    Copyright 2014 Google Inc. All Rights Reserved.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->
<html>
<head>
  <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
  <script src="../platform/platform.js"></script>
  <link rel="import" href="../polymer/polymer.html">
  <link rel="import" href="../core-component-page/core-component-page.html">

</head>
<body unresolved>

  <core-component-page></core-component-page>

</body>
</html>


text:
package com.itto3.itimeu;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.SeekBar;

import com.itto3.itimeu.data.SharedPreferenceUtil;

public class SettingFragment extends Fragment {
    private View mSettingView;
    private Activity mSettingActivity;
    private Context mSettingContext;

    private SeekBar mworksb, mbreaksb, mlongBreaksb, msessionNumsb; //시크바
    private EditText mworket, mbreaket, mlongBreaket, msessionNumet; //에디트텍스트 뷰
    private CheckBox msoundOncb, mvibrateOncb, continuousCheckbox; //체크박스

    public static final String WORKTIME = "worktime";
    public static final String BREAKTIME = "breaktime";
    public static final String LONGBREAKTIME = "longbreaktime";
    public static final String SESSION = "session";
    public static final String SCREENON = "screen"; //boolean, 참이면 켜짐
    public static final String SOUNDON = "sound";
    public static final String VIBRATEON = "vibrate";
    public static final String CONTINUOUS_OPTION = "continuous";

    //설정 저장에 필요한 상수(이름)

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             Bundle savedInstanceState) {
        mSettingView = inflater.inflate(R.layout.fragment_setting, container, false);
        mSettingActivity = getActivity();
        mSettingContext = mSettingView.getContext();

        mworksb = mSettingView.findViewById(R.id.work_seek);
        mbreaksb = mSettingView.findViewById(R.id.break_seek);
        mlongBreaksb = mSettingView.findViewById(R.id.long_break_seek);
        msessionNumsb = mSettingView.findViewById(R.id.session_number_seek);
        /////////각 시크바

        mworket = mSettingView.findViewById(R.id.work_time);
        mbreaket = mSettingView.findViewById(R.id.break_time);
        mlongBreaket = mSettingView.findViewById(R.id.long_break_time);
        msessionNumet = mSettingView.findViewById(R.id.session_number);
        ///////각 에디트텍스트

        //각 체크박스
        msoundOncb = mSettingView.findViewById(R.id.sound_check);
        mvibrateOncb = mSettingView.findViewById(R.id.vibrate_check);
        continuousCheckbox = mSettingView.findViewById(R.id.setting_continuous_timer_check);

        //저장해둔 숫자 설정 불러오기
        mworket.setText(String.valueOf(SharedPreferenceUtil.get(getContext(), WORKTIME, 25)));
        mbreaket.setText(String.valueOf(SharedPreferenceUtil.get(getContext(), BREAKTIME, 5)));
        mlongBreaket.setText(String.valueOf(SharedPreferenceUtil.get(getContext(), LONGBREAKTIME, 20)));
        msessionNumet.setText(String.valueOf(SharedPreferenceUtil.get(getContext(), SESSION, 4)));

        final EditText[] editTexts = {mworket, mbreaket, mlongBreaket, msessionNumet};
        final SeekBar[] seekBars = {mworksb, mbreaksb, mlongBreaksb, msessionNumsb};
        final String[] constants = {WORKTIME, BREAKTIME, LONGBREAKTIME, SESSION};

        for (int i = 0; i < editTexts.length; i++) {
            final int finalI = i;
            editTexts[i].addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (s.length() > 0) {
                        seekBars[finalI].setProgress(Integer.parseInt(s.toString()));
                    } else {
                        seekBars[finalI].setProgress(1);
                        editTexts[finalI].setText("1");
                    }
                    SharedPreferenceUtil.save(getActivity(), constants[finalI],
                            Integer.parseInt(editTexts[finalI].getText().toString()));
                }
            });
        }

        //숫자-시크바 연동

        mbreaksb.setProgress(Integer.parseInt(mbreaket.getText().toString()));
        mlongBreaksb.setProgress(Integer.parseInt(mlongBreaket.getText().toString()));
        msessionNumsb.setProgress(Integer.parseInt(msessionNumet.getText().toString()));

        //체크박스 설정 불러오기
        msoundOncb.setChecked(SharedPreferenceUtil.get(getContext(), SOUNDON, true));
        mvibrateOncb.setChecked(SharedPreferenceUtil.get(getContext(), VIBRATEON, false));
        continuousCheckbox.setChecked(SharedPreferenceUtil.get(getContext(), CONTINUOUS_OPTION, false));

        mworksb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                printSelected(seekBar, progress);
            }

            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            public void onStopTrackingTouch(SeekBar seekBar) {
                doAfterTrack(seekBar);
            }
        }); //워크타임 시크바 리스너

        mbreaksb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                printSelected(seekBar, progress);
            }

            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            public void onStopTrackingTouch(SeekBar seekBar) {
                doAfterTrack(seekBar);
            }
        }); //브레이크타임 시크바 리스너

        mlongBreaksb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                printSelected(seekBar, progress);
            }

            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            public void onStopTrackingTouch(SeekBar seekBar) {
                doAfterTrack(seekBar);
            }
        }); //롱브레이크타임 시크바 리스너

        msessionNumsb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                printSelected(seekBar, progress);
            }

            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            public void onStopTrackingTouch(SeekBar seekBar) {
                doAfterTrack(seekBar);
            }
        }); //세션 수 시크바 리스너

        CheckBox[] checkboxes = {msoundOncb, mvibrateOncb, continuousCheckbox};
        for (CheckBox checkbox : checkboxes) {
            checkbox.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    saveCheckBox(buttonView, isChecked);
                }
            });
        }

        return mSettingView;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    private void printSelected(SeekBar bar, int value) { // 이용자가 바를 누르고 있을 때의 숫자 출력
        if (bar.equals(mworksb)) {
            mworket.setText(String.valueOf(value));
        } else if (bar.equals(mbreaksb)) {
            mbreaket.setText(String.valueOf(value));
        } else if (bar.equals(mlongBreaksb)) {
            mlongBreaket.setText(String.valueOf(value));
        } else if (bar.equals(msessionNumsb)) {
            msessionNumet.setText(String.valueOf(value));
        }
    }

    private void doAfterTrack(SeekBar bar) { // 이용자가 손을 뗐을 때의 숫자 출력
        int temp;

        if (bar.equals(mworksb)) {
            temp = Integer.valueOf(mworket.getText().toString());
            if (temp < 1)
                mworket.setText("1");
            else
                mworket.setText(mworket.getText());
            SharedPreferenceUtil.save(getContext(), WORKTIME, Integer.valueOf(mworket.getText().toString()));
        } else if (bar.equals(mbreaksb)) {
            temp = Integer.valueOf(mbreaket.getText().toString());
            if (temp < 1)
                mbreaket.setText("1");
            else
                mbreaket.setText(mbreaket.getText());
            SharedPreferenceUtil.save(getContext(), BREAKTIME, Integer.valueOf(mbreaket.getText().toString()));
        } else if (bar.equals(mlongBreaksb)) {
            temp = Integer.valueOf(mlongBreaket.getText().toString());
            if (temp < 1)
                mlongBreaket.setText("1");
            else
                mlongBreaket.setText(mlongBreaket.getText());
            SharedPreferenceUtil.save(getContext(), LONGBREAKTIME, Integer.valueOf(mlongBreaket.getText().toString()));
        } else if (bar.equals(msessionNumsb)) {
            temp = Integer.valueOf(msessionNumet.getText().toString());
            if (temp < 1)
                msessionNumet.setText("1");
            else
                msessionNumet.setText(msessionNumet.getText());
            SharedPreferenceUtil.save(getContext(), SESSION, Integer.valueOf(msessionNumet.getText().toString()));
        }
    }

    private void saveCheckBox(CompoundButton cbox, boolean isChecked) {
        if (cbox.equals(msoundOncb)) {
            SharedPreferenceUtil.save(getContext(), SOUNDON, isChecked);
        } else if (cbox.equals(mvibrateOncb)) {
            SharedPreferenceUtil.save(getContext(), VIBRATEON, isChecked);
        } else if (cbox.equals(continuousCheckbox)) {
            SharedPreferenceUtil.save(getContext(), CONTINUOUS_OPTION, isChecked);
        }
    }
}


text:
import { ControllerType, DecoratorMetadata, HttpMethod, NormalizedGuard } from './mix';
import { RouteHandler } from './router';

/**
 * This metadata is generated by `ROUTES_EXTENSIONS` group, and available via DI per
 * a route.
 */
export class RouteMeta {
  httpMethod: HttpMethod;
  path: string;
  controller: ControllerType;
  /**
   * The controller's method name.
   */
  methodName: string;
  /**
   * An array of DI tokens used to look up `CanActivate()` handlers,
   * in order to determine if the current user is allowed to activate the controller.
   * By default, any user can activate.
   */
  guards: NormalizedGuard[];
  /**
   * Route decorator has value of the decorator and ref to other decorators
   * on the same controller's method.
   */
  decoratorMetadata: DecoratorMetadata;
}

/**
 * This metadata is generated by extensions that sets routes.
 */
export interface PreparedRouteMeta {
  moduleName: string;
  httpMethod: HttpMethod;
  path: string;
  handle: RouteHandler;
}


text:
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int min_val = 0;
    // DFS solution
    int minDepth(TreeNode* root) {
        get_min_depth(root, 1);
        return min_val;
    }

    void get_min_depth(TreeNode* root, int depth){
        if (root == nullptr)                    return;
        if (min_val > 0 && depth >= min_val)    return;
        if (root->right)
            get_min_depth(root->right, depth + 1);
        else if (root->left)
            get_min_depth(root->left, depth + 1);
        else
            min_val = (min_val == 0 || min_val > depth) ? depth : min_val;
    }
};


text:
Asserts that the value is `false`.

```javascript
expect(false, 'to be false');
```

In case of a failing expectation you get the following output:

```javascript
expect(true, 'to be false');
```

```output
expected true to be false
```


text:
export class Crime {
    TYPE: string;
    NEIGHBOURHOOD: string;
    X: number;
    Y: number;
    YEAR: number;
    MONTH: number;
    DAY: number;
    HOUR: number;
    MINUTE: number;
    DATE: Date;

    constructor(values: any) {
        this.TYPE = values.TYPE;
        this.NEIGHBOURHOOD = values.NEIGHBOURHOOD;
        this.X = values.X;
        this.Y = values.Y;
        this.YEAR = values.YEAR;
        this.MONTH = values.MONTH;
        this.DAY = values.DAY;
        this.HOUR = values.HOUR;
        this.MINUTE = values.MINUTE;

        this.DATE = new Date(values.YEAR, values.MONTH - 1, values.DAY);
    }
}


text:
import { routes, catalogs, statusValues, publishTypesInfo, publishTypes } from 'funong-common/lib/appConstants';
import { actions as publishesActions } from 'api/publishes/ducks';

const type = publishTypes.supply;
const info = publishTypesInfo[type];
export const catalogGroups = catalogs.groupedFarm;

export default type;
export const shop = info.shop;

// page for list
export const listRoute = {
  path: routes.page_official_supplies,
  name: `page_official_${info.plural}`,
};

export const actions = publishesActions[type];

export const FORM_NAME = type;

export const EMPTY_PRODUCT = {
  category: null,
  species: null,
  name: '',
  specs: [],
  location: null,
  desc: '',
  images: [],
  labels: [],
  status: statusValues.unavailable.value,
};

export const TEST_PRODUCT = {
  category: { name: '人参果', objectId: '5859445ddc9477148f492652', catalog: { objectId: '1', name: 'aaaa', catalogType: 'adlafdjklsa' } },
  species: null,
  name: '',
  specs: [{ name: '默认', params: ['123 rfdqf'], minimum: 1, unit: '斤', price: 1 }],
  location: null,
  desc: '',
  images: [],
  labels: [],
  status: statusValues.unavailable.value,
};


text:
use gst::glib;
use gst::prelude::*;
use gst::subclass::prelude::*;
use gst_base::subclass::prelude::*;

use std::sync::Mutex;
use std::{cmp, i32, u64};

use byte_slice_cast::*;

use num_traits::cast::{FromPrimitive, ToPrimitive};
use num_traits::float::Float;

use once_cell::sync::Lazy;
static CAT: Lazy<gst::DebugCategory> = Lazy::new(|| {
    gst::DebugCategory::new(
        "rsaudioecho",
        gst::DebugColorFlags::empty(),
        Some("Rust Audio Echo Filter"),
    )
});

use super::ring_buffer::RingBuffer;

const DEFAULT_MAX_DELAY: gst::ClockTime = gst::ClockTime::SECOND;
const DEFAULT_DELAY: gst::ClockTime = gst::ClockTime::from_seconds(500);
const DEFAULT_INTENSITY: f64 = 0.5;
const DEFAULT_FEEDBACK: f64 = 0.0;

#[derive(Debug, Clone, Copy)]
struct Settings {
    pub max_delay: gst::ClockTime,
    pub delay: gst::ClockTime,
    pub intensity: f64,
    pub feedback: f64,
}

impl Default for Settings {
    fn default() -> Self {
        Settings {
            max_delay: DEFAULT_MAX_DELAY,
            delay: DEFAULT_DELAY,
            intensity: DEFAULT_INTENSITY,
            feedback: DEFAULT_FEEDBACK,
        }
    }
}

struct State {
    info: gst_audio::AudioInfo,
    buffer: RingBuffer,
}

#[derive(Default)]
pub struct AudioEcho {
    settings: Mutex<Settings>,
    state: Mutex<Option<State>>,
}

impl AudioEcho {
    fn process<F: Float + ToPrimitive + FromPrimitive>(
        data: &mut [F],
        state: &mut State,
        settings: &Settings,
    ) {
        let delay_frames = (settings.delay
            * (state.info.channels() as u64)
            * (state.info.rate() as u64))
            .seconds() as usize;

        for (i, (o, e)) in data.iter_mut().zip(state.buffer.iter(delay_frames)) {
            let inp = (*i).to_f64().unwrap();
            let out = inp + settings.intensity * e;
            *o = inp + settings.feedback * e;
            *i = FromPrimitive::from_f64(out).unwrap();
        }
    }
}

#[glib::object_subclass]
impl ObjectSubclass for AudioEcho {
    const NAME: &'static str = "RsAudioEcho";
    type Type = super::AudioEcho;
    type ParentType = gst_base::BaseTransform;
}

impl ObjectImpl for AudioEcho {
    fn properties() -> &'static [glib::ParamSpec] {
        static PROPERTIES: Lazy<Vec<glib::ParamSpec>> = Lazy::new(|| {
            vec![
                glib::ParamSpecUInt64::new("max-delay",
                    "Maximum Delay",
                    "Maximum delay of the echo in nanoseconds (can't be changed in PLAYING or PAUSED state)",
                    0, u64::MAX - 1,
                    DEFAULT_MAX_DELAY.nseconds(),
                    glib::ParamFlags::READWRITE | gst::PARAM_FLAG_MUTABLE_READY,
                ),
                glib::ParamSpecUInt64::new(
                    "delay",
                    "Delay",
                    "Delay of the echo in nanoseconds",
                    0,
                    u64::MAX - 1,
                    DEFAULT_DELAY.nseconds(),
                    glib::ParamFlags::READWRITE | gst::PARAM_FLAG_MUTABLE_PLAYING,
                ),
                glib::ParamSpecDouble::new(
                    "intensity",
                    "Intensity",
                    "Intensity of the echo",
                    0.0,
                    1.0,
                    DEFAULT_INTENSITY,
                    glib::ParamFlags::READWRITE | gst::PARAM_FLAG_MUTABLE_PLAYING,
                ),
                glib::ParamSpecDouble::new(
                    "feedback",
                    "Feedback",
                    "Amount of feedback",
                    0.0,
                    1.0,
                    DEFAULT_FEEDBACK,
                    glib::ParamFlags::READWRITE | gst::PARAM_FLAG_MUTABLE_PLAYING,
                ),
            ]
        });

        PROPERTIES.as_ref()
    }

    fn set_property(
        &self,
        _obj: &Self::Type,
        _id: usize,
        value: &glib::Value,
        pspec: &glib::ParamSpec,
    ) {
        match pspec.name() {
            "max-delay" => {
                let mut settings = self.settings.lock().unwrap();
                if self.state.lock().unwrap().is_none() {
                    settings.max_delay =
                        gst::ClockTime::from_nseconds(value.get().expect("type checked upstream"));
                }
            }
            "delay" => {
                let mut settings = self.settings.lock().unwrap();
                settings.delay =
                    gst::ClockTime::from_nseconds(value.get().expect("type checked upstream"));
            }
            "intensity" => {
                let mut settings = self.settings.lock().unwrap();
                settings.intensity = value.get().expect("type checked upstream");
            }
            "feedback" => {
                let mut settings = self.settings.lock().unwrap();
                settings.feedback = value.get().expect("type checked upstream");
            }
            _ => unimplemented!(),
        }
    }

    fn property(&self, _obj: &Self::Type, _id: usize, pspec: &glib::ParamSpec) -> glib::Value {
        match pspec.name() {
            "max-delay" => {
                let settings = self.settings.lock().unwrap();
                settings.max_delay.to_value()
            }
            "delay" => {
                let settings = self.settings.lock().unwrap();
                settings.delay.to_value()
            }
            "intensity" => {
                let settings = self.settings.lock().unwrap();
                settings.intensity.to_value()
            }
            "feedback" => {
                let settings = self.settings.lock().unwrap();
                settings.feedback.to_value()
            }
            _ => unimplemented!(),
        }
    }
}

impl GstObjectImpl for AudioEcho {}

impl ElementImpl for AudioEcho {
    fn metadata() -> Option<&'static gst::subclass::ElementMetadata> {
        static ELEMENT_METADATA: Lazy<gst::subclass::ElementMetadata> = Lazy::new(|| {
            gst::subclass::ElementMetadata::new(
                "Audio echo",
                "Filter/Effect/Audio",
                "Adds an echo or reverb effect to an audio stream",
                "Sebastian Dröge <sebastian@centricular.com>",
            )
        });

        Some(&*ELEMENT_METADATA)
    }

    fn pad_templates() -> &'static [gst::PadTemplate] {
        static PAD_TEMPLATES: Lazy<Vec<gst::PadTemplate>> = Lazy::new(|| {
            let caps = gst::Caps::builder("audio/x-raw")
                .field(
                    "format",
                    gst::List::new([
                        gst_audio::AUDIO_FORMAT_F32.to_str(),
                        gst_audio::AUDIO_FORMAT_F64.to_str(),
                    ]),
                )
                .field("rate", gst::IntRange::new(0, i32::MAX))
                .field("channels", gst::IntRange::new(0, i32::MAX))
                .field("layout", "interleaved")
                .build();
            let src_pad_template = gst::PadTemplate::new(
                "src",
                gst::PadDirection::Src,
                gst::PadPresence::Always,
                &caps,
            )
            .unwrap();

            let sink_pad_template = gst::PadTemplate::new(
                "sink",
                gst::PadDirection::Sink,
                gst::PadPresence::Always,
                &caps,
            )
            .unwrap();
            vec![src_pad_template, sink_pad_template]
        });

        PAD_TEMPLATES.as_ref()
    }
}

impl BaseTransformImpl for AudioEcho {
    const MODE: gst_base::subclass::BaseTransformMode =
        gst_base::subclass::BaseTransformMode::AlwaysInPlace;
    const PASSTHROUGH_ON_SAME_CAPS: bool = false;
    const TRANSFORM_IP_ON_PASSTHROUGH: bool = false;

    fn transform_ip(
        &self,
        _element: &Self::Type,
        buf: &mut gst::BufferRef,
    ) -> Result<gst::FlowSuccess, gst::FlowError> {
        let mut settings = *self.settings.lock().unwrap();
        settings.delay = cmp::min(settings.max_delay, settings.delay);

        let mut state_guard = self.state.lock().unwrap();
        let state = state_guard.as_mut().ok_or(gst::FlowError::NotNegotiated)?;

        let mut map = buf.map_writable().map_err(|_| gst::FlowError::Error)?;

        match state.info.format() {
            gst_audio::AUDIO_FORMAT_F64 => {
                let data = map.as_mut_slice_of::<f64>().unwrap();
                Self::process(data, state, &settings);
            }
            gst_audio::AUDIO_FORMAT_F32 => {
                let data = map.as_mut_slice_of::<f32>().unwrap();
                Self::process(data, state, &settings);
            }
            _ => return Err(gst::FlowError::NotNegotiated),
        }

        Ok(gst::FlowSuccess::Ok)
    }

    fn set_caps(
        &self,
        _element: &Self::Type,
        incaps: &gst::Caps,
        outcaps: &gst::Caps,
    ) -> Result<(), gst::LoggableError> {
        if incaps != outcaps {
            return Err(gst::loggable_error!(
                CAT,
                "Input and output caps are not the same"
            ));
        }

        let info = gst_audio::AudioInfo::from_caps(incaps)
            .map_err(|_| gst::loggable_error!(CAT, "Failed to parse input caps"))?;
        let max_delay = self.settings.lock().unwrap().max_delay;
        let size = (max_delay * (info.rate() as u64)).seconds() as usize;
        let buffer_size = size * (info.channels() as usize);

        *self.state.lock().unwrap() = Some(State {
            info,
            buffer: RingBuffer::new(buffer_size),
        });

        Ok(())
    }

    fn stop(&self, _element: &Self::Type) -> Result<(), gst::ErrorMessage> {
        // Drop state
        let _ = self.state.lock().unwrap().take();

        Ok(())
    }
}


text:
<?php

namespace Application\Niagara\MainBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class MainBundle extends Bundle
{
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2008 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:id="@+id/PHONE_MENU">
        <item android:id="@+id/dial_context_menu_id"
            android:title="@string/contextmenu_dial_dot"/>
        <item android:id="@+id/add_contact_context_menu_id"
            android:title="@string/contextmenu_add_contact"/>
        <item android:id="@+id/copy_phone_context_menu_id"
            android:title="@string/contextmenu_copy"/>
    </group>
    <group android:id="@+id/EMAIL_MENU">
        <item android:id="@+id/email_context_menu_id"
            android:title="@string/contextmenu_send_mail"/>
        <item android:id="@+id/copy_mail_context_menu_id"
            android:title="@string/contextmenu_copy"/>
    </group>
    <group android:id="@+id/GEO_MENU">
        <item android:id="@+id/map_context_menu_id"
            android:title="@string/contextmenu_map"/>
        <item android:id="@+id/copy_geo_context_menu_id"
            android:title="@string/contextmenu_copy"/>
    </group>
    <group android:id="@+id/ANCHOR_MENU">
        <item android:id="@+id/open_context_menu_id"
            android:title="@string/contextmenu_openlink"/>
        <item android:id="@+id/open_newtab_context_menu_id"
            android:title="@string/contextmenu_openlink_newwindow"/>
        <item android:id="@+id/open_newtab_incognito_context_menu_id"
            android:title="@string/contextmenu_openlink_incognito_newwindow"/>
        <item android:id="@+id/save_link_context_menu_id"
            android:title="@string/contextmenu_savelink"/>
        <item android:id="@+id/copy_link_context_menu_id"
            android:title="@string/contextmenu_copylink"/>
    </group>
    <group android:id="@+id/IMAGE_MENU">
        <item android:id="@+id/download_context_menu_id"
            android:title="@string/contextmenu_download_image"/>
        <item android:id="@+id/view_image_context_menu_id"
            android:title="@string/contextmenu_view_image"/>
        <item android:id="@+id/set_wallpaper_context_menu_id"
            android:title="@string/contextmenu_set_wallpaper"/>
        <item android:id="@+id/share_link_context_menu_id"
            android:title="@string/contextmenu_sharelink"/>
    </group>
    <group android:id="@+id/SELECT_TEXT_MENU">
        <item android:id="@+id/select_text_menu_id"
            android:title="@string/select_dot"/>
    </group>
</menu>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
ResultSetWrapper (Hibernate JavaDocs)
</TITLE>

<META NAME="date" CONTENT="2013-10-23">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.hibernate.engine.jdbc.spi

Interface ResultSetWrapper

All Known Implementing Classes:
ResultSetWrapperImpl

public interface ResultSetWrapper

Contract for wrapping a ResultSet in a "column name cache" wrapper.

Method Summary

 ResultSet
wrap(ResultSet resultSet,
     ColumnNameCache columnNameCache)

          Wrap a result set in a "column name cache" wrapper.

Method Detail

wrap

ResultSet wrap(ResultSet resultSet,
               ColumnNameCache columnNameCache)

Wrap a result set in a "column name cache" wrapper.

Parameters:
resultSet - The result set to wrap
columnNameCache - The column name cache.

Returns:
The wrapped result set.

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2001-2013 Red Hat, Inc.  All Rights Reserved.


text:
namespace std {
#if 0
    // Types T1, T2, ... are unspecified implementation types
    T1 resetiosflags(ios_base::fmtflags mask);
    T2 setiosflags (ios_base::fmtflags mask);
    T3 setbase(int base);
    template<charT> T4 setfill(charT c);
    T5 setprecision(int n);
    T6 setw(int n);
#endif
}


text:
@extends('site.layouts.default')

{{-- Web site Title --}}
@section('title')
{{{ String::title($note->title) }}} ::
@parent
@stop

{{-- Update the Meta Title --}}
@section('meta_title')
@parent

@stop

{{-- Update the Meta Description --}}
@section('meta_description')
<meta name="description" content="{{{ $note->meta_description() }}}" />

@stop

{{-- Update the Meta Keywords --}}
@section('meta_keywords')
<meta name="keywords" content="{{{ $note->meta_keywords() }}}" />

@stop

@section('meta_author')
<meta name="author" content="{{{ $note->author->username }}}" />
@stop

{{-- Content --}}
@section('content')

{{ $note->title }}

{{ $note->content() }}

	Posted {{{ $note->date() }}}

{{ $comments->count() }} {{ \Illuminate\Support\Pluralizer::plural('Comment', $comments->count()) }}

@if ($comments->count())
@foreach ($comments as $comment)

				{{{ $comment->author->username }}}
				•
				{{{ $comment->date() }}}

				{{ nl2br(e($comment->content())) }}

@endforeach
@else

@endif

@include('notes.partials.comment_form')

@stop


text:
import os

import testtools

from saharaclient.tests.integration.configs import config as cfg
import saharaclient.tests.integration.tests.full_test_driver as driver

cfg = cfg.ITConfig()
vanilla = cfg.vanilla2_config

class ClusterVanilla2(driver.FullTestDriver):

    @testtools.skipIf(vanilla.SKIP_ALL_TESTS_FOR_PLUGIN,
                      'All tests for Vanilla2 plugin were skipped')
    def test_cluster_vanilla(self):
        marker = str(os.getpid())
        ng_templates = [
            {
                "values": {
                    "name": "m-nr-%s" % marker,
                    "flavor_id": "2",
                    "plugin_name": vanilla.PLUGIN_NAME,
                    "hadoop_version": vanilla.HADOOP_VERSION,
                    "node_processes": ["namenode", "resourcemanager"],
                    "floating_ip_pool": self.floating_ip_pool
                },
                "count": 1
            },
            {
                "values": {
                    "name": "m-oh-%s" % marker,
                    "flavor_id": "2",
                    "plugin_name": vanilla.PLUGIN_NAME,
                    "hadoop_version": vanilla.HADOOP_VERSION,
                    "node_processes": ["oozie", "historyserver"],
                    "floating_ip_pool": self.floating_ip_pool
                },
                "count": 1,
            },
            {
                "values": {
                    "name": "w-%s" % marker,
                    "flavor_id": "2",
                    "plugin_name": vanilla.PLUGIN_NAME,
                    "hadoop_version": vanilla.HADOOP_VERSION,
                    "node_processes": ["nodemanager", "datanode"],
                    "floating_ip_pool": self.floating_ip_pool
                },
                "count": 2
            }
        ]
        self.drive_full_test(vanilla, ng_templates)


text:
<component name="libraryTable">
  <library name="model-lib">
    <CLASSES>
      <root url="file://$PROJECT_DIR$/model/lib" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
    <jarDirectory url="file://$PROJECT_DIR$/model/lib" recursive="false" />
  </library>
</component>


text:
<?php namespace App\Interfaces;

interface ChampionRepositoryInterface
{
    public function get($id);
    public function all();
}


text: AddModalOtherInput.js


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
function abrirDivCurtirPagina() {
    $('#divPaginaCurtida01').hide();
    $('#divCurtirPagina01').fadeIn("slow");
    top.idCurtidas = "";
}

function abrirDivDescurtirPagina(json) {
    $('#divCurtirPagina01').hide();
    $('#divPaginaCurtida01').fadeIn("slow");
    top.idCurtidas = json.idCurtidas;
}

function verificarCurtidas() {
    var url = top.basePath + '/curtidas/index/verificar-curtidas';
    $.ajax({
        type: "POST",
        url: url,
        data: {
            idCliente: top.idCliente
        },
        dataType: "json",
        success: function (data) {
            if (data.tipoMsg === "S") {
                if (data.idCurtidas !== undefined) {
                    abrirDivDescurtirPagina(data);
                } else {
                    abrirDivCurtirPagina();
                }
            }
        }
    });
}

function curtirPagina() {
    var url = top.basePath + '/curtidas/index/curtir-pagina';
    $.ajax({
        type: "POST",
        url: url,
        data: {
            idCliente: top.idCliente
        },
        dataType: "json",
        success: function (data) {
            if (data.tipoMsg === "S") {
                abrirDivDescurtirPagina(data);
                $('#spanVoce').html('Você e ');
            }
        }
    });
}

function descurtirPagina() {
    var url = top.basePath + '/curtidas/index/descurtir-pagina';
    $.ajax({
        type: "POST",
        url: url,
        data: {
            idCurtidas: top.idCurtidas
        },
        dataType: "json",
        success: function (data) {
            if (data.tipoMsg === "S") {
                abrirDivCurtirPagina();
                $('#spanVoce').html('');
            }
        }
    });
}

$(document).ready(function () {

    $('#btnCurtirPagina01').on('click', function () {
        curtirPagina();
    });
    $('#btnCurtirLogado').on('click', function () {
        curtirPagina();
    });
    $('#btnDescurtirLogado').on('click', function () {
        descurtirPagina();
    });
    verificarCurtidas();

});


text:
require 'Blockchain'
require_relative '../lib/blockchain/pushtx'
require 'test/unit'

class TestPushTx < Test::Unit::TestCase

    def test_push_tx_nil_param_api_exception
        assert_raise Blockchain::Client::APIException do Blockchain::PushTx.new.pushtx(nil) end
    end

end


text:
// ***********************************************************************
// Copyright (c) 2011 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************

using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Xml;
using NUnit.Common;
using NUnit.Framework.Api;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;

namespace NUnitLite
{
    /// <summary>
    /// NUnit3XmlOutputWriter is responsible for writing the results
    /// of a test to a file in NUnit 3 format.
    /// </summary>
    public class NUnit3XmlOutputWriter : OutputWriter
    {
        /// <summary>
        /// Writes test info to the specified TextWriter
        /// </summary>
        /// <param name="test">The test to be written</param>
        /// <param name="writer">A TextWriter to which the test info is written</param>
        public override void WriteTestFile(ITest test, TextWriter writer)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;

            using (XmlWriter xmlWriter = XmlWriter.Create(writer, settings))
            {
                test.ToXml(true).WriteTo(xmlWriter);
            }
        }

        /// <summary>
        /// Writes the test result to the specified TextWriter
        /// </summary>
        /// <param name="result">The result to be written to a file</param>
        /// <param name="writer">A TextWriter to which the result is written</param>
        /// <param name="runSettings"></param>
        /// <param name="filter"></param>
        public override void WriteResultFile(ITestResult result, TextWriter writer, IDictionary<string, object> runSettings, TestFilter filter)
        {
            XmlWriterSettings xmlSettings = new XmlWriterSettings();
            xmlSettings.Indent = true;

            using (XmlWriter xmlWriter = XmlWriter.Create(writer, xmlSettings))
            {
                WriteXmlResultOutput(result, xmlWriter, runSettings, filter);
            }
        }

        private void WriteXmlResultOutput(ITestResult result, XmlWriter xmlWriter, IDictionary<string, object> runSettings, TestFilter filter)
        {
            TNode resultNode = result.ToXml(true);

            // Insert elements as first child in reverse order
            if (runSettings != null) // Some platforms don't have settings
                FrameworkController.InsertSettingsElement(resultNode, runSettings);
            FrameworkController.InsertEnvironmentElement(resultNode);

            TNode testRun = MakeTestRunElement(result);

#if !NETSTANDARD1_6
            testRun.ChildNodes.Add(MakeCommandLineElement());
#endif
            testRun.ChildNodes.Add(MakeTestFilterElement(filter));
            testRun.ChildNodes.Add(resultNode);

            testRun.WriteTo(xmlWriter);
        }

        private TNode MakeTestRunElement(ITestResult result)
        {
            TNode testRun = new TNode("test-run");

            testRun.AddAttribute("id", "2");
            testRun.AddAttribute("name", result.Name);
            testRun.AddAttribute("fullname", result.FullName);
            testRun.AddAttribute("testcasecount", result.Test.TestCaseCount.ToString());

            testRun.AddAttribute("result", result.ResultState.Status.ToString());
            if (result.ResultState.Label != string.Empty)
                testRun.AddAttribute("label", result.ResultState.Label);

            testRun.AddAttribute("start-time", result.StartTime.ToString("u"));
            testRun.AddAttribute("end-time", result.EndTime.ToString("u"));
            testRun.AddAttribute("duration", result.Duration.ToString("0.000000", NumberFormatInfo.InvariantInfo));

            testRun.AddAttribute("total", (result.PassCount + result.FailCount + result.SkipCount + result.InconclusiveCount).ToString());
            testRun.AddAttribute("passed", result.PassCount.ToString());
            testRun.AddAttribute("failed", result.FailCount.ToString());
            testRun.AddAttribute("inconclusive", result.InconclusiveCount.ToString());
            testRun.AddAttribute("skipped", result.SkipCount.ToString());
            testRun.AddAttribute("asserts", result.AssertCount.ToString());

            testRun.AddAttribute("random-seed", Randomizer.InitialSeed.ToString());

            // NOTE: The console runner adds attributes for engine-version and clr-version
            // Neither of these is needed under nunitlite since there is no engine involved
            // and we are running under the same runtime as the tests.

            return testRun;
        }

#if !NETSTANDARD1_6
        private static TNode MakeCommandLineElement()
        {
            return new TNode("command-line", Environment.CommandLine, true);
        }
#endif

        private static TNode MakeTestFilterElement(TestFilter filter)
        {
            TNode result = new TNode("filter");
            if (!filter.IsEmpty)
                filter.AddToXml(result, true);
            return result;
        }
    }
}


text:
"""Implements CKY parsing using a Trie data structure to index rules.

This implementation supports non-binarized grammars with rules containing
up to 2 non-terminals.

For each span, rather than enumerating every possible sub-span for up to
2 non-terminals, the algorithm iterates across the span left-to-right and
attempts to match rules stored in a Trie.
"""

import collections

from language.compgen.nqg.common.cky import cfg_rule

class TrieNode(object):
  """Represents a node in a generic Trie data structure."""

  def __init__(self, symbol=None):
    # The individual symbol associated with this node.
    self.symbol = symbol  # Can only be None for root.
    # Map from symbol to TrieNode.
    self.symbol_to_child = {}
    # A set of arbitrarily-typed values associated with this node.
    self.values = []

  def maybe_add_child(self, symbol):
    """Adds a new node for a given child symbol if not already in Trie."""
    if symbol in self.symbol_to_child:
      return self.symbol_to_child[symbol]
    else:
      node = TrieNode(symbol)
      self.symbol_to_child[symbol] = node
      return node

  def maybe_get_child(self, symbol):
    return self.symbol_to_child.get(symbol)

  def __str__(self):
    return "%s %s" % (self.symbol, set(self.symbol_to_child.keys()))

  def __repr__(self):
    return str(self)

def print_trie(trie_node, indent=0):
  """Recursively prints Trie for debugging purposes."""
  print("%s %s" % ("-" * indent, trie_node.symbol))
  for value in trie_node.values:
    print("%s value: %s" % ("-" * indent, value))
  for child in trie_node.symbol_to_child.values():
    print_trie(child, indent=indent + 1)

def add_rule_to_trie(trie_root, rule):
  current_node = trie_root
  for symbol in rule.rhs:
    current_node = current_node.maybe_add_child(symbol)
  current_node.values.append(rule)

class Chart(object):
  """Represents parse chart state."""

  def __init__(self, populate_fn, postprocess_fn):
    # The key_map stores chart entries (of type T) indexed by:
    # (span_begin, span_end, nonterminal)
    self.key_map = collections.defaultdict(list)
    # For optimization purposes, we also index chart entries by their
    # span_begin index only in start_map.
    # Key is span_begin and value is List of (span_end, nonterminal).
    self.start_map = collections.defaultdict(set)
    # See `cfg_parser.py` for definitions of populate_fn and postprocess_fn.
    self.populate_fn = populate_fn
    self.postprocess_fn = postprocess_fn

  def add(self, span_begin, span_end, rule, children):
    """Add an entry to the chart."""
    entry = self.populate_fn(span_begin, span_end, rule, children)
    nonterminal = rule.lhs
    self.key_map[(span_begin, span_end, nonterminal)].append(entry)
    self.start_map[span_begin].add((span_end, nonterminal))

  def get_from_key(self, span_begin, span_end, nonterminal):
    """Get entries based on full key."""
    return self.key_map[(span_begin, span_end, nonterminal)]

  def get_from_start(self, span_begin):
    """Get entries based on start index only."""
    return self.start_map[span_begin]

  def postprocess(self, span_begin, span_end, nonterminal):
    """Apply postpostprocess_fn to a chart cell."""
    if self.postprocess_fn:
      self.key_map[(span_begin, span_end, nonterminal)] = self.postprocess_fn(
          self.key_map[(span_begin, span_end, nonterminal)])

# For a given span, SearchState represents a potential match with a ParserRule.
SearchState = collections.namedtuple(
    "SearchState",
    [
        "anchored_nonterminals",  # List of (span_begin, span_end, nonterminal).
        "trie_node",  # TrieNode.
    ])

# The maximum number of RHS non-terminals in ParserRules that are supported.
MAX_NONTERMINALS = 2

def parse(input_ids,
          rules,
          nonterminals,
          start_idx,
          populate_fn,
          postprocess_fn,
          verbose=False):
  """Run bottom up parser using Trie-based implementation."""
  input_len = len(input_ids)
  input_symbols = tuple(
      [cfg_rule.CFGSymbol(idx, cfg_rule.TERMINAL) for idx in input_ids])

  # Initialize the empty chart.
  chart = Chart(populate_fn, postprocess_fn)

  # Initialize Trie of rules.
  trie_root = TrieNode()
  for rule in rules:
    add_rule_to_trie(trie_root, rule)

  # Populate the chart.
  for span_end in range(1, input_len + 1):
    for span_begin in range(span_end - 1, -1, -1):

      # Map of span_begin to List of SearchState.
      search_map = collections.defaultdict(list)
      search_map[span_begin].append(SearchState([], trie_root))

      # Iterate across every input token in the span range to find rule matches.
      for idx in range(span_begin, span_end):

        # End early if there are no remaining candidate matches.
        if not search_map[idx]:
          continue

        terminal_symbol = input_symbols[idx]

        # Iterate through partial matches.
        while search_map[idx]:
          search_state = search_map[idx].pop()

          # Consider matching terminal.
          new_trie_node = search_state.trie_node.maybe_get_child(
              terminal_symbol)
          if new_trie_node:
            # Found a match for the terminal in the Trie.
            # Add a partial match to search_map with idx incremented by 1 token.
            new_search_state = SearchState(search_state.anchored_nonterminals,
                                           new_trie_node)
            search_map[idx + 1].append(new_search_state)

          # Consider matching non-terminal.
          nonterminal_tuples = chart.get_from_start(idx)
          if len(search_state.anchored_nonterminals) < MAX_NONTERMINALS:
            # Iterate through lower chart entries with a completed sub-tree
            # that starts at the current index.
            for nt_end, nonterminal in nonterminal_tuples:
              nonterminal_symbol = cfg_rule.CFGSymbol(nonterminal,
                                                      cfg_rule.NON_TERMINAL)
              new_trie_node = search_state.trie_node.maybe_get_child(
                  nonterminal_symbol)
              if new_trie_node:
                # Found a match for the non-terminal in the Trie.
                # Add a partial match to search_map with idx set to the end
                # of the sub-tree span.
                new_anchored_nonterminals = search_state.anchored_nonterminals[:]
                new_anchored_nonterminals.append((idx, nt_end, nonterminal))
                search_map[nt_end].append(
                    SearchState(new_anchored_nonterminals, new_trie_node))

      # Loop through search_map for completed matches at span_end.
      for search_state in search_map[span_end]:
        # Get the ParserRule(s) associated with the particular Trie path.
        matched_rules = search_state.trie_node.values
        if not matched_rules:
          continue

        for rule in matched_rules:
          # Given the ParserRule and anchored nonterminal positions, generate
          # new chart entries and add chart.
          if len(search_state.anchored_nonterminals) == 1:
            # Matched rule contains 1 non-terminal.
            for child in chart.get_from_key(
                *search_state.anchored_nonterminals[0]):
              chart.add(span_begin, span_end, rule, [child])
          elif len(search_state.anchored_nonterminals) == 2:
            # Matched rule contains 2 non-terminals.
            for child_0 in chart.get_from_key(
                *search_state.anchored_nonterminals[0]):
              for child_1 in chart.get_from_key(
                  *search_state.anchored_nonterminals[1]):
                chart.add(span_begin, span_end, rule, [child_0, child_1])
          elif len(search_state.anchored_nonterminals) > 2:
            raise ValueError
          else:
            # Matched rule contains 0 non-terminals.
            chart.add(span_begin, span_end, rule, [])

      for nt in nonterminals:
        chart.postprocess(span_begin, span_end, nt)

      if verbose:
        for nt in nonterminals:
          cell = chart.get_from_key(span_begin, span_end, nt)
          if cell:
            print("Populated (%s,%s): %s - %s" %
                  (span_begin, span_end, nt, cell))

  # Return completed parses.
  return chart.get_from_key(0, input_len, start_idx)


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

import com.intellij.openapi.application.ApplicationManager;

import com.intellij.openapi.vcs.VcsException;
import net.groboclown.idea.p4ic.P4Bundle;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * A Vcs specific version of a {@link java.util.concurrent.Future} class.
 * It doesn't directly implement Future, so that it can have
 * the better throwable clauses.
 *
 * @param <T>
 */
public class VcsSettableFuture<T> implements VcsFuture<T>, VcsFutureSetter<T> {
    // Only one of these futures can be the "getter" at a time.
    // That's fine, because the EDT is only one thread.
    private static final Object SYNC = new Object();
    private static VcsSettableFuture<?> EDT_GETTER;

    private final List<Runnable> listeners = new ArrayList<Runnable>();
    private final BlockingQueue<Event<?>> events = new LinkedBlockingDeque<Event<?>>();
    private volatile boolean done;
    private volatile Throwable ex;
    private volatile T value;
    private volatile boolean cancelled;

    public static <T> VcsSettableFuture<T> create() {
        return new VcsSettableFuture<T>();
    }

    private VcsSettableFuture() {}

    @Override
    public void runInEdt(@NotNull Runnable runner) {
        if (ApplicationManager.getApplication().isDispatchThread()) {
            runner.run();
        } else {
            synchronized (SYNC) {
                if (EDT_GETTER == null) {
                    // no "get" waiting in the EDT thread
                    ApplicationManager.getApplication().invokeLater(runner);
                } else {
                    // don't know, and don't care, about the EDT_GETTER value type.
                    EDT_GETTER.events.add(new Event<Void>(null, null, false, runner));
                }
            }
        }
    }

    public void addListener(@NotNull Runnable runnable) {
        listeners.add(runnable);
    }

    @Override
    public void set(T value) {
        done = true;
        this.value = value;
        events.add(new Event<T>(value, null, false, null));
    }

    @Override
    public void setException(@NotNull Throwable t) {
        done = true;
        ex = t;
        events.add(new Event<T>(null, t, false, null));
    }

    @Override
    public boolean cancel(boolean mayInterruptIfRunning) {
        done = true;
        cancelled = true;
        events.add(new Event<T>(null, null, true, null));
        return false;
    }

    @Override
    public boolean isCancelled() {
        return cancelled;
    }

    @Override
    public boolean isDone() {
        return done;
    }

    @Override
    public T get() throws VcsException, CancellationException {
        return get(-1, TimeUnit.MILLISECONDS);
    }

    @Override
    public T get(long timeout, @NotNull TimeUnit unit) throws VcsException, CancellationException {
        boolean isEdtGetter = false;
        if (ApplicationManager.getApplication().isDispatchThread()) {
            synchronized (SYNC) {
                if (EDT_GETTER == null) {
                    // we are now the EDT_GETTER
                    EDT_GETTER = this;
                    isEdtGetter = true;
                } else {
                    throw new VcsException(P4Bundle.message("error.edt.double-call"));
                }
            }
        }
        try {
            long now = System.currentTimeMillis();
            long endTime = now + unit.toMillis(timeout);
            if (timeout < 0) {
                endTime = Long.MAX_VALUE - now - 1;
            }
            while (!done && (timeout < 0 || endTime < now)) {
                long waitTime = endTime - now;
                try {
                    Event ev = events.poll(waitTime, TimeUnit.MILLISECONDS);
                    if (ev != null && ev.edtAction != null) {
                        ev.edtAction.run();
                    }
                } catch (InterruptedException e) {
                    cancelled = true;
                    done = true;
                    ex = e;
                }
                now = System.currentTimeMillis();
            }
            if (done) {
                for (Runnable listener : listeners) {
                    listener.run();
                }
            }
            if (ex != null) {
                if (ex instanceof InterruptedException) {
                    ex.printStackTrace();
                    CancellationException ce = new CancellationException(ex.getMessage());
                    ce.initCause(ex);
                    throw ce;
                }
                if (ex instanceof CancellationException) {
                    throw (CancellationException) ex;
                }
                if (ex instanceof VcsException) {
                    throw (VcsException) ex;
                }
                throw new VcsException(ex);
            }
            if (cancelled) {
                throw new CancellationException(P4Bundle.message("error.cancelled-task"));
            }
            return value;
        } finally {
            if (isEdtGetter) {
                synchronized (SYNC) {
                    EDT_GETTER = null;
                }
            }
        }
    }

    /**
     * Immediately gets the value for the future.  If the future isn't
     * ready yet, it cancels the future and throws a CancellationException.
     *
     * @return the value set to the future.
     * @throws com.intellij.openapi.vcs.VcsException
     * @throws java.util.concurrent.CancellationException
     */
    @Override
    public T getImmediately() throws VcsException, CancellationException {
        if (!isDone()) {
            cancel(true);
            throw new CancellationException(P4Bundle.message("error.cancelled-timeout"));
        }
        if (isCancelled()) {
            throw new CancellationException(P4Bundle.message("error.cancelled-task"));
        }
        return get();
    }

    protected void executeRunner(@NotNull Runnable runner) {
        events.add(new Event<T>(null, null, false, runner));
    }

    private static class Event<T> {
        public final T value;
        public final Throwable ex;
        public final boolean cancelled;
        public final Runnable edtAction;

        private Event(T value, Throwable ex, boolean cancelled, Runnable edtAction) {
            this.value = value;
            this.ex = ex;
            this.cancelled = cancelled;
            this.edtAction = edtAction;
        }
    }
}


text:
package org.gradle.internal.nativeintegration.filesystem.services;

import io.rubygrapefruit.platform.PosixFiles;
import org.gradle.internal.nativeintegration.filesystem.FileModeAccessor;

import java.io.File;
import java.io.IOException;

class NativePlatformBackedStat implements FileModeAccessor {
    private final PosixFiles posixFiles;

    public NativePlatformBackedStat(PosixFiles posixFiles) {
        this.posixFiles = posixFiles;
    }

    public int getUnixMode(File f) throws IOException {
        return posixFiles.getMode(f);
    }
}


text:
#include <zephyr/drivers/can.h>
#include <zephyr/kernel.h>
#include <zephyr/sys/util.h>
#include <zephyr/logging/log.h>

LOG_MODULE_REGISTER(can_common, CONFIG_CAN_LOG_LEVEL);

/* Maximum acceptable deviation in sample point location (permille) */
#define SAMPLE_POINT_MARGIN 50

/* CAN sync segment is always one time quantum */
#define CAN_SYNC_SEG 1

struct can_tx_default_cb_ctx {
	struct k_sem done;
	int status;
};

static void can_tx_default_cb(const struct device *dev, int error, void *user_data)
{
	struct can_tx_default_cb_ctx *ctx = user_data;

	ctx->status = error;
	k_sem_give(&ctx->done);
}

int z_impl_can_send(const struct device *dev, const struct can_frame *frame,
		    k_timeout_t timeout, can_tx_callback_t callback,
		    void *user_data)
{
	const struct can_driver_api *api = (const struct can_driver_api *)dev->api;

	if (callback == NULL) {
		struct can_tx_default_cb_ctx ctx;
		int err;

		k_sem_init(&ctx.done, 0, 1);

		err = api->send(dev, frame, timeout, can_tx_default_cb, &ctx);
		if (err != 0) {
			return err;
		}

		k_sem_take(&ctx.done, K_FOREVER);

		return ctx.status;
	}

	return api->send(dev, frame, timeout, callback, user_data);
}

static void can_msgq_put(const struct device *dev, struct can_frame *frame, void *user_data)
{
	struct k_msgq *msgq = (struct k_msgq *)user_data;
	int ret;

	ARG_UNUSED(dev);

	__ASSERT_NO_MSG(msgq);

	ret = k_msgq_put(msgq, frame, K_NO_WAIT);
	if (ret) {
		LOG_ERR("Msgq %p overflowed. Frame ID: 0x%x", msgq, frame->id);
	}
}

int z_impl_can_add_rx_filter_msgq(const struct device *dev, struct k_msgq *msgq,
				  const struct can_filter *filter)
{
	const struct can_driver_api *api = dev->api;

	return api->add_rx_filter(dev, can_msgq_put, msgq, filter);
}

static int update_sampling_pnt(uint32_t ts, uint32_t sp, struct can_timing *res,
			       const struct can_timing *max,
			       const struct can_timing *min)
{
	uint16_t ts1_max = max->phase_seg1 + max->prop_seg;
	uint16_t ts1_min = min->phase_seg1 + min->prop_seg;
	uint32_t sp_calc;
	uint16_t ts1, ts2;

	ts2 = ts - (ts * sp) / 1000;
	ts2 = CLAMP(ts2, min->phase_seg2, max->phase_seg2);
	ts1 = ts - CAN_SYNC_SEG - ts2;

	if (ts1 > ts1_max) {
		ts1 = ts1_max;
		ts2 = ts - CAN_SYNC_SEG - ts1;
		if (ts2 > max->phase_seg2) {
			return -1;
		}
	} else if (ts1 < ts1_min) {
		ts1 = ts1_min;
		ts2 = ts - ts1;
		if (ts2 < min->phase_seg2) {
			return -1;
		}
	}

	res->prop_seg = CLAMP(ts1 / 2, min->prop_seg, max->prop_seg);
	res->phase_seg1 = ts1 - res->prop_seg;
	res->phase_seg2 = ts2;

	sp_calc = (CAN_SYNC_SEG + ts1) * 1000 / ts;

	return sp_calc > sp ? sp_calc - sp : sp - sp_calc;
}

/* Internal function to do the actual calculation */
static int can_calc_timing_int(uint32_t core_clock, struct can_timing *res,
			       const struct can_timing *min,
			       const struct can_timing *max,
			       uint32_t bitrate, uint16_t sp)
{
	uint32_t ts = max->prop_seg + max->phase_seg1 + max->phase_seg2 +
		   CAN_SYNC_SEG;
	uint16_t sp_err_min = UINT16_MAX;
	int sp_err;
	struct can_timing tmp_res;

	if (bitrate == 0 || sp >= 1000) {
		return -EINVAL;
	}

	for (int prescaler = MAX(core_clock / (ts * bitrate), 1);
	     prescaler <= max->prescaler; ++prescaler) {
		if (core_clock % (prescaler * bitrate)) {
			/* No integer ts */
			continue;
		}

		ts = core_clock / (prescaler * bitrate);

		sp_err = update_sampling_pnt(ts, sp, &tmp_res,
					     max, min);
		if (sp_err < 0) {
			/* No prop_seg, seg1, seg2 combination possible */
			continue;
		}

		if (sp_err < sp_err_min) {
			sp_err_min = sp_err;
			res->prop_seg = tmp_res.prop_seg;
			res->phase_seg1 = tmp_res.phase_seg1;
			res->phase_seg2 = tmp_res.phase_seg2;
			res->prescaler = (uint16_t)prescaler;
			if (sp_err == 0) {
				/* No better result than a perfect match*/
				break;
			}
		}
	}

	if (sp_err_min) {
		LOG_DBG("SP error: %d 1/1000", sp_err_min);
	}

	return sp_err_min == UINT16_MAX ? -ENOTSUP : (int)sp_err_min;
}

int z_impl_can_calc_timing(const struct device *dev, struct can_timing *res,
			   uint32_t bitrate, uint16_t sample_pnt)
{
	const struct can_timing *min = can_get_timing_min(dev);
	const struct can_timing *max = can_get_timing_max(dev);
	uint32_t core_clock;
	int ret;

	if (bitrate > 1000000) {
		return -EINVAL;
	}

	ret = can_get_core_clock(dev, &core_clock);
	if (ret != 0) {
		return ret;
	}

	return can_calc_timing_int(core_clock, res, min, max, bitrate, sample_pnt);
}

#ifdef CONFIG_CAN_FD_MODE
int z_impl_can_calc_timing_data(const struct device *dev, struct can_timing *res,
				uint32_t bitrate, uint16_t sample_pnt)
{
	const struct can_timing *min = can_get_timing_data_min(dev);
	const struct can_timing *max = can_get_timing_data_max(dev);
	uint32_t core_clock;
	int ret;

	if (bitrate > 8000000) {
		return -EINVAL;
	}

	ret = can_get_core_clock(dev, &core_clock);
	if (ret != 0) {
		return ret;
	}

	return can_calc_timing_int(core_clock, res, min, max, bitrate, sample_pnt);
}
#endif /* CONFIG_CAN_FD_MODE */

int can_calc_prescaler(const struct device *dev, struct can_timing *timing,
		       uint32_t bitrate)
{
	uint32_t ts = timing->prop_seg + timing->phase_seg1 + timing->phase_seg2 +
		   CAN_SYNC_SEG;
	uint32_t core_clock;
	int ret;

	ret = can_get_core_clock(dev, &core_clock);
	if (ret != 0) {
		return ret;
	}

	timing->prescaler = core_clock / (bitrate * ts);

	return core_clock % (ts * timing->prescaler);
}

/**
 * @brief Get the sample point location for a given bitrate
 *
 * @param  bitrate The bitrate in bits/second.
 * @return The sample point in permille.
 */
uint16_t sample_point_for_bitrate(uint32_t bitrate)
{
	uint16_t sample_pnt;

	if (bitrate > 800000) {
		/* 75.0% */
		sample_pnt = 750;
	} else if (bitrate > 500000) {
		/* 80.0% */
		sample_pnt = 800;
	} else {
		/* 87.5% */
		sample_pnt = 875;
	}

	return sample_pnt;
}

int z_impl_can_set_bitrate(const struct device *dev, uint32_t bitrate)
{
	struct can_timing timing;
	uint32_t max_bitrate;
	uint16_t sample_pnt;
	int ret;

	ret = can_get_max_bitrate(dev, &max_bitrate);
	if (ret == -ENOSYS) {
		/* Maximum bitrate unknown */
		max_bitrate = 0;
	} else if (ret < 0) {
		return ret;
	}

	if ((max_bitrate > 0) && (bitrate > max_bitrate)) {
		return -ENOTSUP;
	}

	sample_pnt = sample_point_for_bitrate(bitrate);
	ret = can_calc_timing(dev, &timing, bitrate, sample_pnt);
	if (ret < 0) {
		return ret;
	}

	if (ret > SAMPLE_POINT_MARGIN) {
		return -ERANGE;
	}

	timing.sjw = CAN_SJW_NO_CHANGE;

	return can_set_timing(dev, &timing);
}

#ifdef CONFIG_CAN_FD_MODE
int z_impl_can_set_bitrate_data(const struct device *dev, uint32_t bitrate_data)
{
	struct can_timing timing_data;
	uint32_t max_bitrate;
	uint16_t sample_pnt;
	int ret;

	ret = can_get_max_bitrate(dev, &max_bitrate);
	if (ret == -ENOSYS) {
		/* Maximum bitrate unknown */
		max_bitrate = 0;
	} else if (ret < 0) {
		return ret;
	}

	if ((max_bitrate > 0) && (bitrate_data > max_bitrate)) {
		return -ENOTSUP;
	}

	sample_pnt = sample_point_for_bitrate(bitrate_data);
	ret = can_calc_timing_data(dev, &timing_data, bitrate_data, sample_pnt);
	if (ret < 0) {
		return ret;
	}

	if (ret > SAMPLE_POINT_MARGIN) {
		return -ERANGE;
	}

	timing_data.sjw = CAN_SJW_NO_CHANGE;

	return can_set_timing_data(dev, &timing_data);
}
#endif /* CONFIG_CAN_FD_MODE */