text:
package nl.rivm.cib.epidemes.cbs.json;

import java.io.IOException;
import java.io.InputStream;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.yaml.YamlConfiguration;

import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import io.coala.exception.Thrower;
import io.coala.json.JsonUtil;
import io.coala.log.LogUtil;
import io.coala.util.FileUtil;
import io.reactivex.Observable;

/**
 * {@link CbsRegionHierarchy} basic address data:
 *
 * <pre>
 * {
"reg":["GM...", ...],
"Arbeidsmarktregio's":["AM..", ...],
"Arrondissementen (rechtsgebieden)":["AR..", ...],
"COROP-gebieden":["CR..", ...],
"COROP-subgebieden":["CS..", ...],
"COROP-plusgebieden":["CP..", ...],
"GGD-regio's":["GG..", ...],
"Jeugdzorgregios":["JZ..", ...],
"Kamer van Koophandel":["KK..", ...],
"Landbouwgebieden":["LB..", ...],
"Landbouwgebieden (groepen)":["LG..", ...],
"Landsdelen":["LD", ...],
"NUTS1-gebieden":["NL.", ...],
"NUTS2-gebieden":["NL..", ...],
"NUTS3-gebieden":["NL...", ...],
"Politie Regionale eenheden":["RE..", ...],
"Provincies":["PV..", ...],
"Ressorten (rechtsgebieden)":["RT", ...],
"RPA-gebieden":["RP..", ...],
"Toeristengebieden":["TR", ...],
"Veiligheidsregio's":["VR..", ...],
"Wgr-samenwerkingsgebieden":["WG..", ...],
"Zorgkantoorregio's":["ZK..", ...]
}
 * </pre>
 *
 * @version $Id$
 * @author Rick van Krevelen
 */
@JsonIgnoreProperties( ignoreUnknown = true )
public class CbsRegionHierarchy
{

	@JsonProperty( "reg" )
	public String[] gm;

	public Map<String, Object> values = new TreeMap<>();

	@JsonAnySetter
	public void set( final String key, final Object value )
	{
		this.values.put( key, value );
	}

	@JsonAnyGetter
	public Object get( final String key )
	{
		return this.values.get( key );
	}

	@Override
	public String toString()
	{
		return JsonUtil.stringify( this );
	}

	/** */
	private static final Logger LOG = LogUtil
			.getLogger( CbsRegionHierarchy.class );

	private static final String FILE_BASE = "../episim-demo/dist/";

	private static final String FILE_NAME = "83287NED.json";

	public static void main( final String[] args ) throws IOException
	{

		if( System.getProperty(
				ConfigurationFactory.CONFIGURATION_FILE_PROPERTY ) == null )
			try( final InputStream is = FileUtil
					.toInputStream( FILE_BASE + "log4j2.yaml" ) )
			{
			// see https://stackoverflow.com/a/42524443
			final LoggerContext ctx = LoggerContext.getContext( false );
			ctx.start( new YamlConfiguration( ctx, new ConfigurationSource( is ) ) );
			}

		try( final InputStream is = FileUtil
				.toInputStream( FILE_BASE + FILE_NAME ) )
		{
			final CbsRegionHierarchy hier = JsonUtil.getJOM().readValue( is,
					CbsRegionHierarchy.class );
			LOG.info( "GM regions: {}", hier.cityRegionsByType() );

			LOG.info( "Hierarchy: {}",
					JsonUtil.toJSON( hier.addAdminHierarchy( null ) ) );
		}
	}

	@SuppressWarnings( "unchecked" )
	public TreeMap<String, EnumMap<CBSRegionType, String>> cityRegionsByType()
	{
		return Observable.range( 0, this.gm.length ).collectInto(
				new TreeMap<String, EnumMap<CBSRegionType, String>>(),
				( m, i ) -> m.put( this.gm[i],
						this.values.values().stream()
								.map( v -> ((List<String>) v).get( i ) )
								.filter( v -> v != null && !v.isEmpty() )
								.collect( Collectors.toMap(
										v -> CBSRegionType.parse( v ), v -> v,
										( v1, v2 ) -> v1,
										() -> new EnumMap<>(
												CBSRegionType.class ) ) ) ) )
				.blockingGet();
	}

	// landsdeel/nuts1 -> prov/nuts2 (12) -> corop/nuts3 (25) -> corop_sub -> corop_plus -> gm (400)
	// ggd (25x)
	// jeugdzorg (42x)
	// ressort (4) -> district (11) -> safety (25) (!= police reg eenh)
	// politie reg eenh (10x) -> districten (43x)
	// agri_group -> agr

	public ObjectNode addAdminHierarchy( final JsonNode gmMap )
	{
		final TreeMap<String, EnumMap<CBSRegionType, String>> gmRegs = cityRegionsByType();

		final ObjectNode result = JsonUtil.getJOM().createObjectNode();

		if( gmMap != null && gmMap.isObject() && gmMap.size() != 0 )
			// only place given keys in a hierarchy
			JsonUtil.forEach( (ObjectNode) gmMap,
					( k, v ) -> insertHierarchy( result,
							gmRegs.get( k.toUpperCase() ), k, v ) );
		else if( gmMap == null || gmMap.isNull()
				|| (gmMap.isContainerNode() && gmMap.size() == 0) )
			// create empty nodes for all known keys
			gmRegs.forEach( ( k, v ) -> insertHierarchy( result, v, k,
					JsonUtil.getJOM().createObjectNode() ) );
		else
			Thrower.throwNew( IllegalArgumentException::new,
					() -> "Illegal filter: " + gmMap );

		return result;
	}

	public static final String REG_TAGS_KEY = "reg_tags";

	private void insertHierarchy( final ObjectNode container,
		final EnumMap<CBSRegionType, String> v, final String gm,
		final JsonNode gmNode )
	{
		final ObjectMapper om = JsonUtil.getJOM();

		final ObjectNode ld = container
				.with( v.get( CBSRegionType.TERRITORY ) );
		ld.replace( REG_TAGS_KEY,
				om.createArrayNode().add( v.get( CBSRegionType.TERRITORY ) )
						.add( v.get( CBSRegionType.NUTS1 ) ) );

		final ObjectNode pv = ld.with( CBSRegionType.PROVINCE.getPrefix() )
				.with( v.get( CBSRegionType.PROVINCE ) );
		pv.replace( REG_TAGS_KEY,
				om.createArrayNode().add( v.get( CBSRegionType.TERRITORY ) )
						.add( v.get( CBSRegionType.NUTS1 ) )
						.add( v.get( CBSRegionType.PROVINCE ) )
						.add( v.get( CBSRegionType.NUTS2 ) ) );

		final ObjectNode cr = pv.with( CBSRegionType.COROP.getPrefix() )
				.with( v.get( CBSRegionType.COROP ) );
		cr.replace( REG_TAGS_KEY,
				om.createArrayNode().add( v.get( CBSRegionType.TERRITORY ) )
						.add( v.get( CBSRegionType.NUTS1 ) )
						.add( v.get( CBSRegionType.PROVINCE ) )
						.add( v.get( CBSRegionType.NUTS2 ) )
						.add( v.get( CBSRegionType.COROP ) )
						.add( v.get( CBSRegionType.NUTS3 ) ) );

		cr.with( CBSRegionType.MUNICIPAL.getPrefix() )
				.replace( gm,
						gmNode.isObject()
								? ((ObjectNode) gmNode).set( REG_TAGS_KEY,
										om.valueToTree( v.values() ) )
								: gmNode );
	}
}


text:
+++
Title = "Adiel Cristo"
Twitter = "adielcristo"
linkedin = "https://www.linkedin.com/in/adielcristo/"
image = "adiel-cristo.jpg"
type = "speaker"
linktitle = "adiel-cristo"
website = ""

+++

Desenvolvedor PHP interessado em técnicas e ferramentas para melhoria de código e automatização de processos.

redpajama_set_name: RedPajamaGithub


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable enable

using System.Collections.Generic;
using System.Text;

namespace Roslyn.Utilities
{
    internal static class CommandLineUtilities
    {
        /// <summary>
        /// Split a command line by the same rules as Main would get the commands except the original
        /// state of backslashes and quotes are preserved.  For example in normal Windows command line
        /// parsing the following command lines would produce equivalent Main arguments:
        ///
        ///     - /r:a,b
        ///     - /r:"a,b"
        ///
        /// This method will differ as the latter will have the quotes preserved.  The only case where
        /// quotes are removed is when the entire argument is surrounded by quotes without any inner
        /// quotes.
        /// </summary>
        /// <remarks>
        /// Rules for command line parsing, according to MSDN:
        ///
        /// Arguments are delimited by white space, which is either a space or a tab.
        ///
        /// A string surrounded by double quotation marks ("string") is interpreted
        /// as a single argument, regardless of white space contained within.
        /// A quoted string can be embedded in an argument.
        ///
        /// A double quotation mark preceded by a backslash (\") is interpreted as a
        /// literal double quotation mark character (").
        ///
        /// Backslashes are interpreted literally, unless they immediately precede a
        /// double quotation mark.
        ///
        /// If an even number of backslashes is followed by a double quotation mark,
        /// one backslash is placed in the argv array for every pair of backslashes,
        /// and the double quotation mark is interpreted as a string delimiter.
        ///
        /// If an odd number of backslashes is followed by a double quotation mark,
        /// one backslash is placed in the argv array for every pair of backslashes,
        /// and the double quotation mark is "escaped" by the remaining backslash,
        /// causing a literal double quotation mark (") to be placed in argv.
        /// </remarks>
        public static IEnumerable<string> SplitCommandLineIntoArguments(string commandLine, bool removeHashComments)
        {
            char? unused;
            return SplitCommandLineIntoArguments(commandLine, removeHashComments, out unused);
        }

        public static IEnumerable<string> SplitCommandLineIntoArguments(string commandLine, bool removeHashComments, out char? illegalChar)
        {
            var builder = new StringBuilder(commandLine.Length);
            var list = new List<string>();
            var i = 0;

            illegalChar = null;
            while (i < commandLine.Length)
            {
                while (i < commandLine.Length && char.IsWhiteSpace(commandLine[i]))
                {
                    i++;
                }

                if (i == commandLine.Length)
                {
                    break;
                }

                if (commandLine[i] == '#' && removeHashComments)
                {
                    break;
                }

                var quoteCount = 0;
                builder.Length = 0;
                while (i < commandLine.Length && (!char.IsWhiteSpace(commandLine[i]) || (quoteCount % 2 != 0)))
                {
                    var current = commandLine[i];
                    switch (current)
                    {
                        case '\\':
                            {
                                var slashCount = 0;
                                do
                                {
                                    builder.Append(commandLine[i]);
                                    i++;
                                    slashCount++;
                                } while (i < commandLine.Length && commandLine[i] == '\\');

                                // Slashes not followed by a quote character can be ignored for now
                                if (i >= commandLine.Length || commandLine[i] != '"')
                                {
                                    break;
                                }

                                // If there is an odd number of slashes then it is escaping the quote
                                // otherwise it is just a quote.
                                if (slashCount % 2 == 0)
                                {
                                    quoteCount++;
                                }

                                builder.Append('"');
                                i++;
                                break;
                            }

                        case '"':
                            builder.Append(current);
                            quoteCount++;
                            i++;
                            break;

                        default:
                            if ((current >= 0x1 && current <= 0x1f) || current == '|')
                            {
                                if (illegalChar == null)
                                {
                                    illegalChar = current;
                                }
                            }
                            else
                            {
                                builder.Append(current);
                            }

                            i++;
                            break;
                    }
                }

                // If the quote string is surrounded by quotes with no interior quotes then
                // remove the quotes here.
                if (quoteCount == 2 && builder[0] == '"' && builder[builder.Length - 1] == '"')
                {
                    builder.Remove(0, length: 1);
                    builder.Remove(builder.Length - 1, length: 1);
                }

                if (builder.Length > 0)
                {
                    list.Add(builder.ToString());
                }
            }

            return list;
        }
    }
}


text:
mobilecaddy-cli
===

CLI tools for MobileCaddy.

## Installation

`$ npm install -g mobilecaddy`

## Usage

### List available templates

```
mobilecaddy templates
```

### Create a new project from a template

```
mobilecaddy new <template|git-zip-url> <your-app-name> [--sudo]
```

Supplying *--sudo* flag will run *npm install* commands with sudo (auto on Mac OS)

### Start your app in a local web server

```
mobilecaddy serve [options]

## options:
## --local								# run against local mock data rather than SFDC
## --scrub=[true | full]	# Clears local data ('full'=inc oauth)
## --rec									# Record SFDC responses and populate 'mock' files
```


text:
module GSectionedShower
  module ViewHelpers

    # GUIlded component.
    #
    # *parameters*
    # ar_obj:: The ActiveRecord object containing the information.
    #
    # *options*
    # id:: (required) The id of the element.  Must be unique on the page.
    # class::
    # title_attr:: The attribute to use in the title.
    # title_pre:: A string to override the first part of the title.  defaults to the name
    #   of the active record object's class.
    # date_format:: A symbol representing the date format to use.  Defaults to :default.
    # attributes:: A list of attributes to include in the main section.
    # status:: True to include a status section.
    # namespace:: A namespace to append onto all path helpers that are not overridden.
    # sections::
    #   title:: The title for this section.
    #   attributes:: List of attibutes to include in this section.
    #   {associated_attribute_name}_attributes:: List of attributes from associated attribute to include.
    #   {associated_attribute_name}_max:: The max number of associated records to show.  This will load
    #     all and display max unless you define a limited named scope on the respective model, allowing
    #     the association to be limited to the max, not returning items that will not be displayed.
    #   links:: A list of fields or field => path_helper to generate links to this item in the associated
    #     object.
    #   list_link:: (Boolean, string, or symbol)
    #
    def g_sectioned_shower( ar_obj, *args )

        options = args.extract_options!
        raise ArgumentError, "'title_attr' option required" unless options.include?( :title_attr )
        raise ArgumentError, "'sections' option required" unless options.include?( :sections )
        options.merge! :class => "shower" unless options.include?( :class )
        options.merge! :exclude_css => true, :exclude_js => true
        Guilded::Guilder.instance.add( :sectioned_shower, options )
        html = ""

        html << "
#{options[:status].to_s.humanize}
" if options[:status]

        title_pre = options[:title_pre] || "#{ar_obj.class.to_s.underscore.humanize} |"
        html << "
#{title_pre} #{ar_obj.send( options[:title_attr].to_sym )}
"

        # Resolve sections and meta data there-in
        sections = options[:sections]
        reflections = ar_obj.class.inheritable_attributes[:reflections]

        # Resolve main section
        main_section = sections[0]
        raise ArgumentError, "'attributes' option required within main section configuration" unless main_section.include?( :attributes )

        methods, titles = Guilded::Rails::Helpers.resolve_field_methods_and_titles( main_section[:attributes], ar_obj )

        html << "

"

        methods.each_with_index do |method, i|

          # Handle associative relationships
          if !reflections.nil? && reflections.has_key?( method.to_sym )
            handle_associated( html, ar_obj, main_section, reflections, methods, i )
          else
            # Normal attribute from this model
            html << "
#{titles[i]}
"
            translate_method = "translate_#{method}".to_sym
            val = ar_obj.send( method )
            if respond_to?( translate_method )
              html << "
#{h( send( translate_method, val ) )}
"
            else
              val = val.to_formatted_s( options[:date_format] || :default ) if val.respond_to?( :to_formatted_s )
              html << "
#{h( val )}
"
            end
          end

        end

        html << "

"

        # Get rid of the main section as it was already handled
        sections.delete_at( 0 )

        # Resolve other sections
        sections.each do |section|

          raise ArgumentError, "'attributes' option required within main section configuration" unless section.include?( :attributes )
          raise ArgumentError, "'title' option required within all section configurations except the main section" unless section.include?( :title )

          methods, titles = Guilded::Rails::Helpers.resolve_field_methods_and_titles( section[:attributes], ar_obj )
          html << "

#{section[:title]}

"

          methods.each_with_index do |method, i|

            # Handle associative relationships
            if !reflections.nil? && reflections.has_key?( method.to_sym )
              handle_associated( html, ar_obj, section, reflections, methods, i )
            else
              # Normal attribute from this model
              html << "
#{titles[i]}
"
              translate_method = "translate_#{method}".to_sym
              val = ar_obj.send( method )
              if respond_to?( translate_method )
                "
#{h( send( translate_method, val ) )}
"
              else
                html << "
#{h( val )}
"
              end
            end

          end

          html << "

"

        end

        html
      end

      protected

      def handle_associated( html, ar_obj, section, reflections, methods, index )
        #TODO handle translation helpers if they exist.
        reflection = reflections[methods[index].to_sym]

        # Handle many relationships
        if ['has_many', 'has_and_belongs_to_many'].include?( reflection.macro.to_s )
          handle_associated_many( html, ar_obj, reflection, section, methods, index )
        elsif ['belongs_to', 'has_one'].include?( reflection.macro.to_s ) # Handle single relationships
          handle_associated_single( html, ar_obj, reflection, section, methods, index )
        elsif reflection.macro.to_s == 'composed_of'
          handle_composed_of( html, ar_obj, methods, index )
        end

      end

      def handle_composed_of( html, ar_obj, methods, index )
        label = ar_obj.class.human_attribute_name( methods[index] ) || methods[index].to_s.humanize
        html << "
#{label}

#{ar_obj.send( methods[index] ).to_s}
"
      end

      def handle_associated_single( html, ar_obj, reflection, section, methods, index )

        assoc_obj_output = ""

        if section.has_key?( "#{reflection.name.to_s.singularize}_attributes".to_sym )
          # Handle object output if fields specified explicitly

          attrs = section[ "#{reflection.name.to_s.singularize}_attributes".to_sym ]
          scoped_by = section[ "#{reflection.name.to_s.singularize}_scoped_by".to_sym ]
          rel_methods, rel_titles = Guilded::Rails::Helpers.resolve_field_methods_and_titles( attrs, ar_obj.send( reflection.name.to_s.to_sym ) )
          assoc_obj = ar_obj.send( methods[index] )

          rel_methods.each_with_index do |rel_method, rel_i|

            method_output = h( assoc_obj.send( rel_method ) ) unless assoc_obj.nil?

            links = section[:links]
            throw "The 'links' option must have values in it, or be left out of the options for the section." if !links.nil? && links.empty?
            unless links.nil?
              link_entry = find_link_entry( links, rel_method )  # section.has_key?( :links )
              opts = Hash.new
              opts.merge!( :scoped_by => scoped_by ) unless scoped_by.nil?
              path_helpers = Guilded::Rails::Helpers.resolve_rest_path_helpers( assoc_obj, opts )
            end

            if !link_entry.nil? #&& ( link_entry.is_a?( Symbol ) || link_entry.is_a?( String ) )
              assoc_obj_link = @controller.send( path_helpers[:show_rest_helper], *(path_helpers[:show_rest_args] + [assoc_obj]) )
              assoc_obj_output << "
#{rel_titles[rel_i]}

#{link_to( method_output, assoc_obj_link )}
"
            #elsif !link_entry.nil? && link_entry.is_a?( Hash )
            else
              assoc_obj_output << "
#{rel_titles[rel_i]}

#{h( method_output )}
"
            end

          end

        else
          # Otherwise just use to_s for the object
          assoc_obj_output = ar_obj.send( methods[index] ).to_s
        end

        html << assoc_obj_output
      end

      def handle_associated_many( html, ar_obj, reflection, section, methods, index )
        reflected_name = reflection.name.to_s
        reflected_singular_name = reflected_name.singularize
        reflected_humanized_name = reflected_name.humanize
        attrs_name = "#{reflected_singular_name}_attributes"
        attrs = section[ attrs_name.to_sym ]
        scoped_by = section[ "#{reflection.name.to_s.singularize}_scoped_by".to_sym ]
        max_name = "#{reflected_singular_name}_max"
        max = section[ max_name.to_sym ]
        showing_less_than_all = max && max < ar_obj.send( methods[index] ).count
        empty_embedded_ar_obj = reflection.klass.new
        rel_methods, rel_titles = Guilded::Rails::Helpers.resolve_field_methods_and_titles( attrs, empty_embedded_ar_obj ) unless attrs.nil? || attrs.empty?

        # Handle creating a link to the associated many objects list
    #    if section[:list_link]
    #
    #      if section[:list_link].is_a?( Symbol )
    #        assoc_obj_index_path_helper = section[:list_link].to_s
    #      elsif section[:list_link].is_a?( String )
    #        assoc_obj_index_path_helper = section[:list_link]
    #      elsif section[:list_link] == true
    #        non_namespaced_index_path_helper = "#{ar_obj.class.to_s.tableize.singularize}_#{reflection.name.to_s}_path"
    #        if options[:namespace]
    #          assoc_obj_index_path_helper = "#{options[:namespace].to_s}_#{non_namespaced_index_path_helper}"
    #        else
    #          assoc_obj_index_path_helper = non_namespaced_index_path_helper
    #        end
    #      else
    #        throw "The 'list_link' parameter must be a String, Symbol or true"
    #      end
    #
    #      if showing_less_than_all
    #        index_link = link_to( "More #{reflected_humanized_name}...", @controller.send( assoc_obj_index_path_helper, ar_obj ) )
    #      else
    #        index_link = link_to( "Jump to #{reflected_humanized_name}", @controller.send( assoc_obj_index_path_helper, ar_obj ) )
    #      end
    #
    #      html << "
#{index_link}

"
    #
    #    end

        embedded_collection = (max && ar_obj.send( methods[index] ).respond_to?( :limited )) ? ar_obj.send( methods[index] ).limited( max ) : ar_obj.send( methods[index] )

        # Loop through the collection of embeddeds
        embedded_collection.each_with_index do |assoc_ar_obj, i|

          break if max && i == max # Only display the max number specified (only necessary for when limited is not defined on AR class)
          assoc_obj_output = ""

          if section.has_key?( "#{reflected_singular_name}_attributes".to_sym )
            # Handle object output if fields specified explicitly

            rel_methods.each_with_index do |rel_method, rel_i|

              method_output = h( assoc_ar_obj.send( rel_method ) ) unless assoc_ar_obj.nil?

              links = section[:links]
              throw "The 'links' option must have values in it, or be left out of the options for the section." if !links.nil? && links.empty?
              unless links.nil?
                link_entry = find_link_entry( links, rel_method )  # section.has_key?( :links )
                opts = Hash.new
                opts.merge!( :scoped_by => scoped_by ) unless scoped_by.nil?
                path_helpers = Guilded::Rails::Helpers.resolve_rest_path_helpers( assoc_ar_obj, opts )
              end

              if !link_entry.nil? #&& ( link_entry.is_a?( Symbol ) || link_entry.is_a?( String ) )
                assoc_obj_link = @controller.send( path_helpers[:show_rest_helper], *(path_helpers[:show_rest_args] + [assoc_ar_obj]) )
                assoc_obj_output << "
#{rel_titles[rel_i]}

#{link_to( method_output, assoc_obj_link )}
"
              #elsif !link_entry.nil? && link_entry.is_a?( Hash )
              else
                assoc_obj_output << "
#{rel_titles[rel_i]}

#{h( method_output )}
"
              end

            end

          else
            # Otherwise just use to_s for the object
            assoc_obj_output << assoc_ar_obj.to_s
          end

          html << assoc_obj_output
        end

        # output '...' if there are embeddeds that are not displayed and we did not render a link to embeddeds index
        html << "
...

" if showing_less_than_all && ( section[:list_link].nil? || section[:list_link] == false )

      end # def handle_associated_many

      def find_link_entry( links, val )
        links.each do |link|
          #if link.is_a?( Hash )
          #  return link if link.has_key?( val.to_sym )
          #else
            return link if link == val.to_sym
          #end
        end
        return nil
      end

  end
end


text:
#ifndef AAHairLinePathRenderer_DEFINED
#define AAHairLinePathRenderer_DEFINED

#include "src/gpu/v1/PathRenderer.h"

namespace skgpu::v1 {

class AAHairLinePathRenderer final : public PathRenderer {
public:
    AAHairLinePathRenderer() = default;

    const char* name() const override { return "AAHairline"; }

private:
    CanDrawPath onCanDrawPath(const CanDrawPathArgs&) const override;

    bool onDrawPath(const DrawPathArgs&) override;
};

} // namespace skgpu::v1

#endif // AAHairLinePathRenderer_DEFINED


text:
@implementation GPUImageMissEtikateFilter

- (id)init;
{
    if (!(self = [super init]))
    {
		return nil;
    }

    UIImage *image = [UIImage imageNamed:@"lookup_miss_etikate.png"];
    NSAssert(image, @"To use GPUImageMissEtikateFilter you need to add lookup_miss_etikate.png from GPUImage/framework/Resources to your application bundle.");

    lookupImageSource = [[GPUImagePicture alloc] initWithImage:image];
    GPUImageLookupFilter *lookupFilter = [[GPUImageLookupFilter alloc] init];

    [lookupImageSource addTarget:lookupFilter atTextureLocation:1];
    [lookupImageSource processImage];

    self.initialFilters = [NSArray arrayWithObjects:lookupFilter, nil];
    self.terminalFilter = lookupFilter;

    return self;
}

-(void)prepareForImageCapture {
    [lookupImageSource processImage];
    [super prepareForImageCapture];
}

#pragma mark -
#pragma mark Accessors

@end


text:
package corescala

import scala.xml.NodeSeq

class Container(app: WebApp) {

  private implicit val request = new Request(1)

  def run(page: String): String = page match {
    case "index" => app.index
    case "about" => app.about
    case "contato" => app.contato
    case p => "pagina desconhecida"
  }
}


text:
namespace libkafka_asio
{

inline Int16 OffsetFetchRequest::ApiKey()
{
  return constants::kApiKeyOffsetFetchRequest;
}

inline const String& OffsetFetchRequest::consumer_group() const
{
  return consumer_group_;
}

inline const OffsetFetchRequest::TopicVector& OffsetFetchRequest::topics() const
{
  return topics_;
}

inline void OffsetFetchRequest::set_consumer_group(const String& consumer_group)
{
  consumer_group_ = consumer_group;
}

inline void OffsetFetchRequest::FetchOffset(const String& topic_name,
                                            Int32 partition)
{
  TopicVector::iterator topic_iter =
    detail::FindTopicByName(topic_name, topics_);
  Topic::PartitionVector::iterator partition_iter =
    detail::FindTopicPartitionByNumber(partition, topic_iter->partitions);
}

}  // namespace libkafka_asio

#include <libkafka_asio/detail/impl/offset_fetch_request_write.h>

#endif  // OFFSET_FETCH_REQUEST_H_FCE526A2_0BA6_48F4_9717_4729A46D6D5D


text:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <CheckBox
            android:id="@+id/block_user"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:text="@string/hint_block_user_for" />

        <EditText
            android:id="@+id/block_user_days"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="number"
            android:minEms="3"
            android:text="1"
            tools:ignore="HardcodedText" />
    </LinearLayout>

    <androidx.appcompat.widget.AppCompatSpinner
        android:id="@+id/block_mode"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp" />

</merge>


text:
if (...) then

	-- Dependancies
	local _PATH = (...):gsub('%.core.assert$','')
	local Utils = require (_PATH .. '.core.utils')

	-- Local references
	local lua_type = type
	local floor = math.floor
	local concat = table.concat
	local next = next
	local pairs = pairs
	local getmetatable = getmetatable

	-- Is I an integer ?
	local function isInteger(i)
		return lua_type(i) ==('number') and (floor(i)==i)
	end

	-- Override lua_type to return integers
	local function type(v)
		return isInteger(v) and 'int' or lua_type(v)
	end

	-- Does the given array contents match a predicate type ?
	local function arrayContentsMatch(t,...)
		local n_count = Utils.arraySize(t)
		if n_count < 1 then return false end
		local init_count = t[0] and 0 or 1
		local n_count = (t[0] and n_count-1 or n_count)
		local types = {...}
		if types then types = concat(types) end
		for i=init_count,n_count,1 do
			if not t[i] then return false end
			if types then
				if not types:match(type(t[i])) then return false end
			end
		end
		return true
	end

	-- Checks if arg is a valid array map
  local function isMap(m)
		if not arrayContentsMatch(m, 'table') then return false end
		local lsize = Utils.arraySize(m[next(m)])
		for k,v in pairs(m) do
			if not arrayContentsMatch(m[k], 'string', 'int') then return false end
			if Utils.arraySize(v)~=lsize then return false end
		end
		return true
  end

	-- Checks if s is a valid string map
  local function isStringMap(s)
    if lua_type(s) ~= 'string' then return false end
    local w
    for row in s:gmatch('[^\n\r]+') do
      if not row then return false end
      w = w or #row
      if w ~= #row then return false end
    end
    return true
  end

	-- Does instance derive straight from class
	local function derives(instance, class)
		return getmetatable(instance) == class
	end

	-- Does instance inherits from class
	local function inherits(instance, class)
		return (getmetatable(getmetatable(instance)) == class)
	end

	-- Is arg a boolean
	local function isBoolean(b)
		return (b==true or b==false)
	end

	-- Is arg nil ?
	local function isNil(n)
		return (n==nil)
	end

	local function matchType(value, types)
		return types:match(type(value))
	end

	return {
		arrayContentsMatch = arrayContentsMatch,
		derives = derives,
		inherits = inherits,
		isInteger = isInteger,
		isBool = isBoolean,
		isMap = isMap,
		isStrMap = isStringMap,
		isOutOfRange = isOutOfRange,
		isNil = isNil,
		type = type,
		matchType = matchType
	}

end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--~
    ~ JBoss, Home of Professional Open Source
    ~ Copyright Red Hat, Inc., and individual contributors
    ~ by the @authors tag. See the copyright.txt in the distribution for a
    ~ full listing of individual contributors.
    ~
    ~ 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.
-->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.jboss.as.quickstarts</groupId>
    <artifactId>jboss-as-kitchensink-html5-ios-test</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <name>kitchensink-html5-ios-test</name>

    <developers>
        <developer>
            <name>Tolis Emmanouilidis</name>
            <email>aemmanou@redhat.com</email>
        </developer>
    </developers>

    <url>http://jboss.org/jbossas</url>
    <licenses>
        <license>
            <name>Apache License, Version 2.0</name>
            <distribution>repo</distribution>
            <url>http://www.apache.org/licenses/LICENSE-2.0.html</url>
        </license>
    </licenses>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <version.selenium>2.31.0</version.selenium>
        <version.org.jboss.as>7.1.1.Final</version.org.jboss.as>
        <version.org.jboss.spec>3.0.2.Final</version.org.jboss.spec>
        <version.org.jboss.arquillian.graphene>2.0.0.Alpha3</version.org.jboss.arquillian.graphene>
        <version.org.jboss.arquillian>1.0.3.Final</version.org.jboss.arquillian>
        <version.org.jboss.arquillian.ios>1.0.0-SNAPSHOT</version.org.jboss.arquillian.ios>
        <version.org.apache.commons.lang>3.1</version.org.apache.commons.lang>
        <version.junit>4.11</version.junit>
    </properties>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>2.3.2</version>
                    <configuration>
                        <source>1.6</source>
                        <target>1.6</target>
                    </configuration>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.12</version>
                </plugin>
                <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
                <plugin>
                    <groupId>org.eclipse.m2e</groupId>
                    <artifactId>lifecycle-mapping</artifactId>
                    <version>1.0.0</version>
                    <configuration>
                        <lifecycleMappingMetadata>
                            <pluginExecutions>
                                <pluginExecution>
                                    <pluginExecutionFilter>
                                        <groupId>
                                            org.apache.maven.plugins
                                        </groupId>
                                        <artifactId>
                                            maven-dependency-plugin
                                        </artifactId>
                                        <versionRange>
                                            [2.1,)
                                        </versionRange>
                                        <goals>
                                            <goal>unpack</goal>
                                        </goals>
                                    </pluginExecutionFilter>
                                    <action>
                                        <ignore></ignore>
                                    </action>
                                </pluginExecution>
                            </pluginExecutions>
                        </lifecycleMappingMetadata>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

    <profiles>

        <!-- Arquillian JBoss managed profile -->
        <profile>
            <id>arq-jboss-managed</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <dependencies>
                <dependency>
                    <groupId>org.jboss.spec</groupId>
                    <artifactId>jboss-javaee-6.0</artifactId>
                    <version>${version.org.jboss.spec}</version>
                    <type>pom</type>
                    <scope>provided</scope>
                    <exclusions>
                        <exclusion>
                            <groupId>xalan</groupId>
                            <artifactId>xalan</artifactId>
                        </exclusion>
                    </exclusions>
                </dependency>
                <dependency>
                    <groupId>org.jboss.as</groupId>
                    <artifactId>jboss-as-arquillian-container-managed</artifactId>
                    <version>${version.org.jboss.as}</version>
                    <scope>test</scope>
                </dependency>
                <dependency>
                    <groupId>org.jboss.arquillian.protocol</groupId>
                    <artifactId>arquillian-protocol-servlet</artifactId>
                    <scope>test</scope>
                </dependency>
            </dependencies>
            <build>
                <testResources>
                    <testResource>
                        <directory>src/test/resources</directory>
                    </testResource>
                </testResources>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-dependency-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>unpack</id>
                                <phase>process-test-classes</phase>
                                <goals>
                                    <goal>unpack</goal>
                                </goals>
                                <configuration>
                                    <artifactItems>
                                        <artifactItem>
                                            <groupId>org.jboss.as</groupId>
                                            <artifactId>jboss-as-dist</artifactId>
                                            <version>${version.org.jboss.as}</version>
                                            <type>zip</type>
                                            <overWrite>false</overWrite>
                                            <outputDirectory>${project.build.directory}</outputDirectory>
                                        </artifactItem>
                                    </artifactItems>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                    <plugin>
                        <artifactId>maven-surefire-plugin</artifactId>
                        <version>2.12</version>
                        <executions>
                            <execution>
                                <id>default-test</id>
                                <configuration>
                                    <skip>true</skip>
                                </configuration>
                            </execution>
                            <!-- iPhone 5.0 -->
                            <execution>
                                <id>iPhone-5.0</id>
                                <goals>
                                    <goal>test</goal>
                                </goals>
                                <phase>test</phase>
                                <configuration>
                                    <systemPropertyVariables>
                                        <!-- Value should be iphone or ipad -->
                                        <arq.ios.family>iphone</arq.ios.family>
                                        <!-- SDK version -->
                                        <arq.ios.sdk>5.0</arq.ios.sdk>
                                        <!-- local copy of Selenium SVN repository -->
                                        <arq.ios.drone.localSeleniumCopy>/Users/jboss/Workspace/selenium-read-only</arq.ios.drone.localSeleniumCopy>
                                        <arq.webdriver.remote.address>http://localhost:3001/wd/hub</arq.webdriver.remote.address>
                                        <arq.webdriver.remote>true</arq.webdriver.remote>
                                    </systemPropertyVariables>
                                </configuration>
                            </execution>
                            <!-- iPhone 6.1 -->
                            <execution>
                                <id>iPhone-6.1</id>
                                <goals>
                                    <goal>test</goal>
                                </goals>
                                <phase>test</phase>
                                <configuration>
                                    <systemPropertyVariables>
                                        <!-- Value should be iphone or ipad -->
                                        <arq.ios.family>iphone</arq.ios.family>
                                        <!-- SDK version -->
                                        <arq.ios.sdk>6.1</arq.ios.sdk>
                                        <!-- local copy of Selenium SVN repository -->
                                        <arq.ios.drone.localSeleniumCopy>/Users/jboss/Workspace/selenium-read-only</arq.ios.drone.localSeleniumCopy>
                                        <arq.webdriver.remote.address>http://localhost:3001/wd/hub</arq.webdriver.remote.address>
                                        <arq.webdriver.remote>true</arq.webdriver.remote>
                                    </systemPropertyVariables>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>

        <!-- Arquillian JBoss remote profile -->
        <profile>
            <id>arq-jboss-remote</id>
            <dependencies>
                <dependency>
                    <groupId>org.jboss.spec</groupId>
                    <artifactId>jboss-javaee-6.0</artifactId>
                    <version>${version.org.jboss.spec}</version>
                    <type>pom</type>
                    <scope>provided</scope>
                    <exclusions>
                        <exclusion>
                            <groupId>xalan</groupId>
                            <artifactId>xalan</artifactId>
                        </exclusion>
                    </exclusions>
                </dependency>
                <dependency>
                    <groupId>org.jboss.as</groupId>
                    <artifactId>jboss-as-arquillian-container-remote</artifactId>
                    <version>${version.org.jboss.as}</version>
                    <scope>test</scope>
                </dependency>
                <dependency>
                    <groupId>org.jboss.arquillian.protocol</groupId>
                    <artifactId>arquillian-protocol-servlet</artifactId>
                    <scope>test</scope>
                </dependency>
            </dependencies>
        </profile>

    </profiles>

    <dependencyManagement>
        <dependencies>

            <!-- This POM serves as BOM (Bill of Materials) for managing core Selenium dependency versions. -->
            <dependency>
                <groupId>org.jboss.arquillian.selenium</groupId>
                <artifactId>selenium-bom</artifactId>
                <version>${version.selenium}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

            <!-- Starting point for integration Graphene test suites. -->
            <dependency>
                <groupId>org.jboss.arquillian.graphene</groupId>
                <artifactId>graphene-webdriver</artifactId>
                <version>${version.org.jboss.arquillian.graphene}</version>
                <type>pom</type>
            </dependency>

            <!-- Arquillian BOM (Bill Of Materials). -->
            <dependency>
                <groupId>org.jboss.arquillian</groupId>
                <artifactId>arquillian-bom</artifactId>
                <version>${version.org.jboss.arquillian}</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>

            <!-- JUnit regression testing framework. -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${version.junit}</version>
            </dependency>

        </dependencies>
    </dependencyManagement>

    <dependencies>

        <!-- Apache Commons lang -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>${version.org.apache.commons.lang}</version>
        </dependency>

        <!-- Starting point for integration Graphene test suites. -->
        <dependency>
            <groupId>org.jboss.arquillian.graphene</groupId>
            <artifactId>graphene-webdriver</artifactId>
            <type>pom</type>
        </dependency>

        <!-- Arquillian BOM (Bill Of Materials). -->
        <dependency>
            <groupId>org.jboss.arquillian</groupId>
            <artifactId>arquillian-bom</artifactId>
            <version>${version.org.jboss.arquillian}</version>
            <type>pom</type>
        </dependency>

        <!-- JUnit regression testing framework. -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>

        <!-- JUnit Container Implementation for the Arquillian Project -->
        <dependency>
            <groupId>org.jboss.arquillian.junit</groupId>
            <artifactId>arquillian-junit-container</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- Arquillian iOS extension -->
        <dependency>
            <groupId>org.jboss.arquillian.extension</groupId>
            <artifactId>arquillian-ios-depchain</artifactId>
            <version>${version.org.jboss.arquillian.ios}</version>
            <type>pom</type>
            <scope>test</scope>
        </dependency>

    </dependencies>

</project>


text:
<?php

class Lily_Queue_Worker_Stats {
    protected $_jobs_completed = 0;
    protected $_jobs_failed = 0;
    protected $_loops = 0;
    protected $_sleeps = 0;
    protected $_enqueue_fails = 0;
    protected $_start_time = 0;
    protected $_end_time = 0;

    /**
     * __toArray
     * @return array
     */
    public function __toArray() {
        return array(
            'jobs_completed' => $this->_jobs_completed,
            'jobs_failed' => $this->_jobs_failed,
            'loops' => $this->_loops,
            'sleeps' => $this->_sleeps,
            'enqueue_fails' => $this->_enqueue_fails,
            'start_time' => $this->_start_time,
            'end_time' => $this->_end_time
        );
    }

    /**
     * Increment jobs completed.
     * @return string
     */
    public function incJobsCompleted() {
        return ++$this->_jobs_completed;
    }

    /**
     * Get jobs completed.
     * @return string
     */
    public function getJobsCompleted() {
        return $this->_jobs_completed;
    }

    /**
     * Increment jobs failed.
     * @return string
     */
    public function incJobsFailed() {
        return ++$this->_jobs_failed;
    }

    /**
     * Get jobs failed.
     * @return string
     */
    public function getJobsFailed() {
        return $this->_jobs_failed;
    }

    /**
     * Increment loops.
     * @return string
     */
    public function incLoops() {
        return ++$this->_loops;
    }

    /**
     * Get loops.
     * @return string
     */
    public function getLoops() {
        return $this->_loops;
    }

    /**
     * Increment sleeps.
     * @return string
     */
    public function incSleeps() {
        return ++$this->_sleeps;
    }

    /**
     * Get sleeps.
     * @return string
     */
    public function getSleeps() {
        return $this->_sleeps;
    }

    /**
     * Increment enqueue fails.
     * @return string
     */
    public function incEnqueueFails() {
        return ++$this->_enqueueFails;
    }

    /**
     * Get enqueue fails.
     * @return string
     */
    public function getEnqueueFails() {
        return $this->_enqueueFails;
    }

    /**
     * Set the start time (time()).
     * @return string
     */
    public function setStartTime() {
        $this->_start_time = time();
        return $this;
    }

    /**
     * Get the start time.
     * @return string
     */
    public function getStartTime() {
        return $this->_start_time;
    }

    /**
     * Set the end time.
     * @return string
     */
    public function setEndTime() {
        $this->_end_time = time();
        return $this;
    }

    /**
     * Get end time.
     * @return string
     */
    public function getEndTime() {
        return $this->_end_time;
    }

    /**
     * Get time elapsed.
     * @return string
     */
    public function getElapsedTime() {
        return round($this->_end_time - $this->_start_time, 5);
    }
}


text:
/*
 * This function is used through-out the kernel (including mm and fs)
 * to indicate a major problem.
 */
#include <stdarg.h>

#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/delay.h>

asmlinkage void sys_sync(void);	/* it's really int */
extern void hard_reset_now(void);
extern void do_unblank_screen(void);
extern int C_A_D;

int panic_timeout = 0;

void panic_setup(char *str, int *ints)
{
	if (ints[0] == 1)
		panic_timeout = ints[1];
}

NORET_TYPE void panic(const char * fmt, ...)
{
	static char buf[1024];
	va_list args;
	int i;

	va_start(args, fmt);
	vsprintf(buf, fmt, args);
	va_end(args);
	printk(KERN_EMERG "Kernel panic: %s\n",buf);
	if (current == task[0])
		printk(KERN_EMERG "In swapper task - not syncing\n");
	else
		sys_sync();

	do_unblank_screen();

	if (panic_timeout > 0)
	{
		/*
	 	 * Delay timeout seconds before rebooting the machine.
		 * We can't use the "normal" timers since we just panicked..
	 	 */
		printk(KERN_EMERG "Rebooting in %d seconds..",panic_timeout);
		for(i = 0; i < (panic_timeout*1000); i++)
			udelay(1000);
		hard_reset_now();
	}
	for(;;);
}

/*
 * GCC 2.5.8 doesn't always optimize correctly; see include/asm/segment.h
 */

int bad_user_access_length(void)
{
        panic("bad_user_access_length executed (not cool, dude)");
}


text:
import * as mafmt from '@multiformats/mafmt'
import type { Multiaddr } from '@multiformats/multiaddr'
import {
  CODE_CIRCUIT,
  CODE_P2P,
  CODE_TCP,
  CODE_WS,
  CODE_WSS
} from './constants.js'

export function all (multiaddrs: Multiaddr[]) {
  return multiaddrs.filter((ma) => {
    if (ma.protoCodes().includes(CODE_CIRCUIT)) {
      return false
    }

    const testMa = ma.decapsulateCode(CODE_P2P)

    return mafmt.WebSockets.matches(testMa) ||
      mafmt.WebSocketsSecure.matches(testMa)
  })
}

export function dnsWss (multiaddrs: Multiaddr[]) {
  return multiaddrs.filter((ma) => {
    if (ma.protoCodes().includes(CODE_CIRCUIT)) {
      return false
    }

    const testMa = ma.decapsulateCode(CODE_P2P)

    return mafmt.WebSocketsSecure.matches(testMa) &&
      mafmt.DNS.matches(testMa.decapsulateCode(CODE_TCP).decapsulateCode(CODE_WSS))
  })
}

export function dnsWsOrWss (multiaddrs: Multiaddr[]) {
  return multiaddrs.filter((ma) => {
    if (ma.protoCodes().includes(CODE_CIRCUIT)) {
      return false
    }

    const testMa = ma.decapsulateCode(CODE_P2P)

    // WS
    if (mafmt.WebSockets.matches(testMa)) {
      return mafmt.DNS.matches(testMa.decapsulateCode(CODE_TCP).decapsulateCode(CODE_WS))
    }

    // WSS
    return mafmt.WebSocketsSecure.matches(testMa) &&
      mafmt.DNS.matches(testMa.decapsulateCode(CODE_TCP).decapsulateCode(CODE_WSS))
  })
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.VisualBasic;
using Microsoft.VisualBasic.Devices;
using Roslyn.Utilities;
using TestResources.NetFX;
using Xunit;

namespace Test.Utilities
{
    public abstract class DiagnosticAnalyzerTestBase
    {
        private static readonly MetadataReference s_corlibReference = MetadataReference.CreateFromAssemblyInternal(typeof(object).Assembly);
        private static readonly MetadataReference s_systemCoreReference = MetadataReference.CreateFromAssemblyInternal(typeof(Enumerable).Assembly);
        private static readonly MetadataReference s_systemXmlReference = MetadataReference.CreateFromAssemblyInternal(typeof(System.Xml.XmlDocument).Assembly);
        private static readonly MetadataReference s_systemXmlDataReference = MetadataReference.CreateFromAssemblyInternal(typeof(System.Data.Rule).Assembly);
        private static readonly MetadataReference s_csharpSymbolsReference = MetadataReference.CreateFromAssemblyInternal(typeof(CSharpCompilation).Assembly);
        private static readonly MetadataReference s_visualBasicSymbolsReference = MetadataReference.CreateFromAssemblyInternal(typeof(VisualBasicCompilation).Assembly);
        private static readonly MetadataReference s_visualBasicReference = MetadataReference.CreateFromAssemblyInternal(typeof(ComputerInfo).Assembly);
        private static readonly MetadataReference s_codeAnalysisReference = MetadataReference.CreateFromAssemblyInternal(typeof(Compilation).Assembly);
        private static readonly MetadataReference s_workspacesReference = MetadataReference.CreateFromAssemblyInternal(typeof(Workspace).Assembly);
        private static readonly MetadataReference s_immutableCollectionsReference = MetadataReference.CreateFromAssemblyInternal(typeof(ImmutableArray<int>).Assembly);
        private static readonly MetadataReference s_systemDiagnosticsDebugReference = MetadataReference.CreateFromAssemblyInternal(typeof(System.Diagnostics.Debug).Assembly);
        private static readonly MetadataReference s_systemDataReference = MetadataReference.CreateFromAssemblyInternal(typeof(System.Data.DataSet).Assembly);
        private static readonly CompilationOptions s_CSharpDefaultOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
        private static readonly CompilationOptions s_CSharpUnsafeCodeDefaultOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithAllowUnsafe(true);
        private static readonly CompilationOptions s_visualBasicDefaultOptions = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary);

        internal const string DefaultFilePathPrefix = "Test";
        internal const string CSharpDefaultFileExt = "cs";
        internal const string VisualBasicDefaultExt = "vb";
        internal static readonly string CSharpDefaultFilePath = DefaultFilePathPrefix + 0 + "." + CSharpDefaultFileExt;
        internal static readonly string VisualBasicDefaultFilePath = DefaultFilePathPrefix + 0 + "." + VisualBasicDefaultExt;

        private const string TestProjectName = "TestProject";

        protected const TestValidationMode DefaultTestValidationMode = TestValidationMode.AllowCompileWarnings;

        /// <summary>
        /// Return the C# diagnostic analyzer to get analyzer diagnostics.
        /// This may return null when used in context of verifying a code fix for compiler diagnostics.
        /// </summary>
        /// <returns></returns>
        protected abstract DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer();

        /// <summary>
        /// Return the VB diagnostic analyzer to get analyzer diagnostics.
        /// This may return null when used in context of verifying a code fix for compiler diagnostics.
        /// </summary>
        /// <returns></returns>
        protected abstract DiagnosticAnalyzer GetBasicDiagnosticAnalyzer();

        private static MetadataReference s_systemRuntimeFacadeRef;
        public static MetadataReference SystemRuntimeFacadeRef
        {
            get
            {
                if (s_systemRuntimeFacadeRef == null)
                {
                    s_systemRuntimeFacadeRef = AssemblyMetadata.CreateFromImage(ReferenceAssemblies_V45_Facades.System_Runtime).GetReference(display: "System.Runtime.dll");
                }

                return s_systemRuntimeFacadeRef;
            }
        }

        private static MetadataReference s_systemThreadingFacadeRef;
        public static MetadataReference SystemThreadingFacadeRef
        {
            get
            {
                if (s_systemThreadingFacadeRef == null)
                {
                    s_systemThreadingFacadeRef = AssemblyMetadata.CreateFromImage(ReferenceAssemblies_V45_Facades.System_Threading).GetReference(display: "System.Threading.dll");
                }

                return s_systemThreadingFacadeRef;
            }
        }

        private static MetadataReference s_systemThreadingTasksFacadeRef;
        public static MetadataReference SystemThreadingTaskFacadeRef
        {
            get
            {
                if (s_systemThreadingTasksFacadeRef == null)
                {
                    s_systemThreadingTasksFacadeRef = AssemblyMetadata.CreateFromImage(ReferenceAssemblies_V45_Facades.System_Threading_Tasks).GetReference(display: "System.Threading.Tasks.dll");
                }

                return s_systemThreadingTasksFacadeRef;
            }
        }

        protected bool PrintActualDiagnosticsOnFailure { get; set; }

        // It is assumed to be of the format, Get<RuleId>CSharpResultAt(line: {0}, column: {1}, message: {2})
        private string ExpectedDiagnosticsAssertionTemplate { get; set; }

        protected static DiagnosticResult GetGlobalResult(string id, string message)
        {
            return new DiagnosticResult
            {
                Id = id,
                Severity = DiagnosticSeverity.Warning,
                Message = message
            };
        }

        protected static DiagnosticResult GetGlobalResult(DiagnosticDescriptor rule, params string[] messageArguments)
        {
            return new DiagnosticResult
            {
                Id = rule.Id,
                Severity = rule.DefaultSeverity,
                Message = string.Format(rule.MessageFormat.ToString(), messageArguments)
            };
        }

        protected static DiagnosticResult GetBasicResultAt(int line, int column, string id, string message)
        {
            return GetResultAt(VisualBasicDefaultFilePath, line, column, id, message);
        }

        protected static DiagnosticResult GetBasicResultAt(int line, int column, DiagnosticDescriptor rule, params object[] messageArguments)
        {
            return GetResultAt(VisualBasicDefaultFilePath, line, column, rule, messageArguments);
        }

        protected static DiagnosticResult GetCSharpResultAt(int line, int column, string id, string message)
        {
            return GetResultAt(CSharpDefaultFilePath, line, column, id, message);
        }

        protected static DiagnosticResult GetCSharpResultAt(string id, string message, params string[] locationStrings)
        {
            return GetResultAt(CSharpDefaultFilePath, id, message, locationStrings);
        }

        protected static DiagnosticResult GetCSharpResultAt(int line, int column, DiagnosticDescriptor rule, params object[] messageArguments)
        {
            return GetResultAt(CSharpDefaultFilePath, line, column, rule, messageArguments);
        }

        protected static DiagnosticResult GetAdditionalFileResultAt(int line, int column, string additionalFilePath, DiagnosticDescriptor rule, params object[] messageArguments)
        {
            return GetResultAt(additionalFilePath, line, column, rule, messageArguments);
        }

        private static DiagnosticResult GetResultAt(string path, int line, int column, string id, string message)
        {
            var location = new DiagnosticResultLocation(path, line, column);

            return new DiagnosticResult
            {
                Locations = new[] { location },
                Id = id,
                Severity = DiagnosticSeverity.Warning,
                Message = message
            };
        }

        protected static DiagnosticResult GetResultAt(string path, string id, string message, params string[] locationStrings)
        {
            return new DiagnosticResult
            {
                Locations = ParseResultLocations(path, locationStrings),
                Id = id,
                Severity = DiagnosticSeverity.Warning,
                Message = message
            };
        }

        private static DiagnosticResult GetResultAt(string path, int line, int column, DiagnosticDescriptor rule, params object[] messageArguments)
        {
            var location = new DiagnosticResultLocation(path, line, column);

            return new DiagnosticResult
            {
                Locations = new[] { location },
                Id = rule.Id,
                Severity = rule.DefaultSeverity,
                Message = string.Format(rule.MessageFormat.ToString(), messageArguments)
            };
        }

        private static DiagnosticResultLocation[] ParseResultLocations(string defaultPath, string[] locationStrings)
        {
            var builder = new List<DiagnosticResultLocation>();

            foreach (string str in locationStrings)
            {
                string[] tokens = str.Split('(', ',', ')');
                Assert.True(tokens.Length == 4, "Location string must be of the format 'FileName.cs(line,column)' or just 'line,column' to use " + defaultPath + " as the file name.");

                string path = tokens[0] == "" ? defaultPath : tokens[0];

                int line;
                Assert.True(int.TryParse(tokens[1], out line) && line >= -1, "Line must be >= -1 in location string: " + str);

                int column;
                Assert.True(int.TryParse(tokens[2], out column) && line >= -1, "Column must be >= -1 in location string: " + str);

                builder.Add(new DiagnosticResultLocation(path, line, column));
            }

            return builder.ToArray();
        }

        protected void VerifyCSharpUnsafeCode(string source, params DiagnosticResult[] expected)
        {
            Verify(new[] { source }.ToFileAndSource(), LanguageNames.CSharp, GetCSharpDiagnosticAnalyzer(), DefaultTestValidationMode, true, expected);
        }

        protected void VerifyCSharp(string source, params DiagnosticResult[] expected)
        {
            Verify(new[] { source }.ToFileAndSource(), LanguageNames.CSharp, GetCSharpDiagnosticAnalyzer(), DefaultTestValidationMode, false, expected);
        }

        protected void VerifyCSharp(string source, TestValidationMode validationMode, params DiagnosticResult[] expected)
        {
            Verify(new[] { source }.ToFileAndSource(), LanguageNames.CSharp, GetCSharpDiagnosticAnalyzer(), validationMode, false, expected);
        }

        protected void VerifyCSharp(string source, bool addLanguageSpecificCodeAnalysisReference, TestValidationMode validationMode = DefaultTestValidationMode, params DiagnosticResult[] expected)
        {
            Verify(source, LanguageNames.CSharp, GetCSharpDiagnosticAnalyzer(), addLanguageSpecificCodeAnalysisReference, validationMode, expected);
        }

        protected void VerifyCSharp(string[] sources, params DiagnosticResult[] expected)
        {
            Verify(sources.ToFileAndSource(), LanguageNames.CSharp, GetCSharpDiagnosticAnalyzer(), DefaultTestValidationMode, false, expected);
        }

        protected void VerifyCSharp(FileAndSource[] sources, params DiagnosticResult[] expected)
        {
            Verify(sources, LanguageNames.CSharp, GetCSharpDiagnosticAnalyzer(), DefaultTestValidationMode, false, expected);
        }

        protected void VerifyBasic(string source, params DiagnosticResult[] expected)
        {
            Verify(new[] { source }.ToFileAndSource(), LanguageNames.VisualBasic, GetBasicDiagnosticAnalyzer(), DefaultTestValidationMode, false, expected);
        }

        protected void VerifyBasic(string source, TestValidationMode validationMode, params DiagnosticResult[] expected)
        {
            Verify(new[] { source }.ToFileAndSource(), LanguageNames.VisualBasic, GetBasicDiagnosticAnalyzer(), validationMode, false, expected);
        }

        protected void VerifyBasic(string source, bool addLanguageSpecificCodeAnalysisReference, TestValidationMode validationMode = DefaultTestValidationMode, params DiagnosticResult[] expected)
        {
            Verify(source, LanguageNames.VisualBasic, GetBasicDiagnosticAnalyzer(), addLanguageSpecificCodeAnalysisReference, validationMode, expected);
        }

        protected void VerifyBasic(string[] sources, params DiagnosticResult[] expected)
        {
            Verify(sources.ToFileAndSource(), LanguageNames.VisualBasic, GetBasicDiagnosticAnalyzer(), DefaultTestValidationMode, false, expected);
        }

        protected void VerifyBasic(FileAndSource[] sources, params DiagnosticResult[] expected)
        {
            Verify(sources, LanguageNames.VisualBasic, GetBasicDiagnosticAnalyzer(), DefaultTestValidationMode, false, expected);
        }

        protected void Verify(string source, string language, DiagnosticAnalyzer analyzer, IEnumerable<TestAdditionalDocument> additionalFiles, params DiagnosticResult[] expected)
        {
            var diagnostics = GetSortedDiagnostics(new[] { source }.ToFileAndSource(), language, analyzer, additionalFiles: additionalFiles);
            diagnostics.Verify(analyzer, PrintActualDiagnosticsOnFailure, ExpectedDiagnosticsAssertionTemplate, expected);
        }

        private void Verify(string source, string language, DiagnosticAnalyzer analyzer, bool addLanguageSpecificCodeAnalysisReference, TestValidationMode validationMode, params DiagnosticResult[] expected)
        {
            var diagnostics = GetSortedDiagnostics(new[] { source }.ToFileAndSource(), language, analyzer, addLanguageSpecificCodeAnalysisReference: addLanguageSpecificCodeAnalysisReference, validationMode: validationMode);
            diagnostics.Verify(analyzer, PrintActualDiagnosticsOnFailure, ExpectedDiagnosticsAssertionTemplate, expected);
        }

        private void Verify(FileAndSource[] sources, string language, DiagnosticAnalyzer analyzer, TestValidationMode validationMode, bool allowUnsafeCode, params DiagnosticResult[] expected)
        {
            var diagnostics = GetSortedDiagnostics(sources, language, analyzer, validationMode, allowUnsafeCode: allowUnsafeCode);
            diagnostics.Verify(analyzer, PrintActualDiagnosticsOnFailure, ExpectedDiagnosticsAssertionTemplate, expected);
        }

        private static Tuple<Document[], bool, TextSpan?[]> GetDocumentsAndSpans(FileAndSource[] sources, string language, bool addLanguageSpecificCodeAnalysisReference = true, string projectName = TestProjectName, bool allowUnsafeCode = false)
        {
            Assert.True(language == LanguageNames.CSharp || language == LanguageNames.VisualBasic, "Unsupported language");

            var spans = new TextSpan?[sources.Length];
            bool useSpans = false;

            for (int i = 0; i < sources.Length; i++)
            {
                string source;
                int? pos;
                TextSpan? span;
                MarkupTestFile.GetPositionAndSpan(sources[i].Source, out source, out pos, out span);

                sources[i].Source = source;
                spans[i] = span;

                if (span != null)
                {
                    useSpans = true;
                }
            }

            Project project = CreateProject(sources, language, addLanguageSpecificCodeAnalysisReference, null, projectName, allowUnsafeCode);
            Document[] documents = project.Documents.ToArray();
            Assert.Equal(sources.Length, documents.Length);

            return Tuple.Create(documents, useSpans, spans);
        }

        protected static Document CreateDocument(string source, string language = LanguageNames.CSharp, bool addLanguageSpecificCodeAnalysisReference = true, bool allowUnsafeCode = false)
        {
            return CreateProject(new[] { source }.ToFileAndSource(), language, addLanguageSpecificCodeAnalysisReference, allowUnsafeCode: allowUnsafeCode).Documents.First();
        }

        protected static Project CreateProject(string[] sources, string language = LanguageNames.CSharp, bool addLanguageSpecificCodeAnalysisReference = true, Solution addToSolution = null)
        {
            return CreateProject(sources.ToFileAndSource(), language, addLanguageSpecificCodeAnalysisReference, addToSolution);
        }

        private static Project CreateProject(
            FileAndSource[] sources,
            string language = LanguageNames.CSharp,
            bool addLanguageSpecificCodeAnalysisReference = true,
            Solution addToSolution = null,
            string projectName = TestProjectName,
            bool allowUnsafeCode = false)
        {
            string fileNamePrefix = DefaultFilePathPrefix;
            string fileExt = language == LanguageNames.CSharp ? CSharpDefaultFileExt : VisualBasicDefaultExt;
            CompilationOptions options = language == LanguageNames.CSharp
                ? (allowUnsafeCode ? s_CSharpUnsafeCodeDefaultOptions : s_CSharpDefaultOptions)
                : s_visualBasicDefaultOptions;

            ProjectId projectId = ProjectId.CreateNewId(debugName: projectName);

            Project project = (addToSolution ?? new AdhocWorkspace().CurrentSolution)
                .AddProject(projectId, projectName, projectName, language)
                .AddMetadataReference(projectId, s_corlibReference)
                .AddMetadataReference(projectId, s_systemCoreReference)
                .AddMetadataReference(projectId, s_systemXmlReference)
                .AddMetadataReference(projectId, s_systemXmlDataReference)
                .AddMetadataReference(projectId, s_codeAnalysisReference)
                .AddMetadataReference(projectId, SystemRuntimeFacadeRef)
                .AddMetadataReference(projectId, SystemThreadingFacadeRef)
                .AddMetadataReference(projectId, SystemThreadingTaskFacadeRef)
                .AddMetadataReference(projectId, s_immutableCollectionsReference)
                .AddMetadataReference(projectId, s_workspacesReference)
                .AddMetadataReference(projectId, s_systemDiagnosticsDebugReference)
                .AddMetadataReference(projectId, s_systemDataReference)
                .WithProjectCompilationOptions(projectId, options)
                .GetProject(projectId);

            // Enable IOperation Feature on the project
            var parseOptions = project.ParseOptions.WithFeatures(project.ParseOptions.Features.Concat(SpecializedCollections.SingletonEnumerable(KeyValuePair.Create("IOperation", "true"))));
            project = project.WithParseOptions(parseOptions);

            if (addLanguageSpecificCodeAnalysisReference)
            {
                MetadataReference symbolsReference = language == LanguageNames.CSharp ? s_csharpSymbolsReference : s_visualBasicSymbolsReference;
                project = project.AddMetadataReference(symbolsReference);
            }

            if (language == LanguageNames.VisualBasic)
            {
                project = project.AddMetadataReference(s_visualBasicReference);
            }

            int count = 0;
            foreach (FileAndSource source in sources)
            {
                string newFileName = source.FilePath ?? fileNamePrefix + count++ + "." + fileExt;
                DocumentId documentId = DocumentId.CreateNewId(projectId, debugName: newFileName);
                project = project.AddDocument(newFileName, SourceText.From(source.Source)).Project;
            }

            return project;
        }

        protected static Diagnostic[] GetSortedDiagnostics(FileAndSource[] sources, string language, DiagnosticAnalyzer analyzer, TestValidationMode validationMode = DefaultTestValidationMode, bool addLanguageSpecificCodeAnalysisReference = true, bool allowUnsafeCode = false, string projectName = TestProjectName, IEnumerable<TestAdditionalDocument> additionalFiles = null)
        {
            Tuple<Document[], bool, TextSpan?[]> documentsAndUseSpan = GetDocumentsAndSpans(sources, language, addLanguageSpecificCodeAnalysisReference, projectName, allowUnsafeCode);
            Document[] documents = documentsAndUseSpan.Item1;
            bool useSpans = documentsAndUseSpan.Item2;
            TextSpan?[] spans = documentsAndUseSpan.Item3;
            return GetSortedDiagnostics(analyzer, documents, useSpans ? spans : null, validationMode, additionalFiles);
        }

        protected static Diagnostic[] GetSortedDiagnostics(DiagnosticAnalyzer analyzerOpt, Document document, TextSpan?[] spans = null, IEnumerable<TestAdditionalDocument> additionalFiles = null)
        {
            return GetSortedDiagnostics(analyzerOpt, new[] { document }, spans, additionalFiles: additionalFiles);
        }

        protected static Diagnostic[] GetSortedDiagnostics(DiagnosticAnalyzer analyzerOpt, Document[] documents, TextSpan?[] spans = null, TestValidationMode validationMode = DefaultTestValidationMode, IEnumerable<TestAdditionalDocument> additionalFiles = null)
        {
            if (analyzerOpt == null)
            {
                return SpecializedCollections.EmptyArray<Diagnostic>();
            }

            var projects = new HashSet<Project>();
            foreach (Document document in documents)
            {
                projects.Add(document.Project);
            }

            var analyzerOptions = additionalFiles != null ? new AnalyzerOptions(additionalFiles.ToImmutableArray<AdditionalText>()) : null;
            DiagnosticBag diagnostics = DiagnosticBag.GetInstance();
            foreach (Project project in projects)
            {
                Compilation compilation = project.GetCompilationAsync().Result;
                compilation = EnableAnalyzer(analyzerOpt, compilation);

                ImmutableArray <Diagnostic> diags = compilation.GetAnalyzerDiagnostics(new[] { analyzerOpt }, validationMode, analyzerOptions);
                if (spans == null)
                {
                    diagnostics.AddRange(diags);
                }
                else
                {
                    Debug.Assert(spans.Length == documents.Length);
                    foreach (Diagnostic diag in diags)
                    {
                        if (diag.Location == Location.None || diag.Location.IsInMetadata)
                        {
                            diagnostics.Add(diag);
                        }
                        else
                        {
                            for (int i = 0; i < documents.Length; i++)
                            {
                                Document document = documents[i];
                                SyntaxTree tree = document.GetSyntaxTreeAsync().Result;
                                if (tree == diag.Location.SourceTree)
                                {
                                    TextSpan? span = spans[i];
                                    if (span == null || span.Value.Contains(diag.Location.SourceSpan))
                                    {
                                        diagnostics.Add(diag);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            Diagnostic[] results = diagnostics.AsEnumerable().OrderBy(d => d.Location.SourceSpan.Start).ToArray();
            diagnostics.Free();
            return results;
        }

        private static Compilation EnableAnalyzer(DiagnosticAnalyzer analyzer, Compilation compilation)
        {
            return compilation.WithOptions(
                compilation
                    .Options
                    .WithSpecificDiagnosticOptions(
                        analyzer
                            .SupportedDiagnostics
                            .Select(x => KeyValuePair.Create(x.Id, ReportDiagnostic.Default))
                            .ToImmutableDictionaryOrEmpty()));
        }
    }

    // Justification for suppression: We are not going to compare FileAndSource objects for equality.
#pragma warning disable CA1815 // Override equals and operator equals on value types
    public struct FileAndSource
#pragma warning restore CA1815 // Override equals and operator equals on value types
    {
        public string FilePath { get; set; }
        public string Source { get; set; }
    }
}


text:
<?php namespace Flynsarmy\SocialLogin\Components;

use Session;
use URL;
use Cms\Classes\ComponentBase;
use Flynsarmy\SocialLogin\Models\Settings;
use Flynsarmy\SocialLogin\Classes\ProviderManager;
use Illuminate\Support\ViewErrorBag;

class SocialLogin extends ComponentBase
{

	public function componentDetails()
	{
		return [
			'name'        => 'Social Login',
			'description' => 'Adds social_login_link($provider, $success_url, $error_url) method.'
		];
	}

	/**
	 * Executed when this component is bound to a page or layout.
	 */
	public function onRun()
	{
		$providers = ProviderManager::instance()->listProviders();

		// MarkupManager::instance()->registerFunctions([
		// 	function($provider, $success_redirect='/', $error_redirect='/login') {
		// 		$settings = Settings::instance()->getHauthProviderConfig();
		// 		$is_enabled = !empty($settings[$provider]);

		// 		if ( !$is_enabled )
		// 			return '#';

		// 		return ProviderManager::instance()->getBaseURL($provider) .
		// 			'?s=' . URL::to($success_redirect) .
		// 			'&f=' . URL::to($error_redirect);
		// 	}
		// ]);

		$social_login_links = [];
		foreach ( $providers as $provider_class => $provider_details )
			if ( $provider_class::instance()->isEnabled() )
				$social_login_links[$provider_details['alias']] = URL::route('flynsarmy_sociallogin_provider', [$provider_details['alias']]);

		$this->page['social_login_links'] = $social_login_links;

		$this->page['errors'] = Session::get('errors', new ViewErrorBag);
	}
}


text:
<!doctype html>
<title>importScripts(undefined)</title>


text:
Difficulty: Medium

https://leetcode.com/problems/decode-ways/

A message containing letters from A-Z is being encoded to numbers using the following mapping:
```
'A' -> 1
'B' -> 2
...
'Z' -> 26
```
Given a non-empty string containing only digits, determine the total number of ways to decode it.

**Example 1:**
```
Input: "12"
Output: 2
Explanation: It could be decoded as "AB" (1 2) or "L" (12).
```

**Example 2:**
```
Input: "226"
Output: 3
Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
```


text:
@interface CPRegexpRecogniserTest : XCTestCase

@end

@implementation CPRegexpRecogniserTest

- (void)setUp
{
    [super setUp];
    // Put setup code here; it will be run once, before the first test case.
}

- (void)tearDown
{
    // Put teardown code here; it will be run once, after the last test case.
    [super tearDown];
}

- (void)testRecognizeRegexp
{
    NSUInteger position = 0;
    CPRegexpRecogniser* recognizer = [[CPRegexpRecogniser alloc] initWithRegexp:[[NSRegularExpression alloc] initWithPattern:@"[a-z]+" options:0 error:nil]
                                                                       matchHandler:^CPToken *(NSString *tokenString, NSTextCheckingResult *match) {
                                                                           NSString* matchedString = [tokenString substringWithRange:[match range]];
                                                                           return [CPKeywordToken tokenWithKeyword:matchedString];
                                                                       }];
    CPKeywordToken* token = (CPKeywordToken*) [recognizer recogniseTokenInString:@"hello world" currentTokenPosition:&position];
    XCTAssertEqualObjects([token class], [CPKeywordToken class], @"should be keyword token");
    XCTAssertEqualObjects(@"hello", [token keyword], @"should match the string hello");

    position = 5;
    token = (CPKeywordToken*) [recognizer recogniseTokenInString:@"hello world" currentTokenPosition:&position];
    XCTAssertNil(token, @"should not match space");

    position = 6;
    token = (CPKeywordToken*) [recognizer recogniseTokenInString:@"hello world" currentTokenPosition:&position];
    XCTAssertEqualObjects([token class], [CPKeywordToken class], @"should be keyword token");
    XCTAssertEqualObjects(@"world", [token keyword], @"should match the string world");
}

- (void)testReturnNilFromCallbackWillNotSkipContent
{
    NSUInteger position = 0;
    CPRegexpRecogniser* recognizer = [[CPRegexpRecogniser alloc] initWithRegexp:[[NSRegularExpression alloc] initWithPattern:@"[a-z]+" options:0 error:nil]
                                                                       matchHandler:^CPToken *(NSString *tokenString, NSTextCheckingResult *match) {
                                                                           return nil;
                                                                       }];
    CPKeywordToken* token = (CPKeywordToken*) [recognizer recogniseTokenInString:@"hello world" currentTokenPosition:&position];
    XCTAssertNil(token, @"should be nil");
    XCTAssertTrue(position == 0, @"should not skip content if callback return nil");
}

@end


text:
struct reference address;

struct MMUstruct[TLB_SIZE] TLB;

int main(int argc, char const *argv[])
{
    FILE *fp;
    unsigned int Tmem, Ttlb, Tfault;

    fp = fopen("testTrace.txt", "r"); //Name of trace file

    if (fp == NULL) //Check if open worked correctly;
    {
        printf("ERROR OPENING FILE\n");
        exit(EXIT_FAILURE);
    }
    else //file is open.
    {
        Tmem = GetInt(fp);   //Get Initial Values.
        Ttlb = GetInt(fp);   //
        Tfault = GetInt(fp); //

        printf("Tmem: %d, Ttlb: %d, Tfault: %d\n", Tmem, Ttlb, Tfault);

        while ((address.address = GetAddr(fp)) && (address.access = GetType(fp)) && !feof(fp)) // Loop through all addresses and access types, and check address and access type != 0;
        {

            printf("%x ", address.address);
            printf("%c\n", address.access);
        }
    }

    return 0;
}


text:
namespace blink {

class LocalDOMWindow;

// Base controller class for registering controllers with a dispatcher.
// It watches page visibility and calls stopUpdating when page is not visible.
// It provides a DidUpdateData() callback method which is called when new data
// it available.
class CORE_EXPORT PlatformEventController : public PageVisibilityObserver {
 public:
  void StartUpdating();
  void StopUpdating();

  // This is called when new data becomes available.
  virtual void DidUpdateData() = 0;

  void Trace(Visitor*) const override;
  LocalDOMWindow& GetWindow() const { return *window_; }

 protected:
  explicit PlatformEventController(LocalDOMWindow&);
  virtual ~PlatformEventController();

  virtual void RegisterWithDispatcher() = 0;
  virtual void UnregisterWithDispatcher() = 0;

  // When true initiates a one-shot DidUpdateData() when StartUpdating() is
  // called.
  virtual bool HasLastData() = 0;

  bool has_event_listener_;

 private:
  // Inherited from PageVisibilityObserver.
  void PageVisibilityChanged() override;

  void UpdateCallback();

  bool is_active_;
  Member<LocalDOMWindow> window_;
  TaskHandle update_callback_handle_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_PLATFORM_EVENT_CONTROLLER_H_


text:
'use strict';

import * as React from 'react';
import Platform from '../Utilities/Platform';
import StyleSheet, {type ColorValue} from '../StyleSheet/StyleSheet';
import Text from '../Text/Text';
import TouchableNativeFeedback from './Touchable/TouchableNativeFeedback';
import TouchableOpacity from './Touchable/TouchableOpacity';
import View from './View/View';
import invariant from 'invariant';

import type {AccessibilityState} from './View/ViewAccessibility';
import type {PressEvent} from '../Types/CoreEventTypes';

type ButtonProps = $ReadOnly<{|
  /**
    Text to display inside the button. On Android the given title will be
    converted to the uppercased form.
   */
  title: string,

  /**
    Handler to be called when the user taps the button. The first function
    argument is an event in form of [PressEvent](pressevent).
   */
  onPress: (event?: PressEvent) => mixed,

  /**
    If `true`, doesn't play system sound on touch.

    @platform android

    @default false
   */
  touchSoundDisabled?: ?boolean,

  /**
    Color of the text (iOS), or background color of the button (Android).

    @default {@platform android} '#2196F3'
    @default {@platform ios} '#007AFF'
   */
  color?: ?ColorValue,

  /**
    TV preferred focus.

    @platform tv

    @default false
   */
  hasTVPreferredFocus?: ?boolean,

  /**
    Designates the next view to receive focus when the user navigates down. See
    the [Android documentation][android:nextFocusDown].

    [android:nextFocusDown]:
    https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusDown

    @platform android, tv
   */
  nextFocusDown?: ?number,

  /**
    Designates the next view to receive focus when the user navigates forward.
    See the [Android documentation][android:nextFocusForward].

    [android:nextFocusForward]:
    https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusForward

    @platform android, tv
   */
  nextFocusForward?: ?number,

  /**
    Designates the next view to receive focus when the user navigates left. See
    the [Android documentation][android:nextFocusLeft].

    [android:nextFocusLeft]:
    https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusLeft

    @platform android, tv
   */
  nextFocusLeft?: ?number,

  /**
    Designates the next view to receive focus when the user navigates right. See
    the [Android documentation][android:nextFocusRight].

    [android:nextFocusRight]:
    https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusRight

    @platform android, tv
   */
  nextFocusRight?: ?number,

  /**
    Designates the next view to receive focus when the user navigates up. See
    the [Android documentation][android:nextFocusUp].

    [android:nextFocusUp]:
    https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusUp

    @platform android, tv
   */
  nextFocusUp?: ?number,

  /**
    Text to display for blindness accessibility features.
   */
  accessibilityLabel?: ?string,

  /**
    If `true`, disable all interactions for this component.

    @default false
   */
  disabled?: ?boolean,

  /**
    Used to locate this view in end-to-end tests.
   */
  testID?: ?string,

  /**
   * Accessibility props.
   */
  accessibilityState?: ?AccessibilityState,
|}>;

/**
  A basic button component that should render nicely on any platform. Supports a
  minimal level of customization.

  If this button doesn't look right for your app, you can build your own button
  using [TouchableOpacity](touchableopacity) or
  [TouchableWithoutFeedback](touchablewithoutfeedback). For inspiration, look at
  the [source code for this button component][button:source]. Or, take a look at
  the [wide variety of button components built by the community]
  [button:examples].

  [button:source]:
  https://github.com/facebook/react-native/blob/master/Libraries/Components/Button.js

  [button:examples]:
  https://js.coach/?menu%5Bcollections%5D=React%20Native&page=1&query=button

  ```jsx
  <Button
    onPress={onPressLearnMore}
    title="Learn More"
    color="#841584"
    accessibilityLabel="Learn more about this purple button"
  />
  ```

  ```SnackPlayer name=Button%20Example
  import React from 'react';
  import { StyleSheet, Button, View, SafeAreaView, Text, Alert } from 'react-native';

  const Separator = () => (
    <View style={styles.separator} />
  );

  const App = () => (
    <SafeAreaView style={styles.container}>
      <View>
        <Text style={styles.title}>
          The title and onPress handler are required. It is recommended to set accessibilityLabel to help make your app usable by everyone.
        </Text>
        <Button
          title="Press me"
          onPress={() => Alert.alert('Simple Button pressed')}
        />
      </View>
      <Separator />
      <View>
        <Text style={styles.title}>
          Adjust the color in a way that looks standard on each platform. On  iOS, the color prop controls the color of the text. On Android, the color adjusts the background color of the button.
        </Text>
        <Button
          title="Press me"
          color="#f194ff"
          onPress={() => Alert.alert('Button with adjusted color pressed')}
        />
      </View>
      <Separator />
      <View>
        <Text style={styles.title}>
          All interaction for the component are disabled.
        </Text>
        <Button
          title="Press me"
          disabled
          onPress={() => Alert.alert('Cannot press this one')}
        />
      </View>
      <Separator />
      <View>
        <Text style={styles.title}>
          This layout strategy lets the title define the width of the button.
        </Text>
        <View style={styles.fixToText}>
          <Button
            title="Left button"
            onPress={() => Alert.alert('Left button pressed')}
          />
          <Button
            title="Right button"
            onPress={() => Alert.alert('Right button pressed')}
          />
        </View>
      </View>
    </SafeAreaView>
  );

  const styles = StyleSheet.create({
    container: {
      flex: 1,
      justifyContent: 'center',
      marginHorizontal: 16,
    },
    title: {
      textAlign: 'center',
      marginVertical: 8,
    },
    fixToText: {
      flexDirection: 'row',
      justifyContent: 'space-between',
    },
    separator: {
      marginVertical: 8,
      borderBottomColor: '#737373',
      borderBottomWidth: StyleSheet.hairlineWidth,
    },
  });

  export default App;
  ```
 */

class Button extends React.Component<ButtonProps> {
  render(): React.Node {
    const {
      accessibilityLabel,
      color,
      onPress,
      touchSoundDisabled,
      title,
      hasTVPreferredFocus,
      nextFocusDown,
      nextFocusForward,
      nextFocusLeft,
      nextFocusRight,
      nextFocusUp,
      testID,
    } = this.props;
    const buttonStyles = [styles.button];
    const textStyles = [styles.text];
    if (color) {
      if (Platform.OS === 'ios') {
        textStyles.push({color: color});
      } else {
        buttonStyles.push({backgroundColor: color});
      }
    }

    const disabled =
      this.props.disabled != null
        ? this.props.disabled
        : this.props.accessibilityState?.disabled;

    const accessibilityState =
      disabled !== this.props.accessibilityState?.disabled
        ? {...this.props.accessibilityState, disabled}
        : this.props.accessibilityState;

    if (disabled) {
      buttonStyles.push(styles.buttonDisabled);
      textStyles.push(styles.textDisabled);
    }

    invariant(
      typeof title === 'string',
      'The title prop of a Button must be a string',
    );
    const formattedTitle =
      Platform.OS === 'android' ? title.toUpperCase() : title;
    const Touchable =
      Platform.OS === 'android' ? TouchableNativeFeedback : TouchableOpacity;

    return (
      <Touchable
        accessibilityLabel={accessibilityLabel}
        accessibilityRole="button"
        accessibilityState={accessibilityState}
        hasTVPreferredFocus={hasTVPreferredFocus}
        nextFocusDown={nextFocusDown}
        nextFocusForward={nextFocusForward}
        nextFocusLeft={nextFocusLeft}
        nextFocusRight={nextFocusRight}
        nextFocusUp={nextFocusUp}
        testID={testID}
        disabled={disabled}
        onPress={onPress}
        touchSoundDisabled={touchSoundDisabled}>
        <View style={buttonStyles}>
          <Text style={textStyles} disabled={disabled}>
            {formattedTitle}
          </Text>
        </View>
      </Touchable>
    );
  }
}

const styles = StyleSheet.create({
  button: Platform.select({
    ios: {},
    android: {
      elevation: 4,
      // Material design blue from https://material.google.com/style/color.html#color-color-palette
      backgroundColor: '#2196F3',
      borderRadius: 2,
    },
  }),
  text: {
    textAlign: 'center',
    margin: 8,
    ...Platform.select({
      ios: {
        // iOS blue from https://developer.apple.com/ios/human-interface-guidelines/visual-design/color/
        color: '#007AFF',
        fontSize: 18,
      },
      android: {
        color: 'white',
        fontWeight: '500',
      },
    }),
  },
  buttonDisabled: Platform.select({
    ios: {},
    android: {
      elevation: 0,
      backgroundColor: '#dfdfdf',
    },
  }),
  textDisabled: Platform.select({
    ios: {
      color: '#cdcdcd',
    },
    android: {
      color: '#a1a1a1',
    },
  }),
});

module.exports = Button;