text:
const transform = (obj, fn) => {
  return Object.keys(obj).reduce(
    (next, key) => {
      next[key] = fn(obj[key]);
      return next;
    },
    {}
  );
};

export const conduit = {
  input(argsFn) {
    this.argsFn = argsFn;
    return this;
  },

  source(sourceFn) {
    this.sourceFn = sourceFn;
    return this;
  },

  output(onChangeFn) {
    const { argsFn, sourceFn } = this;
    const argsR = argsFn
      ? transform(argsFn(), value => new ReactiveVar(value))
      : {};

    let response;

    const c = Tracker.autorun(() => {
      response = sourceFn(
        transform(argsR, value => value.get())
      );
      onChangeFn(response);
    });

    return {
      stop(cleanupFn) {
        if (cleanupFn) {
          cleanupFn(response);
        }
        c.stop();
      },
      update() {
        const args = argsFn();
        return Object.keys(argsR).forEach(
          key => argsR[key].set(args[key])
        );
      }
    };
  }
};


text:
<?php
use ImmutableStateStatusTracker\Controller\ISSTController;
use ImmutableStateStatusTracker\Factory\ISSTControllerFactory;
return array(
    'service_manager' => array(
        'factories' => array(
            'immutable-state-status-tracker' => '\ImmutableStateStatusTracker\Factory\ImmutableStateStatusFactory'
        )
    ),
    'controllers' => array(
        'factories' => array(
            ISSTController::class => ISSTControllerFactory::class
        )
    ),

    'console' => array(
        'router' => array(
            'routes' => array(
                'isst-clean' => array(
                    'type' => 'simple',
                    'options' => array(
                        'route' => 'isst:clean <num_days>',
                        'defaults' => array(
                            '__NAMESPACE__' => 'ImmutableStateStatusTracker\Controller',
                            'controller' => 'ISSTController',
                            'action' => 'clean'
                        )
                    )
                )
            )
        )
    )
);

redpajama_set_name: RedPajamaGithub


text:
    title: "2. Das Angular-CLI: professionelle Projektorganisation für Angular-Projekte"

---

Eine der größten Stärken des JavaScript-Ökosystems ist gleichzeitig auch eine seiner größten Schwächen: Die Masse an verfügbaren Tools und Möglichkeiten ist schier unendlich. Das Angular-CLI sagt dieser Unübersichtlichkeit den Kampf an.

In diesem Kapitel werden Sie lernen, wie Sie das CLI verwenden können, um damit Folgendes zu tun:
- ein voll funktionales Applikationsgerüst erstellen
- Komponenten, Services, Pipes und vieles mehr generieren
- die Applikation und Tests ausführen
- die Angular-Version updaten
- Projektabhängigkeit hinzufügen
- einen Produktionsbuild über webpack erstellen
- einen CSS-Präprozessor wie Sass, Less oder Stylus integrieren


text:
{{<layout}}

{{$pageTitle}}
	GOV.UK payment page
{{/pageTitle}}

{{$content}}

		◀ Back

Take this barcode to a PayPoint store

A link to the barcode has been sent to your mobile phone

					 Find your nearest PayPoint store

						Enter a postcode
			  			<input class="form-control" id="phone-number" type="text" placeholder="WC1A 2SA">

You'll get a receipt from the shopkeeper when you pay.

 Send me this barcode

We can send you this barcode by email or text message. We'll also send you a confirmation when you've paid.

We won't spam you or use your contact details for anything else.

			<fieldset>

				Email address

			  	<input class="form-control" id="email-address" type="text">
			  	<button class="button-grey">Send</button>

				Mobile phone number

			  	<input class="form-control" id="phone-number" type="text">
			  	<button class="button-grey">Send</button>

			</fieldset>

Print this barcode now

Download the barcode (PDF)

Payment summary

Partner on the 5 or 10 year route visa

Amount to pay:

 £1415.00

	 			<button class="button">Continue</button>

{{/content}}

{{/layout}}


text:
const BaseChecker = require('./../base-checker');

class ExplicitVisibilityChecker extends BaseChecker {

    constructor(reporter) {
        super(reporter);
    }

    exitModifierList(ctx) {
        const text = ctx.getText();

        const hasInternal = text.includes('internal');
        const hasExternal = text.includes('external');
        const hasPrivate = text.includes('private');
        const hasPublic = text.includes('public');

        if (!hasExternal && !hasInternal && !hasPrivate && !hasPublic) {
            this.warn(ctx, 'func-visibility', 'Explicitly mark visibility in function');
        }
    }

    exitStateVariableDeclaration(ctx) {
        const text = ctx.getText();

        const hasInternal = text.includes('internal');
        const hasPrivate = text.includes('private');
        const hasPublic = text.includes('public');

        if (!hasInternal && !hasPrivate && !hasPublic) {
            this.warn(ctx, 'state-visibility', 'Explicitly mark visibility of state');
        }
    }

}

module.exports = ExplicitVisibilityChecker;


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!--
 Copyright (c) 2002-2008 International Business Machines Corporation and others. All rights reserved.
-->
<!DOCTYPE ldml SYSTEM "http://www.unicode.org/cldr/dtd/1.6/ldml.dtd"
[
   <!ENTITY % icu SYSTEM " http://www.unicode.org/cldr/dtd/1.6/ldmlICU.dtd">
   %icu;
]
>
<ldml>
	<identity>
		<version number="$Revision: 1.19 $"/>
		<generation date="$Date: 2008/05/25 01:05:50 $"/>
		<language type="pa"/>
		<territory type="PK"/>
	</identity>
</ldml>


text:
<?xml version="1.0" encoding="utf-8"?>
<browserconfig>
    <msapplication>
        <tile>
            <square150x150logo src="/images/favicon/favicon-ozar/mstile-150x150.png"/>
            <TileColor>#00a300</TileColor>
        </tile>
    </msapplication>
</browserconfig>


text:
<html>
<meta http-equiv="Cache-Control" content="no-store" />
<head>
<title>Stock Quote Connector</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script src="https://connectors.tableau.com/libs/tableauwdc-1.1.1.js" type="text/javascript"></script>
<script type="text/javascript">
 (function() {

  //
  // Helper functions
  //

  // Takes a ticker symbol, a start date and an end date, and constructs a URL for the Yahoo! stock quote API
  function buildUrl(tickerSymbol, startDate, endDate) {
    var startDateStr = getDateAsString(startDate);
    var endDateStr = getDateAsString(endDate);
    var data = 'select * from yahoo.finance.historicaldata where symbol = "' + tickerSymbol + '" and startDate = "' + startDateStr
        + '" and endDate = "' + endDateStr + '"';
    var url = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(data) + "&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json";
    return url;
  }

  // Gets a string representation of a date that can be used with the Yahoo! API.
  function getDateAsString(date) {
    return date.getUTCFullYear()  + '-' + makeTwoDigits(date.getUTCMonth() + 1) + '-' + makeTwoDigits(date.getUTCDate());
  }

  // Pads a given number with leading 0s so that there are two characters in the string. Example: makeTwoDigits(1) --> "01"
  function makeTwoDigits(num) {
    return num < 9 ? "0" + num.toString() : num.toString();
  }

  //
  // Connector definition
  //

  var myConnector = tableau.makeConnector();

  myConnector.getColumnHeaders = function() {
    var fieldNames = ['Ticker', 'Day', 'Close'];
    var fieldTypes = ['string', 'date', 'float'];
    tableau.headersCallback(fieldNames, fieldTypes); // tell tableau about the fields and their types
  };

  myConnector.getTableData = function(lastRecordToken) {
    var endDate = new Date();
    var ticker = tableau.connectionData;
    var startDate = new Date();
    // set the start of the range to be 1 year ago
    startDate.setYear(endDate.getFullYear() - 1);

    var connectionUrl = buildUrl(ticker, startDate, endDate);
    var xhr = $.ajax({
        url: connectionUrl,
        dataType: 'json',
        success: function (data) {
            if (data.query.results) {
              var quotes = data.query.results.quote;
              var ii;
              var toRet = [];
              // mash the data into an array of objects
              for (ii = 0; ii < quotes.length; ++ii) {
                  // Each entry can be a list of values in the same order as the columns
                  //var entry = [quotes[ii].Symbol, quotes[ii].Date, quotes[ii].Close];
                  // or an object where the column names are the keys of the map
                  var entry = {'Ticker': quotes[ii].Symbol,
                               'Day': quotes[ii].Date,
                               'Close': quotes[ii].Close};
                  toRet.push(entry);
              }
              // Call back to tableau with the table data and the new record number (this is stored as a string)
              tableau.dataCallback(toRet, toRet.length.toString(), false);
            } else {
              tableau.abortWithError("No results found for ticker symbol: " + ticker);
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
          // add something to the log and return an empty set if there was problem with the connection
          tableau.log("connection error: " + xhr.responseText + "\n" + thrownError);
          tableau.abortWithError("error connecting to the yahoo stock data source");
        }
    });
  };

  myConnector.setTicker = function(tickerSymbol) {
    tableau.connectionData = tickerSymbol; // set the ticker symbol as the connection data so we can get to it when we fetch the data
    tableau.connectionName = 'Stock quote: ' + tickerSymbol; // name the data source. This will be the data source name in Tableau
  };

  tableau.registerConnector(myConnector);

  //
  // Setup connector UI
  //

  $(document).ready(function() {
    $("#submitButton").click(function() { // This event fires when a button is clicked
      var tickerSymbol = $('input[type=text]').val().trim();
      if (tickerSymbol) {
        myConnector.setTicker(tickerSymbol);
        tableau.submit();
      }
    });
  });

})();
</script>
</head>
<body>
  Enter a ticker symbol: <input type="text" name="ticker" style="width: 150px;" />
  <br>
  <button type="button" id="submitButton">Get Stock Data</button>
</body>
</html>


text:
function fValConfig()
{
	/*	Globals.  Modify these to suit your setup
	------------------------------------------- */

	//	Attribute used for fValidate Validator codes
	this.code = 'alt';

	//	Attribute used for custom error messages (override built-in error messages)
	this.emsg = 'emsg';

	//	Attribute used for pattern with custom validator type
	this.pattern = 'pattern';

	//	Change this to the classname you want for the error highlighting
	this.errorClass = 'errHilite';

	//	If you wish fValidate to use only single classNames for errors
	this.useSingleClassNames = false; // or true

	//	This is the even that triggers the clearing of the errorClass hilighting
	this.clearEvent = 'change'; // 'change' | 'blur' | null

	//	For browsers that don't support attachEvent or addEventListere - override existing events for error reverting?
	this.eventOverride = false;

	//	If the bConfirm flag is set to true, the users will be prompted with CONFIRM box with this message
	//	See your language file for this value
	this.confirmMsg = fvalidate.i18n.config.confirmMsg;

	//	If user cancels CONFIRM, then this message will be alerted.  If you don't want this alert to show, then
	//	empty the variable (  this.confirmAbortMsg = '';  )
	//	See your langauge file for this value
	this.confirmAbortMsg = fvalidate.i18n.config.confirmAbortMsg;

	//	Enter the name/id of your form's submit button here.  Can be a string or array of strings
	this.submitButton = ['Submit','Submit2'];

	//	Enter the name/id of your form's reset button here
	this.resetButton = 'Reset';

	//	Ender the name or id of the SELECT object here. Make sure you pay attention to the values (CC Types)
	//	used in the case statement for the function validateCC()
	this.ccType = 'Credit_Card_Type';

	//	NOTE: The config value below exists for backwards compatibility with fValidate 3.55b.  If you have a newer
	//	version, use the above this.ccType instead.
	//	Enter the DOM name of the SELECT object here. Make sure you pay attention to the values (CC Types)
	//	used in the case statement for the function validateCC()
	this.ccTypeObj = 'form1.Credit_Card_Type';

	//	Element where box errors will appear
	this.boxError = 'errors';

	//	Prefix given to all error paragraphs in box error mode
	this.boxErrorPrefix = 'fv_error_';
}
//	EOF


text:
using System;

using UIKit;

namespace CustomTransitions {
	public partial class CDSecondViewController : UIViewController {
		public CDSecondViewController (IntPtr handle) : base (handle)
		{
		}

		partial void DismissAction(UIButton sender)
		{
			DismissViewController (true, null);
		}
	}
}


text:
module Pohoda
  module Builders
    module SEET
      class RecordSendEETType
        include ParserCore::BaseBuilder
        include Ftr::Groups::GroupFilter1

        def builder
          root = Ox::Element.new(name)
          root = add_attributes_and_namespaces(root)

          mega.each do |r|
            r.nodes.each { |n| root << n }
          end

          root
        end
      end
    end
  end
end


text:
require 'lims-core/actions/action'
require 'lims-laboratory-app/organization/batch'

module Lims::LaboratoryApp
  module Organization
    class Batch
      class CreateBatch
        include Lims::Core::Actions::Action

        attribute :process, String, :required => false, :writer => :private
        attribute :kit, String, :required => false, :writer => :private

        def _call_in_session(session)
          batch = Batch.new({
              :process => process,
              :kit => kit
            })
          session << batch
          {:batch => batch, :uuid => session.uuid_for!(batch)}
        end

      end
    end
    class Batch
      Create = CreateBatch
    end
  end
end


text:
ALTER TABLE object_xref
  DROP INDEX object_type_idx,
  ADD UNIQUE INDEX
    object_type_idx (ensembl_object_type, ensembl_id, xref_id, analysis_id);

ANALYZE TABLE object_xref;

# Insert patch identifier.
INSERT INTO meta (species_id, meta_key, meta_value)
  VALUES (NULL, 'patch',
    'patch_58_59_d.sql|object_xref_extend_index');


text:
from __future__ import unicode_literals

from django.db import models, migrations
import datetime

class Migration(migrations.Migration):

    dependencies = [
        ('pacientes', '0009_auto_20150505_0055'),
    ]

    operations = [
        migrations.AlterField(
            model_name='pacientes',
            name='fecha_ingreso',
            field=models.DateField(default=datetime.datetime(2015, 5, 5, 0, 56, 59, 512000), help_text='Formato: dd/mm/yyyy', verbose_name='Fecha de Ingreso'),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='pacientes',
            name='hora_ingreso',
            field=models.TimeField(default=datetime.datetime(2015, 5, 5, 0, 56, 59, 511946), help_text='Formato: hh:mm', verbose_name='Hora de Ingreso'),
            preserve_default=True,
        ),
    ]


text:
package com.xmlcalabash.model;

import net.sf.saxon.s9api.XdmNode;
import com.xmlcalabash.core.XProcRuntime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author ndw
 */
public class ErrorBinding extends Binding {
    /* Creates a new instance of EmptyBinding */
    public ErrorBinding() {
        super(null,null);
        bindingType = ERROR_BINDING;
    }

    public ErrorBinding(XProcRuntime xproc, XdmNode node) {
        super(xproc, node);
        bindingType = ERROR_BINDING;
    }

    protected void dump(int depth) {
        String indent = "";
        for (int count = 0; count < depth; count++) {
            indent += " ";
        }

        logger.trace(indent + "Error binding");
    }
}


text:
function(doc, req){
  return { code : 301, headers : { "Location" : 'http://liblib.com/dialog' } };
}


text:
using BlueSheep.Common.IO;
using BlueSheep.Common.Protocol.Messages;
using BlueSheep.Common.Protocol.Types;
using BlueSheep.Engine.Types;
using BlueSheep.Interface;

namespace BlueSheep.Core.Storage
{
    class Opening
    {
        #region Public methods
        public void Init(AccountUC account)
        {
            int skillUID = 0;

            foreach (InteractiveElementSkill skill in account.Safe.enabledSkills)
            {
                if (skill.skillId == 104)
                {
                    skillUID = skill.skillInstanceUid;

                    break;
                }
            }

            InteractiveUseRequestMessage interactiveUseRequestMessage = new InteractiveUseRequestMessage(
                account.Safe.elementId,
                skillUID);

            using (BigEndianWriter writer = new BigEndianWriter())
            {
                interactiveUseRequestMessage.Serialize(writer);
                writer.Content = account.HumanCheck.hash_function(writer.Content);
                MessagePackaging messagePackaging = new MessagePackaging(writer);

                messagePackaging.Pack((int)interactiveUseRequestMessage.ProtocolID);

                account.SocketManager.Send(messagePackaging.Writer.Content);
                account.LastPacketID.Clear();
                if (account.DebugMode.Checked)
                    account.Log(new BlueSheep.Interface.Text.DebugTextInformation("[SND] 5001 (InteractiveUseRequestMessage)"), 0);
            }
        }
        #endregion
    }
}


text: exports.SrcdsRconService = require('./SrcdsRconService')


text:
export class Cell {
  public x: number;
  public y: number;
  public populated: boolean;

  constructor(x: number, y: number, populated: boolean) {
    this.x = x;
    this.y = y;
    this.populated = populated;
  }
}


text:
package org.springframework.cloud.dataflow.server.local.security;

import org.junit.ClassRule;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;

import org.springframework.cloud.dataflow.server.single.LocalDataflowResource;

import static org.springframework.cloud.dataflow.server.single.security.SecurityTestUtils.basicAuthorizationHeader;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * @author Marius Bogoevici
 * @author Gunnar Hillert
 */
@Ignore("Ignored until proper UAA integration exists") //FIXME see https://github.com/spring-cloud/spring-cloud-dataflow/issues/2580
public class LocalServerSecurityWithLdapSearchAndBindTests {

	private final static LocalDataflowResource localDataflowResource = new LocalDataflowResource(
			"classpath:org/springframework/cloud/dataflow/server/local/security" + "/ldapSearchAndBind.yml");

	@ClassRule
	public static TestRule springDataflowAndLdapServer = RuleChain.outerRule(new LdapServerResource())
			.around(localDataflowResource);

	@Test
	public void testUnauthenticatedAccessToModulesEndpointFails() throws Exception {
		localDataflowResource.getMockMvc().perform(get("/apps")).andExpect(status().isUnauthorized());
	}

	@Test
	public void testUnauthenticatedAccessToManagementEndpointFails() throws Exception {
		localDataflowResource.getMockMvc().perform(get("/management/metrics")).andExpect(status().isUnauthorized());
	}

	@Test
	public void testAuthenticatedAccessToModulesEndpointSucceeds() throws Exception {
		localDataflowResource.getMockMvc()
				.perform(get("/apps").header("Authorization", basicAuthorizationHeader("joe", "joespassword")))
				.andDo(print()).andExpect(status().isOk());
	}

	@Test
	public void testUserExistsButNotFoundBySearch() throws Exception {
		localDataflowResource.getMockMvc()
				.perform(get("/apps").header("Authorization", basicAuthorizationHeader("bob", "bobspassword")))
				.andDo(print()).andExpect(status().isUnauthorized());
	}

	// TODO: BOOT2, handle this test when we have something from micrometrics
	//	@Test
	//	public void testAuthenticatedAccessToManagementEndpointSucceeds() throws Exception {
	//		localDataflowResource.getMockMvc().perform(
	//				get("/management/metrics").header("Authorization", basicAuthorizationHeader("joe", "joespassword")))
	//				.andDo(print()).andExpect(status().isOk());
	//	}
}


text:
const Action = require('./Action');
const { Events } = require('../../util/Constants');

class MessageCreateAction extends Action {
  handle(data) {
    const client = this.client;
    const channel = client.channels.get(data.channel_id);
    if (channel) {
      const existing = channel.messages.get(data.id);
      if (existing) return { message: existing };
      const message = channel.messages.add(data);
      const user = message.author;
      const member = channel.guild ? channel.guild.member(user) : null;
      channel.lastMessageID = data.id;
      if (user) {
        user.lastMessageID = data.id;
        user.lastMessageChannelID = channel.id;
      }
      if (member) {
        member.lastMessageID = data.id;
        member.lastMessageChannelID = channel.id;
      }

      client.emit(Events.MESSAGE_CREATE, message);
      return { message };
    }

    return {};
  }
}

/**
 * Emitted whenever a message is created.
 * @event Client#message
 * @param {Message} message The created message
 */

module.exports = MessageCreateAction;


text:
<?php

namespace Eloquent\Phuri\SchemeSpecific\Mailto\Validation;

use Eloquent\Liberator\Liberator;
use PHPUnit_Framework_TestCase;

class EmailAddressValidatorTest extends PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        parent::setUp();

        $this->validator = new EmailAddressValidator;
    }

    public function addressData()
    {
        //                                             address                                                                       isValid
        return array(
            'Typical email address'           => array('eloquent@example.org',                                                       true),
            'Domain literal'                  => array('eloquent@[2620:0:1cfe:face:b00c::3]',                                        true),
            'Quoted string'                   => array('"eloquent"@example.org',                                                     true),
            'UTF-8 local-part'                => array("\xE7\xB4\x8D\xE8\xB1\x86@example.org",                                       true),
            'UTF-8 quoted local-part'         => array("\"\xE7\xB4\x8D\xE8\xB1\x86\"@example.org",                                   true),
            'UTF-8 domain'                    => array("eloquent@\xE7\xB4\x8D\xE8\xB1\x86.\xE7\xB4\x8D\xE8\xB1\x86",                 true),
            'UTF-8 domain literal'            => array("eloquent@[\xE7\xB4\x8D\xE8\xB1\x86]",                                        true),
            'UTF-8 everywhere'                => array("\xE7\xB4\x8D\xE8\xB1\x86@\xE7\xB4\x8D\xE8\xB1\x86.\xE7\xB4\x8D\xE8\xB1\x86", true),

            'RFC 6068 example 1'              => array('chris@example.com',                                                          true),
            'RFC 6068 example 2'              => array('infobot@example.com',                                                        true),
            'RFC 6068 example 5'              => array('list@example.org',                                                           true),
            'RFC 6068 example 6'              => array('majordomo@example.com',                                                      true),
            'RFC 6068 example 7'              => array('joe@example.com',                                                            true),
            'RFC 6068 example 9'              => array('gorby%kremvax@example.com',                                                  true),
            'RFC 6068 example 10'             => array('unlikely?address@example.com',                                               true),
            'RFC 6068 example 12'             => array('Mike&family@example.org',                                                    true),
            'RFC 6068 example 13'             => array('"not@me"@example.org',                                                       true),
            'RFC 6068 example 14'             => array('"oh\\\no"@example.org',                                                      true),
            'RFC 6068 example 15'             => array('"\\\\\"it\'s\ ugly\\\\\""@example.org',                                      true),
            'RFC 6068 example 16'             => array('user@example.org',                                                           true),
            'RFC 6068 example 20'             => array("user@\xE7\xB4\x8D\xE8\xB1\x86.example.org",                                  true),

            'Zend valid example 1'            => array('username@example.com',                                                       true),
            'Zend valid example 2'            => array('username@localhost',                                                         true),
            'Zend valid example 3'            => array('username@localhost.localdomain',                                             true),
            'Zend valid example 4'            => array('bob@212.212.20.4',                                                           true),
            'Zend valid example 5'            => array('"Some User"@example.com',                                                    true),
            'Zend valid example 6'            => array('""@domain.com',                                                              true),
            'Zend valid example 7'            => array('" "@domain.com',                                                             true),
            'Zend valid example 8'            => array('"!"@domain.com',                                                             true),
            'Zend valid example 9'            => array('"\""@domain.com',                                                            true),
            'Zend valid example 10'           => array('"#"@domain.com',                                                             true),
            'Zend valid example 11'           => array('"$"@domain.com',                                                             true),
            'Zend valid example 12'           => array('"Z"@domain.com',                                                             true),
            'Zend valid example 13'           => array('"["@domain.com',                                                             true),
            'Zend valid example 14'           => array('"\\\"@domain.com',                                                           true),
            'Zend valid example 15'           => array('"]"@domain.com',                                                             true),
            'Zend valid example 16'           => array('"^"@domain.com',                                                             true),
            'Zend valid example 17'           => array('"}"@domain.com',                                                             true),
            'Zend valid example 18'           => array('"~"@domain.com',                                                             true),
            'Zend valid example 19'           => array('"username"@example.com',                                                     true),
            'Zend valid example 20'           => array('"bob%jones"@domain.com',                                                     true),
            'Zend valid example 21'           => array('"bob jones"@domain.com',                                                     true),
            'Zend valid example 22'           => array('"bob@jones"@domain.com',                                                     true),
            'Zend valid example 23'           => array('"[[ bob ]]"@domain.com',                                                     true),
            'Zend valid example 24'           => array('"jones"@domain.com',                                                         true),
            'Zend valid example 25'           => array('bob@domain.com',                                                             true),
            'Zend valid example 26'           => array('bob.jones@domain.co.uk',                                                     true),
            'Zend valid example 27'           => array('bob.jones.smythe@domain.co.uk',                                              true),
            'Zend valid example 28'           => array('BoB@domain.museum',                                                          true),
            'Zend valid example 29'           => array('bobjones@domain.info',                                                       true),
            'Zend valid example 30'           => array("B.O'Callaghan@domain.com",                                                   true),
            'Zend valid example 31'           => array('bob+jones@domain.us',                                                        true),
            'Zend valid example 32'           => array('bob+jones@domain.co.uk',                                                     true),
            'Zend valid example 33'           => array('bob@some.domain.uk.com',                                                     true),
            'Zend valid example 34'           => array('bob@verylongdomainsupercalifragilisticexpialidociousspoonfulofsugar.com',    true),
            'Zend valid example 35'           => array('Bob.Jones@domain.com',                                                       true),
            'Zend valid example 36'           => array('Bob.Jones!@domain.com',                                                      true),
            'Zend valid example 37'           => array('Bob&Jones@domain.com',                                                       true),
            'Zend valid example 38'           => array('/Bob.Jones@domain.com',                                                      true),
            'Zend valid example 39'           => array('#Bob.Jones@domain.com',                                                      true),
            'Zend valid example 40'           => array('Bob.Jones?@domain.com',                                                      true),
            'Zend valid example 41'           => array('Bob~Jones@domain.com',                                                       true),

            'Invalid - non-string'            => array(array(),                                                                      false),
            'Too many parts'                  => array('eloquent@gmail@com',                                                         false),
            'Invalid domain'                  => array('eloquent@<example.org>',                                                     false),
            'Invalid local-part'              => array('<eloquent>@example.org',                                                     false),
            'Missing domain'                  => array('eloquent@',                                                                  false),
            'Missing local-part'              => array('@example.org',                                                               false),
            'Invalid UTF-8 local-part'        => array("\xE7@example.org",                                                           false),
            'Invalid UTF-8 quoted local-part' => array("\"\xE7\"@example.org",                                                       false),
            'Invalid UTF-8 domain'            => array("eloquent@\xE7\xB4\x8D\xE8\xB1\x86.\xE7",                                     false),
            'Invalid UTF-8 domain literal'    => array("eloquent@[\xE7]",                                                            false),
            'Semicolon in local-part'         => array('elo;quent@example.org',                                                      false),
            'Semicolon in domain'             => array('eloquent@exam;ple.org',                                                      false),

            'Zend invalid example 1'          => array('@example.com',                                                               false),
            'Zend invalid example 2'          => array('Some User@example.com',                                                      false),
            'Zend invalid example 3'          => array('username@ example . com',                                                    false),
            'Zend invalid example 4'          => array("\"\x00\"@example.com",                                                       false),
            'Zend invalid example 5'          => array("\"\x01\"@example.com",                                                       false),
            'Zend invalid example 6'          => array("\"\x1E\"@example.com",                                                       false),
            'Zend invalid example 7'          => array("\"\x1F\"@example.com",                                                       false),
            'Zend invalid example 8'          => array('"""@example.com',                                                            false),
            'Zend invalid example 9'          => array('"\"@example.com',                                                            false),
            'Zend invalid example 10'         => array("\"\x7F\"@example.com",                                                       true),  // deviation from Zend
            'Zend invalid example 11'         => array('User Name <username@example.com>',                                           false),
            'Zend invalid example 12'         => array('',                                                                           false),
            'Zend invalid example 13'         => array("bob\n\n@domain.com",                                                         false),
            'Zend invalid example 14'         => array('bob jones@domain.com',                                                       false),
            'Zend invalid example 15'         => array('.bobJones@studio24.com',                                                     false),
            'Zend invalid example 16'         => array('bobJones.@studio24.com',                                                     false),
            'Zend invalid example 17'         => array('bob.Jones.@studio24.com',                                                    false),
            'Zend invalid example 18'         => array('"bob%jones@domain.com',                                                      false),
            'Zend invalid example 19'         => array('bob@verylongdomainsupercalifragilisticexpialidociousaspoonfulofsugar.com',   true),  // deviation from Zend
            'Zend invalid example 20'         => array('bob+domain.com',                                                             false),
            'Zend invalid example 21'         => array('bob.domain.com',                                                             false),
            'Zend invalid example 22'         => array('bob @domain.com',                                                            false),
            'Zend invalid example 23'         => array('bob@ domain.com',                                                            false),
            'Zend invalid example 24'         => array('bob @ domain.com',                                                           false),
            'Zend invalid example 25'         => array('Abc..123@example.com',                                                       false),
        );
    }

    /**
     * @dataProvider addressData
     */
    public function testValidateAddress($address, $isValid)
    {
        $this->assertSame($isValid, $this->validator->validateAddress($address));
    }

    /**
     * @dataProvider addressData
     */
    public function testAssertAddress($address, $isValid)
    {
        if ($isValid) {
            $this->assertNull($this->validator->assertAddress($address));
        } else {
            $this->setExpectedException(
                'Eloquent\Phuri\SchemeSpecific\Mailto\Validation\Exception\InvalidEmailAddressException'
            );
            $this->validator->assertAddress($address);
        }
    }

    public function addressListData()
    {
        //                              addressList                                    isValid
        return array(
            'Single valid'     => array('eloquent@example.org',                        true),
            'Multiple valid'   => array('eloquent@example.org,username@example.org',   true),

            'Valid, invalid'   => array('eloquent@example.org,user name@example.org',  false),
            'Invalid, valid'   => array('eloq uent@example.org,username@example.org',  false),
            'Multiple invalid' => array('eloq uent@example.org,usern ame@example.org', false),
        );
    }

    /**
     * @dataProvider addressListData
     */
    public function testValidateAddressList($addressList, $isValid)
    {
        $this->assertSame($isValid, $this->validator->validateAddressList($addressList));
    }

    /**
     * @dataProvider addressListData
     */
    public function testAssertAddressList($addressList, $isValid)
    {
        if ($isValid) {
            $this->assertNull($this->validator->assertAddressList($addressList));
        } else {
            $this->setExpectedException(
                'Eloquent\Phuri\SchemeSpecific\Mailto\Validation\Exception\InvalidEmailAddressException'
            );
            $this->validator->assertAddressList($addressList);
        }
    }

    public function testInstance()
    {
        $class = Liberator::liberateClass(__NAMESPACE__ . '\EmailAddressValidator');
        $class->instance = null;
        $actual = EmailAddressValidator::instance();

        $this->assertInstanceOf(__NAMESPACE__ . '\EmailAddressValidator', $actual);
        $this->assertSame($actual, EmailAddressValidator::instance());
    }
}


text:
// Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.skyframe;

import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.devtools.build.lib.actions.Action;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.analysis.DependencyResolver.Dependency;
import com.google.devtools.build.lib.analysis.LabelAndConfiguration;
import com.google.devtools.build.lib.analysis.TargetAndConfiguration;
import com.google.devtools.build.lib.analysis.config.ConfigMatchingProvider;
import com.google.devtools.build.lib.packages.Attribute;
import com.google.devtools.build.lib.packages.RawAttributeMapper;
import com.google.devtools.build.lib.packages.Rule;
import com.google.devtools.build.lib.packages.Type;
import com.google.devtools.build.lib.skyframe.SkyframeActionExecutor.ConflictException;
import com.google.devtools.build.lib.syntax.Label;
import com.google.devtools.build.skyframe.SkyFunction;
import com.google.devtools.build.skyframe.SkyFunctionException;
import com.google.devtools.build.skyframe.SkyKey;
import com.google.devtools.build.skyframe.SkyValue;

import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

import javax.annotation.Nullable;

/**
 * Build a post-processed ConfiguredTarget, vetting it for action conflict issues.
 */
public class PostConfiguredTargetFunction implements SkyFunction {
  private static final Function<Dependency, SkyKey> TO_KEYS =
      new Function<Dependency, SkyKey>() {
    @Override
    public SkyKey apply(Dependency input) {
      return PostConfiguredTargetValue.key(
          new ConfiguredTargetKey(input.getLabel(), input.getConfiguration()));
    }
  };

  private final SkyframeExecutor.BuildViewProvider buildViewProvider;

  public PostConfiguredTargetFunction(
      SkyframeExecutor.BuildViewProvider buildViewProvider) {
    this.buildViewProvider = Preconditions.checkNotNull(buildViewProvider);
  }

  @Nullable
  @Override
  public SkyValue compute(SkyKey skyKey, Environment env) throws SkyFunctionException {
    ImmutableMap<Action, ConflictException> badActions = PrecomputedValue.BAD_ACTIONS.get(env);
    ConfiguredTargetValue ctValue = (ConfiguredTargetValue)
        env.getValue(ConfiguredTargetValue.key((ConfiguredTargetKey) skyKey.argument()));
    SkyframeDependencyResolver resolver =
        buildViewProvider.getSkyframeBuildView().createDependencyResolver(env);
    if (env.valuesMissing()) {
      return null;
    }

    for (Action action : ctValue.getActions()) {
      if (badActions.containsKey(action)) {
        throw new ActionConflictFunctionException(badActions.get(action));
      }
    }

    ConfiguredTarget ct = ctValue.getConfiguredTarget();
    TargetAndConfiguration ctgValue =
        new TargetAndConfiguration(ct.getTarget(), ct.getConfiguration());

    Set<ConfigMatchingProvider> configConditions =
        getConfigurableAttributeConditions(ctgValue, env);
    if (configConditions == null) {
      return null;
    }

    Collection<Dependency> deps = resolver.dependentNodes(ctgValue, configConditions);
    env.getValues(Iterables.transform(deps, TO_KEYS));
    if (env.valuesMissing()) {
      return null;
    }

    return new PostConfiguredTargetValue(ct);
  }

  /**
   * Returns the configurable attribute conditions necessary to evaluate the given configured
   * target, or null if not all dependencies have yet been SkyFrame-evaluated.
   */
  @Nullable
  private Set<ConfigMatchingProvider> getConfigurableAttributeConditions(
      TargetAndConfiguration ctg, Environment env) {
    if (!(ctg.getTarget() instanceof Rule)) {
      return ImmutableSet.of();
    }
    Rule rule = (Rule) ctg.getTarget();
    RawAttributeMapper mapper = RawAttributeMapper.of(rule);
    Set<SkyKey> depKeys = new LinkedHashSet<>();
    for (Attribute attribute : rule.getAttributes()) {
      for (Label label : mapper.getConfigurabilityKeys(attribute.getName(), attribute.getType())) {
        if (!Type.Selector.isReservedLabel(label)) {
          depKeys.add(ConfiguredTargetValue.key(label, ctg.getConfiguration()));
        }
      }
    }
    Map<SkyKey, SkyValue> cts = env.getValues(depKeys);
    if (env.valuesMissing()) {
      return null;
    }
    ImmutableSet.Builder<ConfigMatchingProvider> conditions = ImmutableSet.builder();
    for (SkyValue ctValue : cts.values()) {
      ConfiguredTarget ct = ((ConfiguredTargetValue) ctValue).getConfiguredTarget();
      conditions.add(Preconditions.checkNotNull(ct.getProvider(ConfigMatchingProvider.class)));
    }
    return conditions.build();
  }

  @Nullable
  @Override
  public String extractTag(SkyKey skyKey) {
    return Label.print(((LabelAndConfiguration) skyKey.argument()).getLabel());
  }

  private static class ActionConflictFunctionException extends SkyFunctionException {
    public ActionConflictFunctionException(ConflictException e) {
      super(e, Transience.PERSISTENT);
    }
  }
}


text:
C:\Windows\System32\setx THEORA_DIR "%CD%"
pause


text:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd"
         bootstrap="vendor/autoload.php"
         colors="true"
>
    <testsuites>
        <testsuite name="Unit">
            <directory suffix="Test.php">./tests/Unit</directory>
        </testsuite>
        <testsuite name="Feature">
            <directory suffix="Test.php">./tests/Feature</directory>
        </testsuite>
    </testsuites>
    <coverage processUncoveredFiles="true">
        <include>
            <directory suffix=".php">./app</directory>
        </include>
    </coverage>
    <php>
        <server name="APP_KEY" value="AckfSECXIvnK5r28GVIWUAxmbBSjTsmF"/>
        <server name="APP_ENV" value="testing"/>
        <server name="BCRYPT_ROUNDS" value="4"/>
        <server name="CACHE_DRIVER" value="array"/>
        <server name="DB_CONNECTION" value="sqlite"/>
        <server name="DB_DATABASE" value=":memory:"/>
        <server name="DB_FOREIGN_KEYS" value="(false)"/>
        <server name="MAIL_MAILER" value="array"/>
        <server name="QUEUE_CONNECTION" value="sync"/>
        <server name="SESSION_DRIVER" value="array"/>
        <server name="TELESCOPE_ENABLED" value="false"/>
        <server name="JWT_SECRET" value="9K6whOetAFaokQgSIdbMQZuJuDV5uS2Y"/>
    </php>
</phpunit>


text:
'use strict';
let expect  = require('chai').expect;
let wrap    = require('./index').wrap;

class FakeDataStore {
  constructor() {
    // In memory store, imagine a DB instead
    this.store = new Map();
  }

  static exampleSync() {
    return 'foo';
  }

  static examplePromiseAsync() {
    return 'foo';
  }

  static *exampleAsync() {
    return yield Promise.resolve('foo');
  }

  static *example() {
    return yield Promise.resolve('foo');
  }

  keys() {
    let keys = [];
    for (let key of this.store.keys()) {
      keys.push(key);
    }
    return keys;
  }

  get size() {
    return this.store.size;
  }

  getAsync(key) {
    let val = this.store.get(key);
    return Promise.resolve(val);
  }

  *setAsync(key, value) {
    this.store.set(key, value);
    return yield Promise.resolve(key);
  }
}

wrap(FakeDataStore);

describe('async-class', function() {
  let dataStore;

  beforeEach(function() {
    dataStore = new FakeDataStore();
  });

  describe('wrap', function() {
    it('does not modify getters', function() {
      expect(dataStore.size).to.eql(0);
    });

    it('only modifies properties that are functions', function() {
      expect(dataStore.store).to.be.instanceOf(Map);
    });

    it('does not wrap functions that do not end with Async', function() {
      dataStore.store.set('foo', 'bar');
      let keys = dataStore.keys();
      expect(keys).to.eql(['foo']);
    });

    it('wraps all GeneratorFunctions', function*() {
      let res = yield FakeDataStore.example();
      expect(res).to.eql('foo');
    });

    it('wraps instance methods that end with Async', function*() {
      dataStore.store.set('foo', 'bar');
      let res = yield dataStore.getAsync('foo');
      expect(res).to.eql('bar');
    });

    it('wraps instance methods that use generator functions', function*() {
      let key = yield dataStore.setAsync('foo', 'bar');
      let res = dataStore.store.get('foo');
      expect(key).to.eql('foo');
      expect(res).to.eql('bar');
    });

    it('does not wrap static methods that do not end with Async', function() {
      let res = FakeDataStore.exampleSync();
      expect(res).to.eql('foo');
    });

    it('wraps static methods that end with Async', function*() {
      let res = yield FakeDataStore.examplePromiseAsync();
      expect(res).to.eql('foo');
    });

    it('wraps static methods that use generator functions', function*() {
      let res = yield FakeDataStore.exampleAsync();
      expect(res).to.eql('foo');
    });
  });
});


text:
#include "config.h"
#include "bindings/core/v8/V8Initializer.h"

#include "bindings/core/v8/DOMWrapperWorld.h"
#include "bindings/core/v8/ScriptCallStackFactory.h"
#include "bindings/core/v8/ScriptController.h"
#include "bindings/core/v8/ScriptProfiler.h"
#include "bindings/core/v8/ScriptValue.h"
#include "bindings/core/v8/V8Binding.h"
#include "bindings/core/v8/V8DOMException.h"
#include "bindings/core/v8/V8ErrorEvent.h"
#include "bindings/core/v8/V8ErrorHandler.h"
#include "bindings/core/v8/V8GCController.h"
#include "bindings/core/v8/V8History.h"
#include "bindings/core/v8/V8Location.h"
#include "bindings/core/v8/V8PerContextData.h"
#include "bindings/core/v8/V8Window.h"
#include "core/dom/Document.h"
#include "core/dom/ExceptionCode.h"
#include "core/frame/ConsoleTypes.h"
#include "core/frame/LocalDOMWindow.h"
#include "core/frame/LocalFrame.h"
#include "core/frame/csp/ContentSecurityPolicy.h"
#include "core/inspector/ConsoleMessage.h"
#include "core/inspector/ScriptArguments.h"
#include "core/inspector/ScriptCallStack.h"
#include "platform/EventDispatchForbiddenScope.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/TraceEvent.h"
#include "platform/scheduler/Scheduler.h"
#include "public/platform/Platform.h"
#include "wtf/RefPtr.h"
#include "wtf/ThreadSpecific.h"
#include "wtf/text/WTFString.h"
#include <v8-debug.h>

namespace blink {

static LocalFrame* findFrame(v8::Local<v8::Object> host, v8::Local<v8::Value> data, v8::Isolate* isolate)
{
    const WrapperTypeInfo* type = WrapperTypeInfo::unwrap(data);

    if (V8Window::wrapperTypeInfo.equals(type)) {
        v8::Handle<v8::Object> windowWrapper = V8Window::findInstanceInPrototypeChain(host, isolate);
        if (windowWrapper.IsEmpty())
            return 0;
        return V8Window::toImpl(windowWrapper)->frame();
    }

    if (V8History::wrapperTypeInfo.equals(type))
        return V8History::toImpl(host)->frame();

    if (V8Location::wrapperTypeInfo.equals(type))
        return V8Location::toImpl(host)->frame();

    // This function can handle only those types listed above.
    ASSERT_NOT_REACHED();
    return 0;
}

static void reportFatalErrorInMainThread(const char* location, const char* message)
{
    int memoryUsageMB = blink::Platform::current()->actualMemoryUsageMB();
    printf("V8 error: %s (%s).  Current memory usage: %d MB\n", message, location, memoryUsageMB);
    CRASH();
}

static void messageHandlerInMainThread(v8::Handle<v8::Message> message, v8::Handle<v8::Value> data)
{
    ASSERT(isMainThread());
    // It's possible that messageHandlerInMainThread() is invoked while we're initializing a window.
    // In that half-baked situation, we don't have a valid context nor a valid world,
    // so just return immediately.
    if (DOMWrapperWorld::windowIsBeingInitialized())
        return;

    v8::Isolate* isolate = v8::Isolate::GetCurrent();
    // If called during context initialization, there will be no entered window.
    LocalDOMWindow* enteredWindow = enteredDOMWindow(isolate);
    if (!enteredWindow || !enteredWindow->isCurrentlyDisplayedInFrame())
        return;

    String errorMessage = toCoreString(message->Get());

    v8::Handle<v8::StackTrace> stackTrace = message->GetStackTrace();
    RefPtrWillBeRawPtr<ScriptCallStack> callStack = nullptr;
    int scriptId = message->GetScriptOrigin().ScriptID()->Value();
    // Currently stack trace is only collected when inspector is open.
    if (!stackTrace.IsEmpty() && stackTrace->GetFrameCount() > 0) {
        callStack = createScriptCallStack(stackTrace, ScriptCallStack::maxCallStackSizeToCapture, isolate);
        bool success = false;
        int topScriptId = callStack->at(0).scriptId().toInt(&success);
        if (success && topScriptId == scriptId)
            scriptId = 0;
    } else {
        Vector<ScriptCallFrame> callFrames;
        callStack = ScriptCallStack::create(callFrames);
    }

    v8::Handle<v8::Value> resourceName = message->GetScriptOrigin().ResourceName();
    bool shouldUseDocumentURL = resourceName.IsEmpty() || !resourceName->IsString();
    String resource = shouldUseDocumentURL ? enteredWindow->document()->url() : toCoreString(resourceName.As<v8::String>());
    AccessControlStatus corsStatus = message->IsSharedCrossOrigin() ? SharableCrossOrigin : NotSharableCrossOrigin;

    ScriptState* scriptState = ScriptState::current(isolate);
    RefPtrWillBeRawPtr<ErrorEvent> event = ErrorEvent::create(errorMessage, resource, message->GetLineNumber(), message->GetStartColumn() + 1, &scriptState->world());
    if (V8DOMWrapper::isDOMWrapper(data)) {
        v8::Handle<v8::Object> obj = v8::Handle<v8::Object>::Cast(data);
        const WrapperTypeInfo* type = toWrapperTypeInfo(obj);
        if (V8DOMException::wrapperTypeInfo.isSubclass(type)) {
            DOMException* exception = V8DOMException::toImpl(obj);
            if (exception && !exception->messageForConsole().isEmpty())
                event->setUnsanitizedMessage("Uncaught " + exception->toStringForConsole());
        }
    }

    // This method might be called while we're creating a new context. In this case, we
    // avoid storing the exception object, as we can't create a wrapper during context creation.
    // FIXME: Can we even get here during initialization now that we bail out when GetEntered returns an empty handle?
    LocalFrame* frame = enteredWindow->document()->frame();
    if (frame && frame->script().existingWindowProxy(scriptState->world())) {
        V8ErrorHandler::storeExceptionOnErrorEventWrapper(isolate, event.get(), data, scriptState->context()->Global());
    }

    if (scriptState->world().isPrivateScriptIsolatedWorld()) {
        // We allow a private script to dispatch error events even in a EventDispatchForbiddenScope scope.
        // Without having this ability, it's hard to debug the private script because syntax errors
        // in the private script are not reported to console (the private script just crashes silently).
        // Allowing error events in private scripts is safe because error events don't propagate to
        // other isolated worlds (which means that the error events won't fire any event listeners
        // in user's scripts).
        EventDispatchForbiddenScope::AllowUserAgentEvents allowUserAgentEvents;
        enteredWindow->document()->reportException(event.release(), scriptId, callStack, corsStatus);
    } else {
        enteredWindow->document()->reportException(event.release(), scriptId, callStack, corsStatus);
    }
}

namespace {

class PromiseRejectMessage {
    ALLOW_ONLY_INLINE_ALLOCATION();
public:
    PromiseRejectMessage(const ScriptValue& promise, PassRefPtrWillBeRawPtr<ScriptCallStack> callStack)
        : m_promise(promise)
        , m_callStack(callStack)
    {
    }

    void trace(Visitor* visitor)
    {
        visitor->trace(m_callStack);
    }

    const ScriptValue m_promise;
    const RefPtrWillBeMember<ScriptCallStack> m_callStack;
};

} // namespace

typedef Deque<PromiseRejectMessage> PromiseRejectMessageQueue;

static PromiseRejectMessageQueue& promiseRejectMessageQueue()
{
    AtomicallyInitializedStatic(ThreadSpecific<PromiseRejectMessageQueue>*, queue = new ThreadSpecific<PromiseRejectMessageQueue>);
    return **queue;
}

void V8Initializer::reportRejectedPromises()
{
    PromiseRejectMessageQueue& queue = promiseRejectMessageQueue();
    while (!queue.isEmpty()) {
        PromiseRejectMessage message = queue.takeFirst();
        ScriptState* scriptState = message.m_promise.scriptState();
        if (!scriptState->contextIsValid())
            continue;
        // If execution termination has been triggered, quietly bail out.
        if (v8::V8::IsExecutionTerminating(scriptState->isolate()))
            continue;
        ExecutionContext* executionContext = scriptState->executionContext();
        if (!executionContext)
            continue;

        ScriptState::Scope scope(scriptState);

        ASSERT(!message.m_promise.isEmpty());
        v8::Handle<v8::Value> value = message.m_promise.v8Value();
        ASSERT(!value.IsEmpty() && value->IsPromise());
        if (v8::Handle<v8::Promise>::Cast(value)->HasHandler())
            continue;

        const String errorMessage = "Unhandled promise rejection";
        Vector<ScriptValue> args;
        args.append(ScriptValue(scriptState, v8String(scriptState->isolate(), errorMessage)));
        args.append(message.m_promise);
        RefPtrWillBeRawPtr<ScriptArguments> arguments = ScriptArguments::create(scriptState, args);

        RefPtrWillBeRawPtr<ConsoleMessage> consoleMessage = ConsoleMessage::create(JSMessageSource, ErrorMessageLevel, errorMessage);
        consoleMessage->setScriptArguments(arguments);
        consoleMessage->setCallStack(message.m_callStack);
        executionContext->addConsoleMessage(consoleMessage.release());
    }
}

static void promiseRejectHandlerInMainThread(v8::PromiseRejectMessage message)
{
    ASSERT(isMainThread());

    if (message.GetEvent() != v8::kPromiseRejectWithNoHandler)
        return;

    // It's possible that promiseRejectHandlerInMainThread() is invoked while we're initializing a window.
    // In that half-baked situation, we don't have a valid context nor a valid world,
    // so just return immediately.
    if (DOMWrapperWorld::windowIsBeingInitialized())
        return;

    v8::Handle<v8::Promise> promise = message.GetPromise();

    // Bail out if called during context initialization.
    v8::Isolate* isolate = promise->GetIsolate();
    v8::Handle<v8::Context> context = isolate->GetCurrentContext();
    if (context.IsEmpty())
        return;
    v8::Handle<v8::Value> global = V8Window::findInstanceInPrototypeChain(context->Global(), context->GetIsolate());
    if (global.IsEmpty())
        return;
    if (!toFrameIfNotDetached(context))
        return;

    RefPtrWillBeRawPtr<ScriptCallStack> callStack = nullptr;
    v8::Handle<v8::StackTrace> stackTrace = message.GetStackTrace();
    if (!stackTrace.IsEmpty() && stackTrace->GetFrameCount() > 0)
        callStack = createScriptCallStack(stackTrace, ScriptCallStack::maxCallStackSizeToCapture, isolate);

    if (!callStack && V8DOMWrapper::isDOMWrapper(message.GetValue())) {
        // Try to get the stack from a wrapped exception object (e.g. DOMException).
        v8::Handle<v8::Object> obj = v8::Handle<v8::Object>::Cast(message.GetValue());
        v8::Handle<v8::Value> error = V8HiddenValue::getHiddenValue(isolate, obj, V8HiddenValue::error(isolate));
        if (!error.IsEmpty()) {
            stackTrace = v8::Exception::GetStackTrace(error);
            if (!stackTrace.IsEmpty() && stackTrace->GetFrameCount() > 0)
                callStack = createScriptCallStack(stackTrace, ScriptCallStack::maxCallStackSizeToCapture, isolate);
        }
    }

    ScriptState* scriptState = ScriptState::from(context);
    promiseRejectMessageQueue().append(PromiseRejectMessage(ScriptValue(scriptState, promise), callStack));
}

static void promiseRejectHandlerInWorker(v8::PromiseRejectMessage message)
{
    if (message.GetEvent() != v8::kPromiseRejectWithNoHandler)
        return;

    v8::Handle<v8::Promise> promise = message.GetPromise();

    // Bail out if called during context initialization.
    v8::Isolate* isolate = promise->GetIsolate();
    v8::Handle<v8::Context> context = isolate->GetCurrentContext();
    if (context.IsEmpty())
        return;

    RefPtrWillBeRawPtr<ScriptCallStack> callStack = nullptr;
    v8::Handle<v8::StackTrace> stackTrace = message.GetStackTrace();
    if (!stackTrace.IsEmpty() && stackTrace->GetFrameCount() > 0)
        callStack = createScriptCallStack(stackTrace, ScriptCallStack::maxCallStackSizeToCapture, isolate);

    ScriptState* scriptState = ScriptState::from(context);
    promiseRejectMessageQueue().append(PromiseRejectMessage(ScriptValue(scriptState, promise), callStack));
}

static void failedAccessCheckCallbackInMainThread(v8::Local<v8::Object> host, v8::AccessType type, v8::Local<v8::Value> data)
{
    v8::Isolate* isolate = v8::Isolate::GetCurrent();
    LocalFrame* target = findFrame(host, data, isolate);
    if (!target)
        return;
    LocalDOMWindow* targetWindow = target->domWindow();

    // FIXME: We should modify V8 to pass in more contextual information (context, property, and object).
    ExceptionState exceptionState(ExceptionState::UnknownContext, 0, 0, isolate->GetCurrentContext()->Global(), isolate);
    exceptionState.throwSecurityError(targetWindow->sanitizedCrossDomainAccessErrorMessage(callingDOMWindow(isolate)), targetWindow->crossDomainAccessErrorMessage(callingDOMWindow(isolate)));
    exceptionState.throwIfNeeded();
}

static bool codeGenerationCheckCallbackInMainThread(v8::Local<v8::Context> context)
{
    if (ExecutionContext* executionContext = toExecutionContext(context)) {
        if (ContentSecurityPolicy* policy = toDocument(executionContext)->contentSecurityPolicy())
            return policy->allowEval(ScriptState::from(context));
    }
    return false;
}

static void idleGCTaskInMainThread(double deadlineSeconds);

static void postIdleGCTaskMainThread()
{
    if (RuntimeEnabledFeatures::v8IdleTasksEnabled()) {
        Scheduler* scheduler = Scheduler::shared();
        if (scheduler)
            scheduler->postIdleTask(FROM_HERE, WTF::bind<double>(idleGCTaskInMainThread));
    }
}

static void idleGCTaskInMainThread(double deadlineSeconds)
{
    ASSERT(isMainThread());
    ASSERT(RuntimeEnabledFeatures::v8IdleTasksEnabled());
    v8::Isolate* isolate = v8::Isolate::GetCurrent();
    // FIXME: Change V8's API to take a deadline - http://crbug.com/417668
    double idleTimeInSeconds = deadlineSeconds - Platform::current()->monotonicallyIncreasingTime();
    int idleTimeInMillis = static_cast<int>(idleTimeInSeconds * 1000);
    if (idleTimeInMillis > 0)
        isolate->IdleNotification(idleTimeInMillis);
    // FIXME: only repost if there is more work to do.
    postIdleGCTaskMainThread();
}

static void timerTraceProfilerInMainThread(const char* name, int status)
{
    if (!status) {
        TRACE_EVENT_BEGIN0("v8", name);
    } else {
        TRACE_EVENT_END0("v8", name);
    }
}

static void initializeV8Common(v8::Isolate* isolate)
{
    v8::V8::AddGCPrologueCallback(V8GCController::gcPrologue);
    v8::V8::AddGCEpilogueCallback(V8GCController::gcEpilogue);

    v8::Debug::SetLiveEditEnabled(isolate, false);

    isolate->SetAutorunMicrotasks(false);
}

void V8Initializer::initializeMainThreadIfNeeded()
{
    ASSERT(isMainThread());

    static bool initialized = false;
    if (initialized)
        return;
    initialized = true;

    gin::IsolateHolder::Initialize(gin::IsolateHolder::kNonStrictMode, v8ArrayBufferAllocator());

    v8::Isolate* isolate = V8PerIsolateData::initialize();

    initializeV8Common(isolate);

    v8::V8::SetFatalErrorHandler(reportFatalErrorInMainThread);
    v8::V8::AddMessageListener(messageHandlerInMainThread);
    v8::V8::SetFailedAccessCheckCallbackFunction(failedAccessCheckCallbackInMainThread);
    v8::V8::SetAllowCodeGenerationFromStringsCallback(codeGenerationCheckCallbackInMainThread);

    postIdleGCTaskMainThread();

    isolate->SetEventLogger(timerTraceProfilerInMainThread);
    isolate->SetPromiseRejectCallback(promiseRejectHandlerInMainThread);

    ScriptProfiler::initialize();
}

static void reportFatalErrorInWorker(const char* location, const char* message)
{
    // FIXME: We temporarily deal with V8 internal error situations such as out-of-memory by crashing the worker.
    CRASH();
}

static void messageHandlerInWorker(v8::Handle<v8::Message> message, v8::Handle<v8::Value> data)
{
    v8::Isolate* isolate = v8::Isolate::GetCurrent();
    V8PerIsolateData* perIsolateData = V8PerIsolateData::from(isolate);
    // Exceptions that occur in error handler should be ignored since in that case
    // WorkerGlobalScope::reportException will send the exception to the worker object.
    if (perIsolateData->isReportingException())
        return;
    perIsolateData->setReportingException(true);

    ScriptState* scriptState = ScriptState::current(isolate);
    // During the frame teardown, there may not be a valid context.
    if (ExecutionContext* context = scriptState->executionContext()) {
        String errorMessage = toCoreString(message->Get());
        TOSTRING_VOID(V8StringResource<>, sourceURL, message->GetScriptOrigin().ResourceName());
        int scriptId = message->GetScriptOrigin().ScriptID()->Value();

        RefPtrWillBeRawPtr<ErrorEvent> event = ErrorEvent::create(errorMessage, sourceURL, message->GetLineNumber(), message->GetStartColumn() + 1, &DOMWrapperWorld::current(isolate));
        AccessControlStatus corsStatus = message->IsSharedCrossOrigin() ? SharableCrossOrigin : NotSharableCrossOrigin;

        // If execution termination has been triggered as part of constructing
        // the error event from the v8::Message, quietly leave.
        if (!v8::V8::IsExecutionTerminating(isolate)) {
            V8ErrorHandler::storeExceptionOnErrorEventWrapper(isolate, event.get(), data, scriptState->context()->Global());
            context->reportException(event.release(), scriptId, nullptr, corsStatus);
        }
    }

    perIsolateData->setReportingException(false);
}

static const int kWorkerMaxStackSize = 500 * 1024;

void V8Initializer::initializeWorker(v8::Isolate* isolate)
{
    initializeV8Common(isolate);

    v8::V8::AddMessageListener(messageHandlerInWorker);
    v8::V8::SetFatalErrorHandler(reportFatalErrorInWorker);

    uint32_t here;
    isolate->SetStackLimit(reinterpret_cast<uintptr_t>(&here - kWorkerMaxStackSize / sizeof(uint32_t*)));
    isolate->SetPromiseRejectCallback(promiseRejectHandlerInWorker);
}

} // namespace blink


text:
<!--
  ~ Copyright (c) 2017 Evolveum and contributors
  ~
  ~ This work is dual-licensed under the Apache License 2.0
  ~ and European Union Public License. See LICENSE file for details.
  -->
<role oid="93d3e436-3c6c-11e7-8168-23796882a64e"
        xmlns="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
        xmlns:c="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
        xmlns:t="http://prism.evolveum.com/xml/ns/public/types-3"
        xmlns:ri="http://midpoint.evolveum.com/xml/ns/public/resource/instance-3"
        xmlns:q="http://prism.evolveum.com/xml/ns/public/query-3"
        xmlns:icfs="http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/resource-schema-3"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:piracy="http://midpoint.evolveum.com/xml/ns/samples/piracy">
    <name>Crew of Guybrush</name>
    <inducement>
        <construction>
            <resourceRef oid="10000000-0000-0000-0000-000000001104" type="c:ResourceType"/> <!-- Orange -->
            <kind>account</kind>
            <association>
                <ref>ri:crew</ref>
                <outbound>
                    <expression>
                        <associationTargetSearch>
                            <filter>
                                <q:equal>
                                    <q:path>attributes/icfs:name</q:path>
                                    <q:value>guybrush</q:value>
                                </q:equal>
                            </filter>
                        </associationTargetSearch>
                    </expression>
                </outbound>
            </association>
        </construction>
    </inducement>
</role>


text:
package com.github.thbrown.softballsim.optimizer.impl.montecarloadaptive.statstransform;

import org.apache.commons.math3.stat.descriptive.StatisticalSummary;
import org.apache.commons.math3.stat.descriptive.SummaryStatistics;
import org.apache.commons.math3.util.Pair;

/**
 * Pushes the distributions of two SummaryStatistics away from each other by some range.
 *
 * This is useful for performing tTests that determine if some mean is within some range of another
 * mean. Larger ranges require fewer sample points to reach a statistically significant results.
 */
public class RangeSummaryStatisticsTransform implements SummaryStatisticsTransform {

  private final double range;

  public RangeSummaryStatisticsTransform(double range) {
    this.range = Math.abs(range);
  }

  public Pair<StatisticalSummary, StatisticalSummary> transform(StatisticalSummary a, StatisticalSummary b) {
    if (a.getMean() > b.getMean()) {
      return new Pair<StatisticalSummary, StatisticalSummary>(new MeanAdjustedSummaryStatistics(a, this.range), b);
    } else {
      return new Pair<StatisticalSummary, StatisticalSummary>(a, new MeanAdjustedSummaryStatistics(b, this.range));
    }
  }

}


text:
use super::ReadBuf;
use std::io;
use std::ops::DerefMut;
use std::pin::Pin;
use std::task::{Context, Poll};

/// Reads bytes from a source.
///
/// This trait is analogous to the [`std::io::Read`] trait, but integrates with
/// the asynchronous task system. In particular, the [`poll_read`] method,
/// unlike [`Read::read`], will automatically queue the current task for wakeup
/// and return if data is not yet available, rather than blocking the calling
/// thread.
///
/// Specifically, this means that the `poll_read` function will return one of
/// the following:
///
/// * `Poll::Ready(Ok(()))` means that data was immediately read and placed into
///   the output buffer. The amount of data read can be determined by the
///   increase in the length of the slice returned by `ReadBuf::filled`. If the
///   difference is 0, EOF has been reached.
///
/// * `Poll::Pending` means that no data was read into the buffer
///   provided. The I/O object is not currently readable but may become readable
///   in the future. Most importantly, **the current future's task is scheduled
///   to get unparked when the object is readable**. This means that like
///   `Future::poll` you'll receive a notification when the I/O object is
///   readable again.
///
/// * `Poll::Ready(Err(e))` for other errors are standard I/O errors coming from the
///   underlying object.
///
/// This trait importantly means that the `read` method only works in the
/// context of a future's task. The object may panic if used outside of a task.
///
/// Utilities for working with `AsyncRead` values are provided by
/// [`AsyncReadExt`].
///
/// [`poll_read`]: AsyncRead::poll_read
/// [`std::io::Read`]: std::io::Read
/// [`Read::read`]: std::io::Read::read
/// [`AsyncReadExt`]: crate::io::AsyncReadExt
pub trait AsyncRead {
    /// Attempts to read from the `AsyncRead` into `buf`.
    ///
    /// On success, returns `Poll::Ready(Ok(()))` and places data in the
    /// unfilled portion of `buf`. If no data was read (`buf.filled().len()` is
    /// unchanged), it implies that EOF has been reached.
    ///
    /// If no data is available for reading, the method returns `Poll::Pending`
    /// and arranges for the current task (via `cx.waker()`) to receive a
    /// notification when the object becomes readable or is closed.
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>>;
}

macro_rules! deref_async_read {
    () => {
        fn poll_read(
            mut self: Pin<&mut Self>,
            cx: &mut Context<'_>,
            buf: &mut ReadBuf<'_>,
        ) -> Poll<io::Result<()>> {
            Pin::new(&mut **self).poll_read(cx, buf)
        }
    };
}

impl<T: ?Sized + AsyncRead + Unpin> AsyncRead for Box<T> {
    deref_async_read!();
}

impl<T: ?Sized + AsyncRead + Unpin> AsyncRead for &mut T {
    deref_async_read!();
}

impl<P> AsyncRead for Pin<P>
where
    P: DerefMut + Unpin,
    P::Target: AsyncRead,
{
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        self.get_mut().as_mut().poll_read(cx, buf)
    }
}

impl AsyncRead for &[u8] {
    fn poll_read(
        mut self: Pin<&mut Self>,
        _cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        let amt = std::cmp::min(self.len(), buf.remaining());
        let (a, b) = self.split_at(amt);
        buf.put_slice(a);
        *self = b;
        Poll::Ready(Ok(()))
    }
}

impl<T: AsRef<[u8]> + Unpin> AsyncRead for io::Cursor<T> {
    fn poll_read(
        mut self: Pin<&mut Self>,
        _cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        let pos = self.position();
        let slice: &[u8] = (*self).get_ref().as_ref();

        // The position could technically be out of bounds, so don't panic...
        if pos > slice.len() as u64 {
            return Poll::Ready(Ok(()));
        }

        let start = pos as usize;
        let amt = std::cmp::min(slice.len() - start, buf.remaining());
        // Add won't overflow because of pos check above.
        let end = start + amt;
        buf.put_slice(&slice[start..end]);
        self.set_position(end as u64);

        Poll::Ready(Ok(()))
    }
}


text:
package com.intellij.codeInspection;

import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;

/**
 * @author Dmitry Avdeev
 */
public abstract class XmlSuppressionProvider {

  public static ExtensionPointName<XmlSuppressionProvider> EP_NAME = new ExtensionPointName<XmlSuppressionProvider>("com.intellij.xml.xmlSuppressionProvider");

  public static boolean isSuppressed(PsiElement element, String inspectionId) {
    for (XmlSuppressionProvider provider : Extensions.getExtensions(EP_NAME)) {
      if (provider.isSuppressedFor(element, inspectionId)) {
        return true;
      }
    }
    return false;
  }

  public static XmlSuppressionProvider getProvider(PsiFile file) {
    for (XmlSuppressionProvider provider : Extensions.getExtensions(EP_NAME)) {
      if (provider.isProviderAvailable(file)) {
        return provider;
      }
    }
    throw new RuntimeException("No providers found for " + file);
  }

  public abstract boolean isProviderAvailable(PsiFile file);

  public abstract boolean isSuppressedFor(PsiElement element, String inspectionId);

  public abstract void suppressForFile(PsiElement element, String inspectionId);

  public abstract void suppressForTag(PsiElement element, String inspectionId);

}


text:
//  PlantUML Studio
//  Copyright 2013 Matthew Hamilton - matthamilton@live.com
//  Copyright 2010 Omar Al Zabir - http://omaralzabir.com/ (original author)
//
//  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.

using System.Diagnostics;
using System.Windows;
using System.Windows.Media.Imaging;
using SharpEssentials.Controls.Mvvm.Commands;

namespace PlantUmlStudio.ViewModel.Commands
{
	/// <summary>
	/// Copies an image to the clipboard.
	/// </summary>
	public class CopyImageCommand : RelayCommand<BitmapSource>
	{
		/// <summary>
		/// Creates a new command.
		/// </summary>
		public CopyImageCommand()
			: base(Clipboard.SetImage) { }
	}

	/// <summary>
	/// Copies text to the clipboard.
	/// </summary>
	public class CopyTextCommand : RelayCommand<string>
	{
		/// <summary>
		/// Creates a new command.
		/// </summary>
		public CopyTextCommand()
			: base(Clipboard.SetText) { }
	}

	/// <summary>
	/// Opens a path in Explorer.
	/// </summary>
	public class BrowseToCommand : RelayCommand<string>
	{
		/// <summary>
		/// Creates a new command.
		/// </summary>
		public BrowseToCommand()
			: base(path => Process.Start("explorer.exe", "/select," + path).Dispose()) { }
	}
}


text:
"use strict";
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(require("rxjs-compat/util/isScheduler"));
//# sourceMappingURL=isScheduler.js.map


text: from .marquise import Marquise


text:
package com.netflix.spinnaker.clouddriver.appengine.deploy.ops;

import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.spinnaker.clouddriver.appengine.deploy.description.DeployAppengineConfigDescription;
import com.netflix.spinnaker.clouddriver.artifacts.ArtifactDownloader;
import com.netflix.spinnaker.kork.artifacts.model.Artifact;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;

public class DeployAppengineConfigAtomicOperationTest {

  DeployAppengineConfigDescription description = new DeployAppengineConfigDescription();
  DeployAppengineConfigAtomicOperation deployAppengineConfigAtomicOperation;
  ObjectMapper mapper;
  ArtifactDownloader artifactDownloader = mock(ArtifactDownloader.class);

  @Before
  public void init() {
    deployAppengineConfigAtomicOperation = new DeployAppengineConfigAtomicOperation(description);
    mapper = new ObjectMapper();
    ReflectionTestUtils.setField(
        deployAppengineConfigAtomicOperation, "artifactDownloader", artifactDownloader);
  }

  @Test
  public void shouldCreateEmptyDirectory() throws IOException {
    Path path = null;
    try {
      path = deployAppengineConfigAtomicOperation.createEmptyDirectory();
      assertTrue(path.isAbsolute());
    } finally {
      FileUtils.cleanDirectory(path.toFile());
      FileUtils.forceDelete(path.toFile());
    }
  }

  @Test
  public void shouldDownloadFiletoDirectory() throws IOException {
    InputStream is = new ByteArrayInputStream("dosomething".getBytes(StandardCharsets.UTF_8));
    Map<String, Object> artifactMap = new HashMap<>();
    artifactMap.put("artifactAccount", "embedded-artifact");
    artifactMap.put("id", "123abc");
    artifactMap.put("reference", "ZG9zb21ldGhpbmc=");
    artifactMap.put("type", "embedded/base64");
    Artifact artifact = mapper.convertValue(artifactMap, Artifact.class);

    Path path = null;
    try {
      path = deployAppengineConfigAtomicOperation.createEmptyDirectory();
      when(artifactDownloader.download(any())).thenReturn(is);
      File file =
          deployAppengineConfigAtomicOperation.downloadFileToDirectory(
              artifact, path, DeployAppengineConfigAtomicOperation.SupportedConfigTypes.CRON);
      assertTrue(file.exists());
      assertTrue(file.canRead());
    } finally {
      FileUtils.cleanDirectory(path.toFile());
      FileUtils.forceDelete(path.toFile());
    }
  }
}


text:
<archimate:Folder
    xmlns:archimate="http://www.archimatetool.com/archimate"
    name="Starting Docker with Docker for Windows/macOS"
    id="b1b591b5-9092-4151-a2cd-6a280c38f19a"/>


text:
namespace extensions {

// static
ExtensionAPI* ExtensionAPI::GetSharedInstance() {
  return NULL;
}

// static
ExtensionAPI* ExtensionAPI::CreateWithDefaultConfiguration() {
  return NULL;
}

Feature::Availability ExtensionAPI::IsAvailable(
    const std::string& api_full_name,
    const Extension* extension,
    Feature::Context context,
    const GURL& url) {
  return Feature::CreateAvailability(Feature::NOT_PRESENT, "");
}

bool ExtensionAPI::IsAnyFeatureAvailableToContext(const std::string& api_name,
                                                  const Extension* extension,
                                                  Feature::Context context,
                                                  const GURL& url) {
  return false;
}

bool ExtensionAPI::IsPrivileged(const std::string& full_name) {
  return false;
}

const base::DictionaryValue* ExtensionAPI::GetSchema(
    const std::string& full_name) {
  return NULL;
}

}  // namespace extensions


text:
"use strict";

// A dialog allowing the user to customise the in-line citations

define(
		[	'src/exampleCitations',
			'src/exampleData',
			'src/debug',
			'jquery.ui'
		],
		function (
			CSLEDIT_exampleCitations,
			CSLEDIT_exampleData,
			debug,
			jquery_ui
		) {
	var dialog = $('
'),
		advanced = $('
', {id: "accordion"}).css({"padding-top": "10px", width: "100%"}),
		advancedContents = $('
'),
		referencePanel = $('
'),
		newReferenceInput = $('<textarea class="addReference" />
').css({width: "100%", height: "100px"}),
		addReferenceButton = $('<button>Add new reference</button>'),
		resetReferencesButton = $('<button>Reset all citations to default</button>'),
		citation,
		initialised = false;

	dialog.append(referencePanel);
	dialog.append(resetReferencesButton);
	dialog.append(advanced);

	advanced.append('
Advanced
');
	advanced.append(advancedContents);

	advancedContents.append("
Add new reference
");
	advancedContents.append("
Input csl-data.json here and click \"Add new Reference\"
");
	advancedContents.append(newReferenceInput);
	advancedContents.append(addReferenceButton);

	resetReferencesButton.on('click', function () {
		CSLEDIT_exampleCitations.resetToDefault();
		updateReferenceList();
	});

	addReferenceButton.on('click', function () {
		var jsonData,
			referenceList;

		try {
			jsonData = JSON.parse(newReferenceInput.val());
		} catch (e) {
			alert("Error: Not valid JSON");
			return;
		}

		// will accept individual references or a list
		referenceList = [].concat(jsonData);
		$.each(referenceList, function (i, reference) {
			CSLEDIT_exampleCitations.addReference(reference, citation);
		});

		updateReferenceList();
		newReferenceInput.val("");
	});

	var updateReferenceList = function () {
		var table = $('
');

		referencePanel.children().remove();

		$.each(CSLEDIT_exampleCitations.getReferences(), function (i, reference) {
			var row = $('
'),
				input,
				label1,
				label2,
				select;

			input = $('<input/>', {
					type : "checkbox",
					id : "citationEditorReference" + i
				});
			label1 = $('', {
					for : "citationEditorReference" + i
				}).append($('').text(reference.type));
			label2 = $('', {
					for : "citationEditorReference" + i
				}).text(reference.title);
			select = $('<select/>');
			$.each(CSLEDIT_exampleData.additionalOptions, function (i, option) {
				select.append($('<option/>').text(option.description));
			});

			var description;
			description = CSLEDIT_exampleData.additionalOptions[
				CSLEDIT_exampleCitations.getOption(citation, i)].description;
			debug.log(description);
			select.val(description);

			row.append($('').append(input));
			row.append($('').append(label1));
			row.append($('').append(label2));
			row.append($('').append(select));
			table.append(row);
		});
		referencePanel.append(table);

		table.find('td').css({"padding-right": "8px"});

		debug.log("checked = " +
				JSON.stringify(CSLEDIT_exampleCitations.getReferenceIndexesForCitation(citation)));

		$.each(CSLEDIT_exampleCitations.getReferenceIndexesForCitation(citation), function (i, refIndex) {
			referencePanel.find('input[type=checkbox]').eq(refIndex).attr('checked', true);
		});
		referencePanel.find('input[type=checkbox]').on('change', function () {
			updateCitations();
		});
		referencePanel.find('select').on('change', function () {
			var reference = referencePanel.find('select').index($(this)),
				optionIndex = $(this).children('option').index(
					$(this).children('option[value="' + $(this).val() + '"]'));

			CSLEDIT_exampleCitations.setOption(citation, reference, optionIndex);
		});
	};

	var updateCitations = function () {
		var citationItem,
			citationItems = [],
			checked = [],
			additionalOptions;

		referencePanel.find('input').each(function (index) {
			if ($(this).is(':checked')) {
				checked.push(index);
			}
		});

		debug.log("setting " + citation + " to " + JSON.stringify(checked));

		CSLEDIT_exampleCitations.setReferenceIndexesForCitation(citation, checked);
	};

	// Presents a dialog allowing customisation of the given inline citation
	//
	// - _citation - the integer index of the citation to edit
	var editCitation = function (_citation) {
		citation = _citation;
		updateReferenceList();

		// list references
		dialog.dialog({
			title : 'Edit Citation ' + (citation + 1),
			width : 700
		});

		if (!initialised) {
			advanced.accordion({
				collapsible : true,
				active : false
			});
			initialised = true;
		}

		if (dialog.height() > $(window).height() - 50) {
			dialog.height($(window).height() - 50);
		}
		if (dialog.offset().top < 80) {
			dialog.dialog("option", "position", [dialog.offset().left, 80]);
		}
	};

	return {
		editCitation : editCitation
	};
});


text:
class C extends C { } // error

class D<T> extends D<T> { } // error

class E<T> extends E<string> { } // error


text:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Authors Simen Brekken @simenbrekken, Einar Löve @einarlove
*/

"use strict";

const DefinePlugin = require("./DefinePlugin");
const WebpackError = require("./WebpackError");

/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./DefinePlugin").CodeValue} CodeValue */

class EnvironmentPlugin {
	constructor(...keys) {
		if (keys.length === 1 && Array.isArray(keys[0])) {
			this.keys = keys[0];
			this.defaultValues = {};
		} else if (keys.length === 1 && keys[0] && typeof keys[0] === "object") {
			this.keys = Object.keys(keys[0]);
			this.defaultValues = keys[0];
		} else {
			this.keys = keys;
			this.defaultValues = {};
		}
	}

	/**
	 * @param {Compiler} compiler webpack compiler instance
	 * @returns {void}
	 */
	apply(compiler) {
		/** @type {Record<string, CodeValue>} */
		const definitions = {};
		for (const key of this.keys) {
			const value =
				process.env[key] !== undefined
					? process.env[key]
					: this.defaultValues[key];

			if (value === undefined) {
				compiler.hooks.thisCompilation.tap("EnvironmentPlugin", compilation => {
					const error = new WebpackError(
						`EnvironmentPlugin - ${key} environment variable is undefined.\n\n` +
							"You can pass an object with default values to suppress this warning.\n" +
							"See https://webpack.js.org/plugins/environment-plugin for example."
					);

					error.name = "EnvVariableNotDefinedError";
					compilation.warnings.push(error);
				});
			}

			definitions[`process.env.${key}`] =
				value === undefined ? "undefined" : JSON.stringify(value);
		}

		new DefinePlugin(definitions).apply(compiler);
	}
}

module.exports = EnvironmentPlugin;


text:
package org.codehaus.groovy.transform.sc.transformers;

import org.codehaus.groovy.ast.ClassHelper;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.expr.ArrayExpression;
import org.codehaus.groovy.ast.expr.CastExpression;
import org.codehaus.groovy.ast.expr.ConstantExpression;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.ast.expr.ListExpression;
import org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport;

public class CastExpressionOptimizer {
    private final StaticCompilationTransformer transformer;

    public CastExpressionOptimizer(StaticCompilationTransformer staticCompilationTransformer) {
        transformer = staticCompilationTransformer;
    }

    public Expression transformCastExpression(final CastExpression cast) {
        if (cast.isCoerce()) {
            Expression expression = cast.getExpression();
            ClassNode exprInferredType = transformer.getTypeChooser().resolveType(expression, transformer.getClassNode());
            ClassNode castType = cast.getType();
            if (castType.isArray() && expression instanceof ListExpression) {
                ArrayExpression arrayExpression = new ArrayExpression(castType.getComponentType(), ((ListExpression) expression).getExpressions());
                arrayExpression.setSourcePosition(cast);
                return transformer.transform(arrayExpression);
            }
            if (isOptimizable(exprInferredType, castType)) {
                // coerce is not needed
                CastExpression trn = new CastExpression(castType, transformer.transform(expression));
                trn.setSourcePosition(cast);
                trn.copyNodeMetaData(cast);
                return trn;
            }
        } else if (ClassHelper.char_TYPE.equals(cast.getType())) {
            Expression expression = cast.getExpression();
            if (expression instanceof ConstantExpression) {
                ConstantExpression ce = (ConstantExpression) expression;
                if (ClassHelper.STRING_TYPE.equals(ce.getType())) {
                    String val = (String) ce.getValue();
                    if (val!=null && val.length()==1) {
                        ConstantExpression result = new ConstantExpression(val.charAt(0),true);
                        result.setSourcePosition(cast);
                        return result;
                    }
                }
            }
        }
        return transformer.superTransform(cast);
    }

    private static boolean isOptimizable(final ClassNode exprInferredType, final ClassNode castType) {
        if (StaticTypeCheckingSupport.implementsInterfaceOrIsSubclassOf(exprInferredType, castType)) {
            return true;
        }
        if (ClassHelper.isPrimitiveType(exprInferredType) && ClassHelper.isPrimitiveType(castType)) {
            return true;
        }
        return false;
    }
}


text:
<?php

class ConfiguracionTrampaController extends BaseController{

    public function index(){
        $trampas = ViewConfiguracionTrampa::all();
        return View::make('trampa.index')->with('trampas',$trampas);
    }

    public function getConfiguracionTrampa(){

		$cfgtrampa = ViewConfiguracionTrampa::all();
        //procces number field, for Typeahead library, needs to be a character.
        foreach ($cfgtrampa as $item)
        {
            $item->notrampa = strval($item->notrampa);
        }

		return Response::json(array(
			'error' => false,
			'cfgtrampas' => $cfgtrampa->toArray()),
			200
		);

    }

    /**
     * GET:
     */
    public function getUbicaciones(){

        $ubicaciones = Ubicacion::all();

        return Response::json(array(
            'error' => false,
            'ubicaciones' => $ubicaciones->toArray()),
                              200
                             );

    }

    //POST
    public function handleCreate()
    {
        // Handle create form submission.
		 if(Request::ajax())
		{
			$trampa = new ConfiguracionTrampa;
			$trampa->number        = Input::get('numero');
			$trampa->idtipotrampa     = Input::get('idtipotrampa');
			$trampa->idclasificaiontrampa     = Input::get('idclasificaiontrampa');
			$trampa->idubicacion     = Input::get('idubicacion');
			$trampa->description    = Input::get('description');

			$trampa->save();

			$resultado = array(
				'status' => 'success',
				'msg' => 'created successfully'
			);

			return Response::json( $resultado );
		}
        //return Redirect::action('ConfiguracionTrampaController@index');
         /*$rules = array(
        'number'   => 'required|min:1',
        'description'      => 'required'
        );
        $validator = Validator::make($trampa->toArray(), $rules);

        if ($validator->passes()) {
            $trampa->save();
            return Redirect::action('ConfiguracionTrampaController@index');
        }
       else
         return Redirect::to('/create')->withErrors($validator);
            //return Redirect::action('TodoController@handleCreate')->withErrors($validator);
        */
    }
}


text:
<?php

namespace PHPExiftool\Driver\Tag\XMPXmpDM;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class CameraLabel extends AbstractTag
{

    protected $Id = 'cameraLabel';

    protected $Name = 'CameraLabel';

    protected $FullName = 'XMP::xmpDM';

    protected $GroupName = 'XMP-xmpDM';

    protected $g0 = 'XMP';

    protected $g1 = 'XMP-xmpDM';

    protected $g2 = 'Image';

    protected $Type = 'string';

    protected $Writable = true;

    protected $Description = 'Camera Label';
}


text:
packageSum :: [Int] -> Int
packageSum (x:xs)  = x + packageSum xs
package _     = 0


text:
import { Inject, Injectable } from '@angular/core';
import { StorageService } from '@renet-consulting/storage';
import { IToken } from './token';

@Injectable({
    providedIn: 'root'
})
export class TokenService {

    private readonly key = 'token';
    private _token: IToken;

    constructor(
        @Inject(StorageService) private storage: StorageService
    ) { }

    private get token(): IToken {
        if (!this._token) {
            this._token = this.storage.get(this.key);
        }
        return this._token && this._token.access_token && this._token.refresh_token ? this._token : null;
    }

    get valid(): boolean {
        const item = this.token;
        return item && item.access_token && !!item.refresh_token;
    }

    get expired(): boolean {
        const item = this.token;
        const expired_at = item && item.expired_at;
        let value: number;
        /** expects date in format number as string */
        try {
            value = JSON.parse(expired_at);
        }
        /** expects date in format ISO or string of a date */
        catch (e) {
            const date = new Date(expired_at).valueOf();
            value = isNaN(date) ? 0 : date;
        }
        return this.valid ? new Date().valueOf() >= new Date(value).valueOf() : false;
    }

    get header(): { [k: string]: string } {
        const item = this.token;
        return this.valid ? { authorization: `${item.token_type} ${item.access_token}` } : null;
    }

    get = <Key extends keyof IToken>(key: Key): IToken[Key] => {
        const item = this.token;
        return item && item[key];
    }

    setToken = (value: IToken, date = new Date()): void => {
        const token = { ...value };
        if (token.access_token && token.refresh_token) {
            if (token.expires_in) {
                token.expired_at = date.setTime(date.valueOf() + 1000 * token.expires_in).toString();
            }
            this._token = { ...token };
            this.storage.set(this.key, token);
        }
    }

    clean = (): void => {
        this._token = null;
        this.storage.remove(this.key);
    }
}


text:
package com.dropbox.djinni.test;

public class ClientInterfaceImpl extends ClientInterface {
    @Override
    public ClientReturnedRecord getRecord(long id, String utf8string, String misc) {
        if (!utf8string.equals("Non-ASCII / 非 ASCII 字符") && !utf8string.equals("Hello World!")) {
            throw new RuntimeException("Unexpected string. Check UTF-8?");
        }
        return new ClientReturnedRecord(id, utf8string, misc);
    }
	@Override
	public double identifierCheck(byte[] data, int r, long jret)
	{
		return 0.0;
	}
    @Override
    public String returnStr() {
        return "test";
    }
}