text:
import json
from collections import namedtuple

from django.utils.translation import gettext as _

from corehq.apps.linked_domain.applications import (
    get_downstream_app_id,
    get_upstream_app_ids,
)
from corehq.apps.linked_domain.exceptions import (
    DomainLinkError,
    MultipleDownstreamAppsError,
    RegistryNotAccessible,
)
from corehq.apps.linked_domain.remote_accessors import \
    get_ucr_config as remote_get_ucr_config
from corehq.apps.userreports.dbaccessors import (
    get_datasources_for_domain,
    get_report_and_registry_report_configs_for_domain,
)
from corehq.apps.userreports.models import (
    ReportConfiguration,
    is_data_registry_report,
)
from corehq.apps.userreports.tasks import rebuild_indicators

from corehq.apps.registry.models import DataRegistry

from corehq.util.couch import DocumentNotFound

from tastypie.exceptions import NotFound

from corehq.apps.userreports.exceptions import (
    DataSourceConfigurationNotFoundError,
    InvalidDataSourceType,
)

from corehq.apps.userreports.util import (
    get_report_config_or_not_found,
    wrap_report_config_by_type,
    _wrap_data_source_by_doc_type,
    get_ucr_datasource_config_by_id
)

LinkedUCRInfo = namedtuple("LinkedUCRInfo", "datasource report")

def create_linked_ucr(domain_link, report_config_id):
    if domain_link.is_remote:
        remote_configs = remote_get_ucr_config(domain_link, report_config_id)
        datasource = remote_configs["datasource"]
        report_config = remote_configs["report"]
    else:
        try:
            report_config = get_report_config_or_not_found(domain_link.master_domain, report_config_id)
        except DocumentNotFound:
            raise NotFound
        try:
            datasource = get_ucr_datasource_config_by_id(report_config.config_id)
            if datasource.is_static:
                message = _('{} is not a valid data source type!').format(datasource.doc_type)
                raise InvalidDataSourceType(message)
        except DataSourceConfigurationNotFoundError:
            raise DataSourceConfigurationNotFoundError(_(
                'The data source referenced by this report could not be found.'
            ))
    if is_data_registry_report(report_config, datasource):
        try:
            DataRegistry.objects.accessible_to_domain(domain_link.linked_domain, slug=report_config.registry_slug)
        except DataRegistry.DoesNotExist:
            message = _("This report cannot be linked because the registry is not accessible to {}."
                " Please make sure the registry invitation has been accepted before"
                " linking reports.").format(domain_link.linked_domain)
            raise RegistryNotAccessible(message)
    # grab the linked app this linked report references
    try:
        downstream_app_id = get_downstream_app_id(domain_link.linked_domain, datasource.meta.build.app_id)
    except MultipleDownstreamAppsError:
        raise DomainLinkError(_("This report cannot be linked because it references an app that has multiple "
                                "downstream apps."))

    new_datasource = _get_or_create_datasource_link(domain_link, datasource, downstream_app_id)
    new_report = _get_or_create_report_link(domain_link, report_config, new_datasource)
    return LinkedUCRInfo(datasource=new_datasource, report=new_report)

def get_downstream_report(downstream_domain, upstream_report_id):
    for linked_report in get_report_and_registry_report_configs_for_domain(downstream_domain):
        if linked_report.report_meta.master_id == upstream_report_id:
            return linked_report
    return None

def _get_or_create_datasource_link(domain_link, datasource, app_id):
    domain_datsources = get_datasources_for_domain(domain_link.linked_domain)
    existing_linked_datasources = [d for d in domain_datsources if d.meta.master_id == datasource.get_id]
    if existing_linked_datasources:
        return existing_linked_datasources[0]

    datasource_json = datasource.to_json()
    datasource_json["domain"] = domain_link.linked_domain
    datasource_json["_id"] = None
    datasource_json["_rev"] = None

    # app_id is needed to edit reports which is not possible with a linked project due to master_id
    # this is to ensure if the link is removed, the downstream report will be editable
    datasource_json["meta"]["build"]["app_id"] = app_id

    datasource_json["meta"]["master_id"] = datasource.get_id

    _replace_master_app_ids(domain_link.linked_domain, datasource_json)

    new_datasource = _wrap_data_source_by_doc_type(datasource_json)
    new_datasource.save()

    rebuild_indicators.delay(
        new_datasource.get_id,
        source=f"Datasource link: {new_datasource.get_id}",
        domain=new_datasource.domain
    )

    return new_datasource

def _replace_master_app_ids(linked_domain, datasource_json):
    configured_filter = json.dumps(datasource_json['configured_filter'])
    for app_id in get_upstream_app_ids(linked_domain):
        configured_filter = _replace_upstream_app_id(configured_filter, app_id, linked_domain)
    datasource_json['configured_filter'] = json.loads(configured_filter)

    named_filters = json.dumps(datasource_json['named_filters'])
    for app_id in get_upstream_app_ids(linked_domain):
        named_filters = _replace_upstream_app_id(named_filters, app_id, linked_domain)
    datasource_json['named_filters'] = json.loads(named_filters)

def _replace_upstream_app_id(haystack, upstream_app_id, downstream_domain):
    if upstream_app_id in haystack:
        try:
            downstream_app_id = get_downstream_app_id(
                downstream_domain,
                upstream_app_id,
                use_upstream_app_id=False
            )
        except MultipleDownstreamAppsError:
            raise DomainLinkError(_("This report cannot be updated because it references an app "
                                    "that has multiple linked apps."))
        haystack = haystack.replace(upstream_app_id, downstream_app_id)
    return haystack

def _get_or_create_report_link(domain_link, report, datasource):
    existing_linked_reports = get_linked_report_configs(domain_link.linked_domain, report.get_id)
    if existing_linked_reports:
        return existing_linked_reports[0]

    report_json = report.to_json()
    report_json["report_meta"]["master_id"] = report.get_id
    report_json["domain"] = domain_link.linked_domain
    report_json["config_id"] = datasource.get_id
    report_json["_id"] = None
    report_json["_rev"] = None

    new_report = wrap_report_config_by_type(report_json)
    new_report.save()

    return new_report

def update_linked_ucr(domain_link, report_id):
    linked_report = ReportConfiguration.get(report_id)
    linked_datasource = linked_report.config

    if domain_link.is_remote:
        remote_configs = remote_get_ucr_config(domain_link, linked_report.report_meta.master_id)
        master_report = remote_configs["report"]
        master_datasource = remote_configs["datasource"]
    else:
        master_report = ReportConfiguration.get(linked_report.report_meta.master_id)
        master_datasource = master_report.config

    _update_linked_datasource(master_datasource, linked_datasource)
    _update_linked_report(master_report, linked_report)

def _update_linked_datasource(master_datasource, linked_datasource):
    master_datasource_json = master_datasource.to_json()
    linked_datasource_json = linked_datasource.to_json()

    master_datasource_json["domain"] = linked_datasource_json["domain"]
    master_datasource_json["_id"] = linked_datasource_json["_id"]
    master_datasource_json["_rev"] = linked_datasource_json["_rev"]
    master_datasource_json["meta"]["master_id"] = linked_datasource_json["meta"]["master_id"]

    _replace_master_app_ids(linked_datasource_json["domain"], master_datasource_json)

    linked_datasource_json.update(master_datasource_json)
    _wrap_data_source_by_doc_type(linked_datasource_json).save()

    rebuild_indicators.delay(
        linked_datasource.get_id,
        source=f"Datasource link: {linked_datasource.get_id}",
        domain=linked_datasource.domain
    )

def _update_linked_report(master_report, linked_report):
    master_report_json = master_report.to_json()
    linked_report_json = linked_report.to_json()

    master_report_json["_id"] = linked_report_json["_id"]
    master_report_json["_rev"] = linked_report_json["_rev"]
    master_report_json["domain"] = linked_report_json["domain"]
    master_report_json["config_id"] = linked_report_json["config_id"]
    master_report_json["report_meta"]["master_id"] = linked_report_json["report_meta"]["master_id"]

    linked_report_json.update(master_report_json)
    wrap_report_config_by_type(linked_report_json, allow_deleted=True).save()

def get_linked_report_configs(domain, report_id):
    domain_reports = get_report_and_registry_report_configs_for_domain(domain)
    existing_linked_reports = [r for r in domain_reports if r.report_meta.master_id == report_id]
    return existing_linked_reports

def get_linked_reports_in_domain(domain):
    reports = get_report_and_registry_report_configs_for_domain(domain)
    linked_reports = [report for report in reports if report.report_meta.master_id]
    return linked_reports

def linked_downstream_reports_by_domain(master_domain, report_id):
    """A dict of all downstream domains with and if this is already linked to `report_id`
    """
    from corehq.apps.linked_domain.dbaccessors import get_linked_domains
    linked_domains = {}
    for domain_link in get_linked_domains(master_domain):
        linked_domains[domain_link.linked_domain] = any(
            r for r in get_linked_report_configs(domain_link.linked_domain, report_id)
        )
    return linked_domains

def unlink_reports_in_domain(domain):
    unlinked_reports = []
    reports = get_linked_reports_in_domain(domain)
    for report in reports:
        unlinked_report = unlink_report(report)
        unlinked_reports.append(unlinked_report)

    return unlinked_reports

def unlink_report(report):
    if not report.report_meta.master_id:
        return None

    report.report_meta.master_id = None
    report.save()

    return report


text:
class DropGoogleGeolocations < ActiveRecord::Migration
  def self.up
    drop_table :google_geolocations
  end

  def self.down
  end
end

redpajama_set_name: RedPajamaGithub


text:
FROM debian:buster
LABEL maintainer "Jessie Frazelle <jess@linux.com>"

RUN apt-get update && apt-get install -y \
	libgssapi-krb5-2 \
	rdesktop \
	--no-install-recommends \
	&& rm -rf /var/lib/apt/lists/*

ENTRYPOINT [ "rdesktop" ]


text:
/**
    @author Benjamin Livshits <livshits@cs.stanford.edu>

    $Id: Aliasing4.java,v 1.1 2006/04/21 17:14:27 livshits Exp $
 */
package securibench.micro.aliasing;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import securibench.micro.BasicTestCase;
import securibench.micro.MicroTestCase;

/**
 *  @servlet description="simple aliasing with casts"
 *  @servlet vuln_count = "1"
 *  */
public class Aliasing4 extends BasicTestCase implements MicroTestCase {
	private static final String FIELD_NAME = "name";

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
       String name = req.getParameter(FIELD_NAME);
       Object o1 = name;
       Object o2 = name.concat("abc");
       Object o3 = "anc";

       PrintWriter writer = resp.getWriter();
       writer.println(o1);                              /* BAD */
       writer.println(o2);                              /* BAD */
       writer.println(o3);                              /* OK */
    }

    public String getDescription() {
        return "simple aliasing with casts";
    }

    public int getVulnerabilityCount() {
        return 1;
    }
}


text:
<?php

namespace LibBundle\Util;

class ConstantValueList
{
    public static function get($className, $constantPrefix = null, $isKeyName = false)
    {
        $prefix = empty($constantPrefix) ? '' : $constantPrefix;

        $class = new \ReflectionClass($className);
        $classConstants = $class->getConstants();
        $constantPrefixLength = strlen($prefix);

        $list = array();
        foreach ($classConstants as $key => $value) {
            if (substr($key, 0, $constantPrefixLength) === $prefix) {
                $name = $isKeyName ? substr($key, $constantPrefixLength) : $value;
                $list[ucfirst(strtolower($name))] = $value;
            }
        }

        return $list;
    }
}


text:
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.

using System.Diagnostics.CodeAnalysis;

#if WINDOWS_PHONE
namespace Microsoft.Phone.Controls
#else
namespace System.Windows.Controls
#endif
{
    /// <summary>
    /// Represents the method that will handle the
    /// <see cref="E:System.Windows.Controls.AutoCompleteBox.Populated" />
    /// event of a <see cref="T:System.Windows.Controls.AutoCompleteBox" />
    /// control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">A
    /// <see cref="T:System.Windows.Controls.PopulatedEventArgs" /> that
    /// contains the event data.</param>
    /// <QualityBand>Stable</QualityBand>
    [SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Justification = "There is no generic RoutedEventHandler.")]
    public delegate void PopulatedEventHandler(object sender, PopulatedEventArgs e);
}


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
info: String.prototype.toLocaleLowerCase()
es5id: 15.5.4.17_A1_T7
description: Call toLocaleLowerCase() function of NaN
---*/

Number.prototype.toLocaleLowerCase = String.prototype.toLocaleLowerCase;

//////////////////////////////////////////////////////////////////////////////
//CHECK#1
if (NaN.toLocaleLowerCase()!== "nan") {
  $ERROR('#1: Number.prototype.toLocaleLowerCase = String.prototype.toLocaleLowerCase; NaN.toLocaleLowerCase()=== "nan". Actual: '+NaN.toLocaleLowerCase());
}
//
//////////////////////////////////////////////////////////////////////////////


text:
package com.baislsl.decompiler.structure.attribute;

import com.baislsl.decompiler.DecompileException;
import com.baislsl.decompiler.structure.constantPool.ConstantPool;
import com.baislsl.decompiler.utils.Read;

import java.io.DataInputStream;

/**
 * super class for RuntimeInvisibleParameterAnnotations and RuntimeVisibleTypeAnnotations
 */
public abstract class RuntimeTypeAnnotationsAttr extends Attribute implements AttributeBuilder {
    private static final int TYPE_ANNOTATIONS_NUMBER_SIZE = 2;
    private TypeAnnotation[] typeAnnotations;

    public RuntimeTypeAnnotationsAttr(int attributeNameIndex, int attributeLength) {
        super(attributeNameIndex, attributeLength);
    }

    @Override
    public Attribute build(DataInputStream file, ConstantPool[] constantPools) throws DecompileException {
        int annotationsNum = Read.readBytes(file, TYPE_ANNOTATIONS_NUMBER_SIZE);
        typeAnnotations = new TypeAnnotation[annotationsNum];
        for (int i = 0; i < annotationsNum; i++) {
            typeAnnotations[i] = TypeAnnotation.getTypeAnnotation(file);
        }
        return this;
    }

    public TypeAnnotation[] getTypeAnnotations() {
        return typeAnnotations;
    }
}


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

import java.util.Objects;

import static java.util.Locale.ENGLISH;
import static java.util.Objects.requireNonNull;

public final class CatalogSchemaName
{
    private final String catalogName;
    private final String schemaName;

    public CatalogSchemaName(String catalogName, String schemaName)
    {
        this.catalogName = requireNonNull(catalogName, "catalogName is null").toLowerCase(ENGLISH);
        this.schemaName = requireNonNull(schemaName, "schemaName is null").toLowerCase(ENGLISH);
    }

    public String getCatalogName()
    {
        return catalogName;
    }

    public String getSchemaName()
    {
        return schemaName;
    }

    @Override
    public boolean equals(Object obj)
    {
        if (this == obj) {
            return true;
        }
        if ((obj == null) || (getClass() != obj.getClass())) {
            return false;
        }
        CatalogSchemaName that = (CatalogSchemaName) obj;
        return Objects.equals(catalogName, that.catalogName) &&
                Objects.equals(schemaName, that.schemaName);
    }

    @Override
    public int hashCode()
    {
        return Objects.hash(catalogName, schemaName);
    }

    @Override
    public String toString()
    {
        return catalogName + '.' + schemaName;
    }
}


text:
using System.Collections.Generic;
using Antlr4.Runtime.Misc;
using Parser = HOPL.Grammar.HOPLGrammarParser;
using HOPL.Interpreter.NamespaceTypes;
using Antlr4.Runtime;

namespace HOPL.Interpreter.Exploration
{
    public class FunctionDependencyExplorer : DependencyExplorer
	{
		private Stack<HashSet<string>> scope = new Stack<HashSet<string>>();

		public string FunctionName { get; protected set; }

		public FunctionDependencyExplorer(ImportAccessTable accessTable, string filename, NamespaceString @namespace)
			: base(accessTable, filename, @namespace)
		{ }

		protected void AddDependency(string id, NamespaceString @namespace, ParserRuleContext context)
		{
			NamespaceString actNs = @namespace;

			Import import;
            NamespaceString remaining;
			if (access.TryGetImport(file, @namespace, out import, out remaining))
				actNs = import.NamespaceName + remaining;

			Dependency dep = new Dependency(id, actNs, file, DependencyType.FUNCTION, context);
			if (!Dependencies.Contains(dep))
				Dependencies.Add(dep);
		}

		public HashSet<Dependency> EvaluateDependencies(Parser.FunctionDecContext funcDec)
		{
			EnterFunctionDec(funcDec);
			return Dependencies;
		}

		private bool IsInScope(string id)
		{
			foreach (HashSet<string> set in scope)
				if (set.Contains(id))
					return true;
			return false;
		}

		public override void EnterFunctionDec([NotNull] Parser.FunctionDecContext context)
		{
			FunctionName = context.ID().GetText();

			HashSet<string> args = new HashSet<string>();
			foreach (Parser.ArgContext arg in context.args().arg())
				args.Add(arg.ID().GetText());

			EnterBody(context.body(), args);
		}

		public override void EnterIdentifier([NotNull] Parser.IdentifierContext context)
		{
			Parser.NamespaceContext ns = context.@namespace();
			string id = context.ID().GetText();

			if (ns != null)
                AddDependency(id, new NamespaceString(ns.GetText()), context);
			else if (!IsInScope(id))
                AddDependency(id, @namespace, context);
		}

		public override void EnterBody([NotNull] Parser.BodyContext context)
		{
			EnterBody(context, new HashSet<string>());
		}

		public void EnterBody([NotNull] Parser.BodyContext context, HashSet<string> initScope)
		{
			scope.Push(new HashSet<string>());
			foreach (Parser.StatContext stat in context.stat())
				stat.EnterRule(this);
			scope.Pop();
		}

		public override void EnterAssignStat([NotNull] Parser.AssignStatContext context)
		{
			context.assign().EnterRule(this);
		}

		public override void EnterAssign([NotNull] Parser.AssignContext context)
		{
			context.identifier().EnterRule(this);
			context.expr().EnterRule(this);
		}

		public override void EnterDecStat([NotNull] Parser.DecStatContext context)
		{
			context.varDec().EnterRule(this);
		}

		public override void EnterVarDec([NotNull] Parser.VarDecContext context)
		{
			Parser.ExprContext expr = context.expr();
			if (expr != null)
				expr.EnterRule(this);

			string id = context.ID().GetText();
			scope.Peek().Add(id);
		}

		public override void EnterExprStat([NotNull] Parser.ExprStatContext context)
		{
			context.expr().EnterRule(this);
		}

		public override void EnterReturnStat([NotNull] Parser.ReturnStatContext context)
		{
			context.@return().EnterRule(this);
		}

		public override void EnterReturn([NotNull] Parser.ReturnContext context)
		{
			Parser.ExprContext expr = context.expr();
			if (expr != null)
				expr.EnterRule(this);
		}

		public override void EnterUnpackStat([NotNull] Parser.UnpackStatContext context)
		{
			context.unpack().EnterRule(this);
		}

		public override void EnterUnpack([NotNull] Parser.UnpackContext context)
		{
			context.expr().EnterRule(this);

			foreach (Parser.UnpackedContext unpackable in context.unpacked())
				unpackable.EnterRule(this);
		}

		public override void EnterIdUnpacked([NotNull] Parser.IdUnpackedContext context)
		{
			context.identifier().EnterRule(this);
		}

		public override void EnterDecUnpacked([NotNull] Parser.DecUnpackedContext context)
		{
			scope.Peek().Add(context.ID().GetText());
		}

		public override void EnterIfStat([NotNull] Parser.IfStatContext context)
		{
			context.@if().EnterRule(this);

			foreach (Parser.ElseIfContext elif in context.elseIf())
				elif.EnterRule(this);

			Parser.ElseContext el = context.@else();
			if (el != null)
				el.EnterRule(this);
		}

		public override void EnterIf([NotNull] Parser.IfContext context)
		{
			context.expr().EnterRule(this);
			context.body().EnterRule(this);
		}

		public override void EnterElseIf([NotNull] Parser.ElseIfContext context)
		{
			context.expr().EnterRule(this);
			context.body().EnterRule(this);
		}

		public override void EnterElse([NotNull] Parser.ElseContext context)
		{
			context.body().EnterRule(this);
		}

		public override void EnterWhileStat([NotNull] Parser.WhileStatContext context)
		{
			context.@while().EnterRule(this);
		}

		public override void EnterWhile([NotNull] Parser.WhileContext context)
		{
			context.expr().EnterRule(this);
			context.body().EnterRule(this);
		}

		public override void EnterForStat([NotNull] Parser.ForStatContext context)
		{
			context.@for().EnterRule(this);
		}

		public override void EnterFor([NotNull] Parser.ForContext context)
		{
			scope.Push(new HashSet<string>());

			if (context.declare != null)
				context.declare.EnterRule(this);

			context.predicate.EnterRule(this);

			if (context.reeval != null)
				context.reeval.EnterRule(this);

			context.body().EnterRule(this);

			scope.Pop();
		}

		public override void EnterForeachStat([NotNull] Parser.ForeachStatContext context)
		{
			context.@foreach().EnterRule(this);
		}

		public override void EnterForeach([NotNull] Parser.ForeachContext context)
		{
			context.expr().EnterRule(this);

			HashSet<string> set = new HashSet<string>();
			set.Add(context.ID().GetText());

			EnterBody(context.body(), set);
		}
	}
}


text:
package com.izforge.izpack.integration.packvalidator;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.io.File;

import org.fest.swing.fixture.FrameFixture;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;

import com.izforge.izpack.api.GuiId;
import com.izforge.izpack.api.data.Panel;
import com.izforge.izpack.compiler.container.TestGUIInstallationContainer;
import com.izforge.izpack.installer.data.GUIInstallData;
import com.izforge.izpack.installer.gui.InstallerController;
import com.izforge.izpack.installer.gui.InstallerFrame;
import com.izforge.izpack.installer.gui.IzPanel;
import com.izforge.izpack.installer.panel.Panels;
import com.izforge.izpack.integration.HelperTestMethod;
import com.izforge.izpack.panels.hello.HelloPanel;
import com.izforge.izpack.panels.install.InstallPanel;
import com.izforge.izpack.panels.packs.PacksPanel;
import com.izforge.izpack.panels.simplefinish.SimpleFinishPanel;
import com.izforge.izpack.panels.treepacks.PackValidator;
import com.izforge.izpack.test.Container;
import com.izforge.izpack.test.InstallFile;
import com.izforge.izpack.test.junit.PicoRunner;
import com.izforge.izpack.test.util.TestHousekeeper;

/**
 * Tests that {@link PackValidator}s are invoked during installation.
 *
 * @author Tim Anderson
 */
@RunWith(PicoRunner.class)
@Container(TestGUIInstallationContainer.class)
public class PackValidatorTest
{
    /**
     * Temporary folder to perform installations to.
     */
    @Rule
    public TemporaryFolder temporaryFolder = new TemporaryFolder();

    /**
     * Install data.
     */
    private final GUIInstallData installData;

    /**
     * The installer frame.
     */
    private final InstallerFrame frame;

    /**
     * The installer controller.
     */
    private final InstallerController controller;

    /**
     * The house-keeper.
     */
    private final TestHousekeeper housekeeper;

    /**
     * The panels.
     */
    private final Panels panels;

    /**
     * The frame fixture.
     */
    private FrameFixture frameFixture;

    /**
     * Constructs an <tt>PanelActionValidatorTest</tt>.
     *
     * @param installData the install data
     * @param frame       the installer frame
     * @param controller  the installer controller
     * @param housekeeper the house-keeper
     * @param panels      the panels
     */
    public PackValidatorTest(GUIInstallData installData, InstallerFrame frame, InstallerController controller,
                             TestHousekeeper housekeeper, Panels panels)
    {
        this.installData = installData;
        this.frame = frame;
        this.controller = controller;
        this.housekeeper = housekeeper;
        this.panels = panels;
    }

    /**
     * Sets up the test case.
     */
    @Before
    public void setUp()
    {
        // write to temporary folder so the test doesn't need to be run with elevated permissions
        File installPath = new File(temporaryFolder.getRoot(), "izpackTest");
        assertTrue(installPath.mkdirs());
        installData.setInstallPath(installPath.getAbsolutePath());
    }

    /**
     * Tears down the test case.
     */
    @After
    public void tearDown()
    {
        if (frameFixture != null)
        {
            frameFixture.cleanUp();
        }
    }

    /**
     * Verifies that registered {@link PackValidator}s are invoked by {@link PacksPanel}.
     *
     * @throws Exception for any error
     */
    @Test
    @InstallFile("samples/packvalidators.xml")
    public void testPackValidator() throws Exception
    {
        assertEquals(4, panels.getPanels().size());

        frameFixture = HelperTestMethod.prepareFrameFixture(frame, controller);

        // HelloPanel
        Thread.sleep(2000);
        checkCurrentPanel(HelloPanel.class);
        frameFixture.button(GuiId.BUTTON_NEXT.id).click();

        // PacksPanel
        Thread.sleep(1000);
        checkCurrentPanel(PacksPanel.class);

        //set the Base pack as invalid, and verify clicking next has no effect
        TestPackValidator.setValid("Base", false, installData);
        frameFixture.button(GuiId.BUTTON_NEXT.id).click();
        Thread.sleep(1000);
        checkCurrentPanel(PacksPanel.class);

        // now set it valid. Should be able to go to next panel
        TestPackValidator.setValid("Base", true, installData);
        frameFixture.button(GuiId.BUTTON_NEXT.id).click();

        // InstallPanel
        Thread.sleep(1000);
        checkCurrentPanel(InstallPanel.class);
        frameFixture.button(GuiId.BUTTON_NEXT.id).click();

        // SimpleFinishPanel
        Thread.sleep(1000);
        checkCurrentPanel(SimpleFinishPanel.class);
        frameFixture.button(GuiId.BUTTON_QUIT.id).click();

        // verify the installer has terminated
        housekeeper.waitShutdown(2 * 60 * 1000);
        assertTrue(housekeeper.hasShutdown());
        assertEquals(0, housekeeper.getExitCode());
        assertFalse(housekeeper.getReboot());
    }

    /**
     * Verifies that the current panel is an instance of the specified type.
     *
     * @param type the expected panel type
     */
    private void checkCurrentPanel(Class<? extends IzPanel> type)
    {
        Panel panel = panels.getPanel();
        assertEquals(type.getName(), panel.getClassName());
    }

}


text:
package org.bartelby.interfaces;

import java.io.FileNotFoundException;

public interface Processor {

	public boolean dataIsValid(Object data);

	public Object parse(Object data) throws Exception;

	public boolean dump(Object data);

}


text:
var $ = jQuery;
$(document).ready(function () {
    var baseUrl = '//dev.mousephenotype.org/data';
    $.ajax({url: baseUrl + '/gostats',
        type: 'get',
        async: true,
        success: function (html) {
            $('div#goBlock').html(html);
        },
        error: function () {
            $('div#goBlock').html("Error loading GO annotation stats");
        }
    });

    // initialize sumo selection
    var holderTxt = 'Select dataset: multiple ok';
    $('.goselect').SumoSelect({
        placeholder: holderTxt,
        csvDispCount: 7
    });
    // some sanity checks for selecting checkboxes

    $('li[data-val=nogo], li[data-val=all],li[data-val=onlygo]').click(function () {
        if ($('li.selected').size() == 0) {
            $(this).removeClass('selected');
            var options = $('select option').size();

            for (var i = 0; i < options; i++) {
                $('.goselect')[0].sumo.unSelectItem(i);
            }
        }
        else {
            //console.log($(this).attr('data-val'));

            $('li.selected').removeClass('selected');
            $(this).addClass('selected');
            $('p.SlectBox span').text($(this).text());
        }

    });

    $('li[data-val=exp], li[data-val=ida],li[data-val=igi],li[data-val=imp], li[data-val=ipi],li[data-val=iso], li[data-val=iss]').click(function () {
        if ($('li.selected').attr('data-val') == 'nogo' || $('li.selected').attr('data-val') == 'onlygo' || $('li.selected').attr('data-val') == 'all') {
            $(this).removeClass('selected');
            alert('Sorry, selecting ' + $(this).text() + ' is disabled since you have selected either "No GO" or "Only GO" or "All dataset"');
            $('p.SlectBox span').text($('li.selected').text());
        }
    });

    var conf = {
        externalDbId: 1,
        fileType: '',
        fileName: '',
        solrCoreName: 'gene',
        params: '',
        gridFields: '',
        dumpMode: 'all',
        dogoterm: true
    };

    var commonQ = '(latest_phenotype_status:"Phenotyping Started" OR latest_phenotype_status:"Phenotyping Complete")';
    var commonFl = "mgi_accession_id,marker_symbol,go_term_id,go_term_evid,go_term_domain,go_term_name";
    var rows = 999999;
    var exportUrl = baseUrl + '/export';

    // submit form dynamically
    $('button').click(function () {
        var selectedStr = $('p.SlectBox span').text().trim();
        if (selectedStr == holderTxt) {
            alert("Sorry, you haven't selected dataset to export");
            return false;
        }

        conf.fileType = $(this).hasClass('tsv') ? 'tsv' : 'xls';
        conf.fileName = 'go_dump.' + conf.fileType;

        var qryMap = {
            "No GO": "q=" + commonQ + " AND -go_term_id:*&fl=mgi_accession_id,marker_symbol&rows=" + rows + "&wt=json",
            "All GO": "q=" + commonQ + " AND go_term_id:*&fl=" + commonFl + "&rows=" + rows + "&wt=json",
            "All dataset": "q=" + commonQ + "&fl=" + commonFl + "&rows=" + rows + "&wt=json"
        };
        if (selectedStr != 'No GO' && selectedStr != 'All GO' && selectedStr != 'All dataset') {
            var list = selectedStr.split(',');
            var aQ = [];
            for (var i = 0; i < list.length; i++) {
                aQ.push("go_term_evid:" + list[i].trim());
            }
            var evidParams = "(" + aQ.join(" OR ") + ")";

            conf.gridFields = commonFl;
            conf.params = "q=" + commonQ + " AND " + evidParams + "&fl=" + commonFl + "&rows=" + rows + "&wt=json";
        }
        else {
            if (selectedStr == 'No GO') {
                conf.gridFields = "mgi_accession_id,marker_symbol";
            }
            conf.params = qryMap[selectedStr.trim()];
        }

        var sInputs = '';
        var aParams = [];
        for (var k in conf) {
            aParams.push(k + "=" + conf[k]);
            sInputs += "<input type='text' name='" + k + "' value='" + conf[k] + "'>";
        }

        var form = "<form action='" + exportUrl + "' method=get>" + sInputs + "</form>";
        $(form).appendTo('body').submit().remove();

    });

});


text:
require 'active_job/async_job'

module ActiveJob
  module QueueAdapters
    # == Active Job Async adapter
    #
    # When enqueueing jobs with the Async adapter the job will be executed
    # asynchronously using {AsyncJob}[http://api.rubyonrails.org/classes/ActiveJob/AsyncJob.html].
    #
    # To use +AsyncJob+ set the queue_adapter config to +:async+.
    #
    #   Rails.application.config.active_job.queue_adapter = :async
    class AsyncAdapter
      def enqueue(job) #:nodoc:
        ActiveJob::AsyncJob.enqueue(job.serialize, queue: job.queue_name)
      end

      def enqueue_at(job, timestamp) #:nodoc:
        ActiveJob::AsyncJob.enqueue_at(job.serialize, timestamp, queue: job.queue_name)
      end
    end
  end
end


text:
define([
	"cldr"
], function( Cldr ) {

var defaultLocale,
	Globalize = {};

/**
 * Globalize.load( json )
 *
 * @json [JSON]
 *
 * Load resolved or unresolved cldr data.
 * Somewhat equivalent to previous Globalize.addCultureInfo(...).
 */
Globalize.load = function( json ) {
	Cldr.load( json );
};

/**
 * Globalize.locale( [locale] )
 *
 * @locale [String]
 *
 * Set default locale.
 * Get default locale if locale argument is undefined.
 * Somewhat equivalent to previous culture( selector ).
 */
Globalize.locale = function( locale ) {
	if ( arguments.length ) {
		defaultLocale = new Cldr( locale );
	}
	return defaultLocale;
};

return Globalize;

});


text:
/*jslint browser: true, white: true, vars: true */
/*global jQuery, Samisdat */
(function($) {

    "use strict";

    //productive

	Samisdat.Conway.Cell = function(row, column) {

		var is_living = false;
		var _is_living = false;

		var _was_alive = false;

		var last_birth_in_generation = false;
		var last_death_in_generation = false;

		var get_row = function() {
			return row;
		};
		var get_column = function() {
			return column;
		};

		var death = function(immediately) {
			immediately = (immediately === undefined) ? false : immediately;

			if (immediately === true) {
				is_living = _is_living = false;
				last_death_in_generation = Samisdat.Conway.Generation.get();
			} else {
				_is_living = false;
				last_death_in_generation = Samisdat.Conway.Generation.get() + 1;
			}
		};
		var birth = function(immediately) {

			immediately = (immediately === undefined) ? false : immediately;

			last_birth_in_generation = Samisdat.Conway.Generation.get();

			if (immediately === true) {
				is_living = _is_living = true;
			} else {
				_is_living = true;
				last_birth_in_generation += 1;
			}
			_was_alive = true;
		};

		var live = function() {
			return is_living;
		};

		var neighbour = function(row, column) {

			var _cell = Samisdat.Conway.Population.get_cell(row, column);

			if (_cell === undefined) {
				return 0;
			}
			if (_cell.live === undefined) {
				return 0;
			}
			var live = _cell.live();

			return (live === true) ? 1 : 0;
		};

		var neighbours_pos = function(){
			var pos = [];
			// neighbours on top
			pos.push({y:row - 1, x: column - 1});
			pos.push({y:row - 1, x: column});
			pos.push({y:row - 1, x: column + 1});

			// neighbours on the left and on the right
			pos.push({y:row, x: column - 1});
			pos.push({y:row, x: column + 1});

			// neighbours below
			pos.push({y:row + 1, x: column - 1});
			pos.push({y:row + 1, x: column});
			pos.push({y:row + 1, x: column + 1});

			return pos;

		};

		/**
		 * Cells affect their neighborhood
		 * Living cells create death cells around them
		 * death cells that are surounded by non living cells disappear
		 */
		var neighborhood = function(){
			var pos = neighbours_pos();
			if(is_living === true){
				for(var i = 0, x = pos.length; i < x; i += 1){
					var cell = Samisdat.Conway.Population.get_cell(pos[i].y, pos[i].x);
					if(cell === undefined){
						var death_cell = Samisdat.Conway.Population.add_cell(pos[i].y, pos[i].x);
						death_cell.death(true);
					}
				}
			}
			else if(is_living === false){

				var neighbours = 0;

				for(var i = 0, x = pos.length; i < x; i += 1){
					neighbours += neighbour(pos[i].y, pos[i].x);
				}

				if(neighbours === 0){
					Samisdat.Conway.Population.remove_cell(row, column);
				}
			}

		};

		var next_generation = function() {

			var pos = neighbours_pos();

			var neighbours = 0;

			for(var i = 0, x = pos.length; i < x; i += 1){
				neighbours += neighbour(pos[i].y, pos[i].x);
			}

			if (is_living === false) {
				// Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
				if (neighbours === 3) {
					birth();
				}
				return;
			}

			// Any live cell with two or three live neighbours lives on to the next generation.
			if (neighbours === 2 || neighbours === 3) {
				// do nothing, just mark for generation switch
				_is_living = true;
				return;
			}

			// Any live cell with fewer than two live neighbours dies, as if caused by under-population.
			// Any live cell with more than three live neighbours dies, as if by overcrowding.
			death();

		};
		var replace_generation = function() {
			is_living = _is_living;

			neighborhood();
		};
		return {
			get_row : get_row,
			get_column : get_column,
			neighborhood: neighborhood,
			next_generation : next_generation,
			replace_generation : replace_generation,
			live : live,
			death : death,
			birth : birth
		};
	};

    //\productive

})(jQuery);


text:
package pl.sloniec.backend.runnable;

import java.rmi.RemoteException;
import java.rmi.registry.Registry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import pl.sloniec.backend.impl.InfoInterfaceImpl;
import pl.sloniec.shared.ConfigGlobal;

public class InfoRunnable implements Runnable {
	private Logger logger = LoggerFactory.getLogger(InfoRunnable.class);
	private Registry registry;

	public InfoRunnable(Registry registry) {
		this.registry = registry;
	}

	public void run() {
		try {
			InfoInterfaceImpl info = new InfoInterfaceImpl();
			registry.rebind(ConfigGlobal.RMI_ID_INFO, info);

			logger.info("started");
		} catch (RemoteException e) {
			logger.error(e.getMessage());
		}
	}

}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.fcrepo</groupId>
    <artifactId>fcrepo</artifactId>
    <version>4.7.1</version>
  </parent>
  <groupId>cesnet</groupId>
  <artifactId>cesnet-fcrepo-auth-django</artifactId>

  <name>Fedora Repository Authorization Module for Django Integration</name>
  <description>Provides extension of HttpHeaderPrincipalProvider to handle django groups.</description>
  <packaging>bundle</packaging>

  <properties>
    <osgi.import.packages>
      javax.jcr,
      javax.servlet.http,

      org.modeshape.jcr.*,

      *
    </osgi.import.packages>
    <osgi.export.packages>
      cz.cesnet.fcrepo.auth.django;version=${project.version}
    </osgi.export.packages>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.fcrepo</groupId>
      <artifactId>fcrepo-auth-common</artifactId>
      <version>${project.version}</version>
    </dependency>

    <!-- test gear -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
      </plugin>
      <plugin>
      	<artifactId>maven-failsafe-plugin</artifactId>
        <configuration>
          <!--Set reuseForks=false due to the need for different instances of the-->
          <!--Singleton ServletContainerAuthenticationProvider-->
          <reuseForks>false</reuseForks>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>


text:
package utils

import (
	"testing"

	envmanModels "github.com/bitrise-io/envman/models"
)

func TestGetInputByKey(t *testing.T) {
	env1 := envmanModels.EnvironmentItemModel{
		"KEY1": "value",
	}

	env2 := envmanModels.EnvironmentItemModel{
		"KEY2": "value",
	}

	env3 := envmanModels.EnvironmentItemModel{
		"KEY3": "value",
	}

	envs := []envmanModels.EnvironmentItemModel{env1, env2, env3}

	_, found, err := GetInputByKey(envs, "KEY1")
	if err != nil {
		t.Fatal("Failed to get input by key (KEY1)")
	}
	if !found {
		t.Fatal("Should found env by key (KEY1)")
	}

	_, found, err = GetInputByKey(envs, "KEY4")
	if err != nil {
		t.Fatal("Failed to get input by key (KEY1)")
	}
	if found {
		t.Fatal("Should not found env by key (KEY4)")
	}

	_, found, err = GetInputByKey(envs, "")
	if err != nil {
		t.Fatal("Failed to get input by key ()")
	}
	if found {
		t.Fatal("Should not found env by key ()")
	}
}


text:
package com.zeppamobile.common.cerealwrapper;

import java.io.Serializable;

/**
 *
 * @author Pete Schuette
 *
 *
Base Class for CerealWrapper classes. CerealWrapper is a pun on
 *         serialized wrapper and the objects are used to pass data between
 *         modules.

 *
 */
public abstract class CerealWrapper implements Serializable {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Entity id (key.getId)
	 */
	protected Long identifier;

	public Long getIdentifier() {
		return identifier;
	}

	public void setIdentifier(Long identifier) {
		this.identifier = identifier;
	}

}


text:
@implementation BFAtomPerson

- (id)initWithXMLElement:(ONOXMLElement *)element {
    if (self = [super init]) {
        self.name = [[element firstChildWithTag:@"name"] stringValue];
        self.uri = [[element firstChildWithTag:@"uri"] stringValue];
    }
    return self;
}

@end


text:
const webpack = require('webpack');
const path = require(`path`);

var options = {
  devtool: 'source-map',
  target: 'electron-main',
  entry: './src/main.js',

  output: {
    path: __dirname + '/build/',
    publicPath: '',
    filename: 'main.js',
    sourceMapFilename: 'main.js.map',
    chunkFilename: '[id].chunk.js'
  },

  resolve: {
    extensions: ['.ts','.js','.jsx','.json', '.css', '.html']
  },
  /**
   * Disables webpack processing of __dirname and __filename.
   * If you run the bundle in node.js it falls back to these values of node.js.
   * https://github.com/webpack/webpack/issues/2010
   */
  node: {
    __dirname: false,
    __filename: false
  },

  plugins: [
    new webpack.NamedModulesPlugin()
  ],
  module: {
    rules: [
      {
        test: /\.(png|jpg|gif|icns|html)$/,
        exclude: path.resolve(__dirname, `env.json`),
        use: [
          {
            loader: 'file-loader',
            options: {
              name: '[name].[ext]'
            }
          }
        ]
      }
    ]
  }

};

module.exports = options;


text:
vim-github-colorscheme
===

A vim colorscheme based on github's syntax highlighting. Originally created by
[Anthony Carapetis](http://www.vim.org/scripts/script.php?script_id=2855)

```viml
" ~/.vimrc
colorscheme github
```

Screenshots
---

![Screenshot](http://i.imgur.com/LJXdy.png )

![Diffsplit screenshot](http://i.imgur.com/RKtVD.png)

Install it using Pathogen or Vundle.

License
---

Distributed under the same terms as Vim itself. See `:help license`.


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE article PUBLIC "-//OASIS//DTD DocBook XML V4.4//EN"
          "http://www.oasis-open.org/docbook/xml/4.4/docbookx.dtd">
<article>
<articleinfo>
<title>Unit Test: profile.001</title>
<releaseinfo role="CVS">$Id: profile.001.xml 4056 2004-11-23 13:28:50Z nwalsh $</releaseinfo>
<author><firstname>John</firstname><surname>Himpel</surname>
        <affiliation><address><email>jwhimpel@users.sourceforge.net</email></address></affiliation>
</author>
</articleinfo>

<para>Profile and linkends attribute.</para>

<screen>
xxxxxxx <co id="id-co" linkends="co"/>
</screen>

<calloutlist>
<callout arearefs="id-co" id="co">
<para>xxxx</para>
</callout>
</calloutlist>
</article>


text:
'use strict';

import PictawallModel from './abstract/PictawallModel';

/**
 * Message model.
 *
 * @class MessageModel
 * @extends PictawallModel
 */
class MessageModel extends PictawallModel {

  /**
   * @param {!Sdk} sdk The instance of the SDK.
   */
  constructor(sdk) {
    super(sdk);
  }

  /**
   * @inheritDoc
   */
  get type() {
    return 'message';
  }
}

export default MessageModel;


text:
extern const struct ManifestMOAttributes {
	__unsafe_unretained NSString *hasUnstagedChanges;
	__unsafe_unretained NSString *manifestDateCreated;
	__unsafe_unretained NSString *manifestDateLastOpened;
	__unsafe_unretained NSString *manifestDateModified;
	__unsafe_unretained NSString *manifestParentDirectoryURL;
	__unsafe_unretained NSString *manifestURL;
	__unsafe_unretained NSString *manifestUserName;
	__unsafe_unretained NSString *originalManifest;
	__unsafe_unretained NSString *title;
} ManifestMOAttributes;

extern const struct ManifestMORelationships {
	__unsafe_unretained NSString *applications;
	__unsafe_unretained NSString *catalogInfos;
	__unsafe_unretained NSString *catalogs;
	__unsafe_unretained NSString *conditionalItems;
	__unsafe_unretained NSString *includedManifests;
	__unsafe_unretained NSString *includedManifestsFaster;
	__unsafe_unretained NSString *managedInstalls;
	__unsafe_unretained NSString *managedInstallsFaster;
	__unsafe_unretained NSString *managedUninstalls;
	__unsafe_unretained NSString *managedUninstallsFaster;
	__unsafe_unretained NSString *managedUpdates;
	__unsafe_unretained NSString *managedUpdatesFaster;
	__unsafe_unretained NSString *manifestInfos;
	__unsafe_unretained NSString *optionalInstalls;
	__unsafe_unretained NSString *optionalInstallsFaster;
	__unsafe_unretained NSString *referencingManifests;
} ManifestMORelationships;

extern const struct ManifestMOFetchedProperties {
	__unsafe_unretained NSString *allIncludedManifests;
	__unsafe_unretained NSString *allManagedInstalls;
	__unsafe_unretained NSString *allManagedUninstalls;
	__unsafe_unretained NSString *allManagedUpdates;
	__unsafe_unretained NSString *allOptionalInstalls;
	__unsafe_unretained NSString *allReferencingManifests;
} ManifestMOFetchedProperties;

@class ApplicationMO;
@class CatalogInfoMO;
@class CatalogMO;
@class ConditionalItemMO;
@class ManifestInfoMO;
@class StringObjectMO;
@class ManagedInstallMO;
@class StringObjectMO;
@class ManagedUninstallMO;
@class StringObjectMO;
@class ManagedUpdateMO;
@class StringObjectMO;
@class ManifestInfoMO;
@class OptionalInstallMO;
@class StringObjectMO;
@class StringObjectMO;

@class NSObject;

@class NSObject;

@class NSObject;

@interface ManifestMOID : NSManagedObjectID {}
@end

@interface _ManifestMO : NSManagedObject {}
+ (id)insertInManagedObjectContext:(NSManagedObjectContext*)moc_;
+ (NSString*)entityName;
+ (NSEntityDescription*)entityInManagedObjectContext:(NSManagedObjectContext*)moc_;
@property (nonatomic, readonly, strong) ManifestMOID* objectID;

@property (nonatomic, strong) NSNumber* hasUnstagedChanges;

@property (atomic) BOOL hasUnstagedChangesValue;
- (BOOL)hasUnstagedChangesValue;
- (void)setHasUnstagedChangesValue:(BOOL)value_;

//- (BOOL)validateHasUnstagedChanges:(id*)value_ error:(NSError**)error_;

@property (nonatomic, strong) NSDate* manifestDateCreated;

//- (BOOL)validateManifestDateCreated:(id*)value_ error:(NSError**)error_;

@property (nonatomic, strong) NSDate* manifestDateLastOpened;

//- (BOOL)validateManifestDateLastOpened:(id*)value_ error:(NSError**)error_;

@property (nonatomic, strong) NSDate* manifestDateModified;

//- (BOOL)validateManifestDateModified:(id*)value_ error:(NSError**)error_;

@property (nonatomic, strong) id manifestParentDirectoryURL;

//- (BOOL)validateManifestParentDirectoryURL:(id*)value_ error:(NSError**)error_;

@property (nonatomic, strong) id manifestURL;

//- (BOOL)validateManifestURL:(id*)value_ error:(NSError**)error_;

@property (nonatomic, strong) NSString* manifestUserName;

//- (BOOL)validateManifestUserName:(id*)value_ error:(NSError**)error_;

@property (nonatomic, strong) id originalManifest;

//- (BOOL)validateOriginalManifest:(id*)value_ error:(NSError**)error_;

@property (nonatomic, strong) NSString* title;

//- (BOOL)validateTitle:(id*)value_ error:(NSError**)error_;

@property (nonatomic, strong) NSSet *applications;

- (NSMutableSet*)applicationsSet;

@property (nonatomic, strong) NSSet *catalogInfos;

- (NSMutableSet*)catalogInfosSet;

@property (nonatomic, strong) NSSet *catalogs;

- (NSMutableSet*)catalogsSet;

@property (nonatomic, strong) NSSet *conditionalItems;

- (NSMutableSet*)conditionalItemsSet;

@property (nonatomic, strong) NSSet *includedManifests;

- (NSMutableSet*)includedManifestsSet;

@property (nonatomic, strong) NSSet *includedManifestsFaster;

- (NSMutableSet*)includedManifestsFasterSet;

@property (nonatomic, strong) NSSet *managedInstalls;

- (NSMutableSet*)managedInstallsSet;

@property (nonatomic, strong) NSSet *managedInstallsFaster;

- (NSMutableSet*)managedInstallsFasterSet;

@property (nonatomic, strong) NSSet *managedUninstalls;

- (NSMutableSet*)managedUninstallsSet;

@property (nonatomic, strong) NSSet *managedUninstallsFaster;

- (NSMutableSet*)managedUninstallsFasterSet;

@property (nonatomic, strong) NSSet *managedUpdates;

- (NSMutableSet*)managedUpdatesSet;

@property (nonatomic, strong) NSSet *managedUpdatesFaster;

- (NSMutableSet*)managedUpdatesFasterSet;

@property (nonatomic, strong) NSSet *manifestInfos;

- (NSMutableSet*)manifestInfosSet;

@property (nonatomic, strong) NSSet *optionalInstalls;

- (NSMutableSet*)optionalInstallsSet;

@property (nonatomic, strong) NSSet *optionalInstallsFaster;

- (NSMutableSet*)optionalInstallsFasterSet;

@property (nonatomic, strong) NSSet *referencingManifests;

- (NSMutableSet*)referencingManifestsSet;

@property (nonatomic, readonly) NSArray *allIncludedManifests;

@property (nonatomic, readonly) NSArray *allManagedInstalls;

@property (nonatomic, readonly) NSArray *allManagedUninstalls;

@property (nonatomic, readonly) NSArray *allManagedUpdates;

@property (nonatomic, readonly) NSArray *allOptionalInstalls;

@property (nonatomic, readonly) NSArray *allReferencingManifests;

@end

@interface _ManifestMO (ApplicationsCoreDataGeneratedAccessors)
- (void)addApplications:(NSSet*)value_;
- (void)removeApplications:(NSSet*)value_;
- (void)addApplicationsObject:(ApplicationMO*)value_;
- (void)removeApplicationsObject:(ApplicationMO*)value_;

@end

@interface _ManifestMO (CatalogInfosCoreDataGeneratedAccessors)
- (void)addCatalogInfos:(NSSet*)value_;
- (void)removeCatalogInfos:(NSSet*)value_;
- (void)addCatalogInfosObject:(CatalogInfoMO*)value_;
- (void)removeCatalogInfosObject:(CatalogInfoMO*)value_;

@end

@interface _ManifestMO (CatalogsCoreDataGeneratedAccessors)
- (void)addCatalogs:(NSSet*)value_;
- (void)removeCatalogs:(NSSet*)value_;
- (void)addCatalogsObject:(CatalogMO*)value_;
- (void)removeCatalogsObject:(CatalogMO*)value_;

@end

@interface _ManifestMO (ConditionalItemsCoreDataGeneratedAccessors)
- (void)addConditionalItems:(NSSet*)value_;
- (void)removeConditionalItems:(NSSet*)value_;
- (void)addConditionalItemsObject:(ConditionalItemMO*)value_;
- (void)removeConditionalItemsObject:(ConditionalItemMO*)value_;

@end

@interface _ManifestMO (IncludedManifestsCoreDataGeneratedAccessors)
- (void)addIncludedManifests:(NSSet*)value_;
- (void)removeIncludedManifests:(NSSet*)value_;
- (void)addIncludedManifestsObject:(ManifestInfoMO*)value_;
- (void)removeIncludedManifestsObject:(ManifestInfoMO*)value_;

@end

@interface _ManifestMO (IncludedManifestsFasterCoreDataGeneratedAccessors)
- (void)addIncludedManifestsFaster:(NSSet*)value_;
- (void)removeIncludedManifestsFaster:(NSSet*)value_;
- (void)addIncludedManifestsFasterObject:(StringObjectMO*)value_;
- (void)removeIncludedManifestsFasterObject:(StringObjectMO*)value_;

@end

@interface _ManifestMO (ManagedInstallsCoreDataGeneratedAccessors)
- (void)addManagedInstalls:(NSSet*)value_;
- (void)removeManagedInstalls:(NSSet*)value_;
- (void)addManagedInstallsObject:(ManagedInstallMO*)value_;
- (void)removeManagedInstallsObject:(ManagedInstallMO*)value_;

@end

@interface _ManifestMO (ManagedInstallsFasterCoreDataGeneratedAccessors)
- (void)addManagedInstallsFaster:(NSSet*)value_;
- (void)removeManagedInstallsFaster:(NSSet*)value_;
- (void)addManagedInstallsFasterObject:(StringObjectMO*)value_;
- (void)removeManagedInstallsFasterObject:(StringObjectMO*)value_;

@end

@interface _ManifestMO (ManagedUninstallsCoreDataGeneratedAccessors)
- (void)addManagedUninstalls:(NSSet*)value_;
- (void)removeManagedUninstalls:(NSSet*)value_;
- (void)addManagedUninstallsObject:(ManagedUninstallMO*)value_;
- (void)removeManagedUninstallsObject:(ManagedUninstallMO*)value_;

@end

@interface _ManifestMO (ManagedUninstallsFasterCoreDataGeneratedAccessors)
- (void)addManagedUninstallsFaster:(NSSet*)value_;
- (void)removeManagedUninstallsFaster:(NSSet*)value_;
- (void)addManagedUninstallsFasterObject:(StringObjectMO*)value_;
- (void)removeManagedUninstallsFasterObject:(StringObjectMO*)value_;

@end

@interface _ManifestMO (ManagedUpdatesCoreDataGeneratedAccessors)
- (void)addManagedUpdates:(NSSet*)value_;
- (void)removeManagedUpdates:(NSSet*)value_;
- (void)addManagedUpdatesObject:(ManagedUpdateMO*)value_;
- (void)removeManagedUpdatesObject:(ManagedUpdateMO*)value_;

@end

@interface _ManifestMO (ManagedUpdatesFasterCoreDataGeneratedAccessors)
- (void)addManagedUpdatesFaster:(NSSet*)value_;
- (void)removeManagedUpdatesFaster:(NSSet*)value_;
- (void)addManagedUpdatesFasterObject:(StringObjectMO*)value_;
- (void)removeManagedUpdatesFasterObject:(StringObjectMO*)value_;

@end

@interface _ManifestMO (ManifestInfosCoreDataGeneratedAccessors)
- (void)addManifestInfos:(NSSet*)value_;
- (void)removeManifestInfos:(NSSet*)value_;
- (void)addManifestInfosObject:(ManifestInfoMO*)value_;
- (void)removeManifestInfosObject:(ManifestInfoMO*)value_;

@end

@interface _ManifestMO (OptionalInstallsCoreDataGeneratedAccessors)
- (void)addOptionalInstalls:(NSSet*)value_;
- (void)removeOptionalInstalls:(NSSet*)value_;
- (void)addOptionalInstallsObject:(OptionalInstallMO*)value_;
- (void)removeOptionalInstallsObject:(OptionalInstallMO*)value_;

@end

@interface _ManifestMO (OptionalInstallsFasterCoreDataGeneratedAccessors)
- (void)addOptionalInstallsFaster:(NSSet*)value_;
- (void)removeOptionalInstallsFaster:(NSSet*)value_;
- (void)addOptionalInstallsFasterObject:(StringObjectMO*)value_;
- (void)removeOptionalInstallsFasterObject:(StringObjectMO*)value_;

@end

@interface _ManifestMO (ReferencingManifestsCoreDataGeneratedAccessors)
- (void)addReferencingManifests:(NSSet*)value_;
- (void)removeReferencingManifests:(NSSet*)value_;
- (void)addReferencingManifestsObject:(StringObjectMO*)value_;
- (void)removeReferencingManifestsObject:(StringObjectMO*)value_;

@end

@interface _ManifestMO (CoreDataGeneratedPrimitiveAccessors)

- (NSNumber*)primitiveHasUnstagedChanges;
- (void)setPrimitiveHasUnstagedChanges:(NSNumber*)value;

- (BOOL)primitiveHasUnstagedChangesValue;
- (void)setPrimitiveHasUnstagedChangesValue:(BOOL)value_;

- (NSDate*)primitiveManifestDateCreated;
- (void)setPrimitiveManifestDateCreated:(NSDate*)value;

- (NSDate*)primitiveManifestDateLastOpened;
- (void)setPrimitiveManifestDateLastOpened:(NSDate*)value;

- (NSDate*)primitiveManifestDateModified;
- (void)setPrimitiveManifestDateModified:(NSDate*)value;

- (id)primitiveManifestParentDirectoryURL;
- (void)setPrimitiveManifestParentDirectoryURL:(id)value;

- (id)primitiveManifestURL;
- (void)setPrimitiveManifestURL:(id)value;

- (NSString*)primitiveManifestUserName;
- (void)setPrimitiveManifestUserName:(NSString*)value;

- (id)primitiveOriginalManifest;
- (void)setPrimitiveOriginalManifest:(id)value;

- (NSString*)primitiveTitle;
- (void)setPrimitiveTitle:(NSString*)value;

- (NSMutableSet*)primitiveApplications;
- (void)setPrimitiveApplications:(NSMutableSet*)value;

- (NSMutableSet*)primitiveCatalogInfos;
- (void)setPrimitiveCatalogInfos:(NSMutableSet*)value;

- (NSMutableSet*)primitiveCatalogs;
- (void)setPrimitiveCatalogs:(NSMutableSet*)value;

- (NSMutableSet*)primitiveConditionalItems;
- (void)setPrimitiveConditionalItems:(NSMutableSet*)value;

- (NSMutableSet*)primitiveIncludedManifests;
- (void)setPrimitiveIncludedManifests:(NSMutableSet*)value;

- (NSMutableSet*)primitiveIncludedManifestsFaster;
- (void)setPrimitiveIncludedManifestsFaster:(NSMutableSet*)value;

- (NSMutableSet*)primitiveManagedInstalls;
- (void)setPrimitiveManagedInstalls:(NSMutableSet*)value;

- (NSMutableSet*)primitiveManagedInstallsFaster;
- (void)setPrimitiveManagedInstallsFaster:(NSMutableSet*)value;

- (NSMutableSet*)primitiveManagedUninstalls;
- (void)setPrimitiveManagedUninstalls:(NSMutableSet*)value;

- (NSMutableSet*)primitiveManagedUninstallsFaster;
- (void)setPrimitiveManagedUninstallsFaster:(NSMutableSet*)value;

- (NSMutableSet*)primitiveManagedUpdates;
- (void)setPrimitiveManagedUpdates:(NSMutableSet*)value;

- (NSMutableSet*)primitiveManagedUpdatesFaster;
- (void)setPrimitiveManagedUpdatesFaster:(NSMutableSet*)value;

- (NSMutableSet*)primitiveManifestInfos;
- (void)setPrimitiveManifestInfos:(NSMutableSet*)value;

- (NSMutableSet*)primitiveOptionalInstalls;
- (void)setPrimitiveOptionalInstalls:(NSMutableSet*)value;

- (NSMutableSet*)primitiveOptionalInstallsFaster;
- (void)setPrimitiveOptionalInstallsFaster:(NSMutableSet*)value;

- (NSMutableSet*)primitiveReferencingManifests;
- (void)setPrimitiveReferencingManifests:(NSMutableSet*)value;

@end


text:
package org.apache.spark.util

import java.util.concurrent.CopyOnWriteArrayList

import scala.collection.JavaConverters._
import scala.reflect.ClassTag
import scala.util.control.NonFatal

import com.codahale.metrics.Timer

import org.apache.spark.internal.Logging

/**
 * An event bus which posts events to its listeners.
 */
private[spark] trait ListenerBus[L <: AnyRef, E] extends Logging {

  private[this] val listenersPlusTimers = new CopyOnWriteArrayList[(L, Option[Timer])]

  // Marked `private[spark]` for access in tests.
  private[spark] def listeners = listenersPlusTimers.asScala.map(_._1).asJava

  /**
   * Returns a CodaHale metrics Timer for measuring the listener's event processing time.
   * This method is intended to be overridden by subclasses.
   */
  protected def getTimer(listener: L): Option[Timer] = None

  /**
   * Add a listener to listen events. This method is thread-safe and can be called in any thread.
   */
  final def addListener(listener: L): Unit = {
    listenersPlusTimers.add((listener, getTimer(listener)))
  }

  /**
   * Remove a listener and it won't receive any events. This method is thread-safe and can be called
   * in any thread.
   */
  final def removeListener(listener: L): Unit = {
    listenersPlusTimers.asScala.find(_._1 eq listener).foreach { listenerAndTimer =>
      listenersPlusTimers.remove(listenerAndTimer)
    }
  }

  /**
   * Remove all listeners and they won't receive any events. This method is thread-safe and can be
   * called in any thread.
   */
  final def removeAllListeners(): Unit = {
    listenersPlusTimers.clear()
  }

  /**
   * This can be overridden by subclasses if there is any extra cleanup to do when removing a
   * listener.  In particular AsyncEventQueues can clean up queues in the LiveListenerBus.
   */
  def removeListenerOnError(listener: L): Unit = {
    removeListener(listener)
  }

  /**
   * Post the event to all registered listeners. The `postToAll` caller should guarantee calling
   * `postToAll` in the same thread for all events.
   */
  def postToAll(event: E): Unit = {
    // JavaConverters can create a JIterableWrapper if we use asScala.
    // However, this method will be called frequently. To avoid the wrapper cost, here we use
    // Java Iterator directly.
    val iter = listenersPlusTimers.iterator
    while (iter.hasNext) {
      val listenerAndMaybeTimer = iter.next()
      val listener = listenerAndMaybeTimer._1
      val maybeTimer = listenerAndMaybeTimer._2
      val maybeTimerContext = if (maybeTimer.isDefined) {
        maybeTimer.get.time()
      } else {
        null
      }
      try {
        doPostEvent(listener, event)
        if (Thread.interrupted()) {
          // We want to throw the InterruptedException right away so we can associate the interrupt
          // with this listener, as opposed to waiting for a queue.take() etc. to detect it.
          throw new InterruptedException()
        }
      } catch {
        case ie: InterruptedException =>
          logError(s"Interrupted while posting to ${Utils.getFormattedClassName(listener)}.  " +
            s"Removing that listener.", ie)
          removeListenerOnError(listener)
        case NonFatal(e) if !isIgnorableException(e) =>
          logError(s"Listener ${Utils.getFormattedClassName(listener)} threw an exception", e)
      } finally {
        if (maybeTimerContext != null) {
          maybeTimerContext.stop()
        }
      }
    }
  }

  /**
   * Post an event to the specified listener. `onPostEvent` is guaranteed to be called in the same
   * thread for all listeners.
   */
  protected def doPostEvent(listener: L, event: E): Unit

  /** Allows bus implementations to prevent error logging for certain exceptions. */
  protected def isIgnorableException(e: Throwable): Boolean = false

  private[spark] def findListenersByClass[T <: L : ClassTag](): Seq[T] = {
    val c = implicitly[ClassTag[T]].runtimeClass
    listeners.asScala.filter(_.getClass == c).map(_.asInstanceOf[T]).toSeq
  }

}


text:
package iso20022

// Choice of format for the date.
type DateCode18Choice struct {

	// Date expressed as an ISO 20022 code.
	Code *DateType5Code `xml:"Cd"`

	// Date expressed as a proprietary code.
	Proprietary *GenericIdentification30 `xml:"Prtry"`
}

func (d *DateCode18Choice) SetCode(value string) {
	d.Code = (*DateType5Code)(&value)
}

func (d *DateCode18Choice) AddProprietary() *GenericIdentification30 {
	d.Proprietary = new(GenericIdentification30)
	return d.Proprietary
}


text:
<?php

/**
 * This is the model class for table "order_log".
 *
 * The followings are the available columns in table 'order_log':
 * @property string $log_id
 * @property integer $order_id
 * @property integer $op_id
 * @property string $op_name
 * @property string $log_text
 * @property string $action_time
 * @property string $behavior
 * @property string $result
 * @property string $origin_body
 */
class OrderLog extends CActiveRecord
{
    private $user_id;
    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return OrderLog the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'order_log';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('user_id', 'numerical', 'integerOnly'=>true),
            array('order_id', 'length', 'max'=>20),
            array('op_name', 'length', 'max'=>45),
            array('action_time', 'length', 'max'=>10),
            array('result', 'length', 'max'=>7),
            array('log_text', 'safe'),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('log_id, order_id, op_name, log_text, action_time, user_id, result', 'safe', 'on'=>'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'log_id' => '日志id',
            'order_id' => '订单id',
            'op_name' => '操作名称',
            'log_text' => '日志内容',
            'action_time' => '操作时间',
            'user_id' => '用户id',
            'result' => '返回结果',
            'origin_body' => 'Request 数据',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('log_id',$this->log_id,true);
        $criteria->compare('order_id',$this->order_id,true);
        $criteria->compare('op_name',$this->op_name,true);
        $criteria->compare('log_text',$this->log_text,true);
        $criteria->compare('action_time',$this->action_time,true);
        $criteria->compare('user_id',$this->user_id);
        $criteria->compare('result',$this->result,true);
        $criteria->compare('origin_body',$this->origin_body,true);

        $criteria->order='log_id desc';

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
        ));
    }

    protected function beforeSave(){
        $this->action_time = date('Y-m-d H:i:s', time());
        $this->user_id = Yii::app()->user->id != 0 ? Yii::app()->user->id : '999999';
        parent::beforeSave();
        return true;
    }

    public function showOp($log_id){
        $logOp = OrderLog::model()->findByPk($log_id);
        $users = Users::model()->findByPk($logOp->user_id);
        $op = $users->username . ' ' .$logOp->op_name .  " order " .$logOp->order_id;
        return $op;
    }
}


text:
<mvc:View
		xmlns:mvc="sap.ui.core.mvc"
		xmlns:vp="sap.ui.core.qunit.mvc.viewprocessing"
		xmlns="sap.m">

	<vp:SimpleAggregationsControl id="mySimpleAggregationsControl">
	</vp:SimpleAggregationsControl>

	<vp:SimpleAggregationsControl id="mySimpleAggregationsControl2">
		<vp:alternativeContent>
			<Button id="InnerButton122" text="A" />
		</vp:alternativeContent>
	</vp:SimpleAggregationsControl>

</mvc:View>


text:
import {
  GraphQLObjectType,
  GraphQLInt,
  GraphQLString,
  GraphQLBoolean,
} from 'graphql'
import usersFollowing from './../../queries/facets/userFollowing'

function followingUrl() {
  return {
    type: GraphQLString,
    description: 'URI to get data on the people this person follows',
    resolve: (obj) => {
      const brackIndex = obj.following_url.indexOf('{')
      return obj.following_url.slice(0, brackIndex)
    },
  }
}

const UserInfoType = new GraphQLObjectType({
  name: 'UserInfo',
  description: 'Basic information of a GitHub user',
  fields: {
    login: { type: GraphQLString },
    id: { type: GraphQLInt },
    avatar_url: { type: GraphQLString },
    gravatar_id: { type: GraphQLString },
    url: { type: GraphQLString },
    html_url: { type: GraphQLString },
    followers_url: { type: GraphQLString },
    following_url: followingUrl(),
    gists_url: { type: GraphQLString },
    starred_url: { type: GraphQLString },
    subscriptions_url: { type: GraphQLString },
    organizations_url: { type: GraphQLString },
    repos_url: { type: GraphQLString },
    events_url: { type: GraphQLString },
    received_events_url: { type: GraphQLString },
    type: { type: GraphQLString },
    site_admin: { type: GraphQLBoolean },
    name: { type: GraphQLString },
    company: { type: GraphQLString },
    blog: { type: GraphQLString },
    location: { type: GraphQLString },
    email: { type: GraphQLString },
    hireable: { type: GraphQLBoolean },
    bio: { type: GraphQLString },
    public_repos: { type: GraphQLInt },
    public_gists: { type: GraphQLInt },
    followers: { type: GraphQLInt },
    following: { type: GraphQLInt },
    created_at: { type: GraphQLString },
    updated_at: { type: GraphQLString },
    usersFollowing,
  },
})

export default UserInfoType


text:
namespace gui {

HeatMapDataSource::HeatMapDataSource(utl::Logger* logger,
                                     const std::string& name,
                                     const std::string& short_name,
                                     const std::string& settings_group)
    : name_(name),
      short_name_(short_name),
      settings_group_(settings_group),
      destroy_map_(true),
      use_dbu_(false),
      populated_(false),
      colors_correct_(false),
      issue_redraw_(true),
      block_(nullptr),
      logger_(logger),
      grid_x_size_(10.0),
      grid_y_size_(10.0),
      display_range_min_(0.0),
      display_range_max_(100.0),
      draw_below_min_display_range_(false),
      draw_above_max_display_range_(true),
      color_alpha_(150),
      log_scale_(false),
      reverse_log_(false),
      show_numbers_(false),
      show_legend_(false),
      map_(),
      renderer_(std::make_unique<HeatMapRenderer>(*this)),
      setup_(nullptr),
      color_generator_(SpectrumGenerator(100.0))
{
  // ensure color map is initialized
  updateMapColors();
}

HeatMapDataSource::~HeatMapDataSource()
{
  Gui::get()->unregisterHeatMap(this);
}

void HeatMapDataSource::registerHeatMap()
{
  Gui::get()->registerHeatMap(this);
}

void HeatMapDataSource::dumpToFile(const std::string& file)
{
  ensureMap();

  if (!isPopulated()) {
    logger_->error(utl::GUI, 72, "\"{}\" is not populated with data.", name_);
  }

  std::ofstream csv(file);
  if (!csv.is_open()) {
    logger_->error(utl::GUI, 73, "Unable to open {}", file);
  }

  const double dbu_to_micron = block_->getDbUnitsPerMicron();

  csv << "x0,y0,x1,y1,value" << std::endl;
  for (const auto& [box, box_value] : map_) {
    if (!box_value->has_value) {
      continue;
    }
    const odb::Rect& box_rect = box_value->rect;
    const double scaled_value = convertPercentToValue(box_value->value);

    csv << std::defaultfloat << std::setprecision(4);
    csv << box_rect.xMin() / dbu_to_micron << ",";
    csv << box_rect.yMin() / dbu_to_micron << ",";
    csv << box_rect.xMax() / dbu_to_micron << ",";
    csv << box_rect.yMax() / dbu_to_micron << ",";
    csv << std::scientific << std::setprecision(6);
    csv << scaled_value << std::endl;
  }

  csv.close();
}

void HeatMapDataSource::redraw()
{
  ensureMap();

  if (issue_redraw_) {
    renderer_->redraw();
  }
}

void HeatMapDataSource::setColorAlpha(int alpha)
{
  color_alpha_
      = boundValue<int>(alpha, getColorAlphaMinimum(), getColorAlphaMaximum());
  updateMapColors();

  redraw();
}

void HeatMapDataSource::setDisplayRange(double min, double max)
{
  if (max < min) {
    std::swap(min, max);
  }

  display_range_min_ = boundValue<double>(
      min, getDisplayRangeMinimumValue(), getDisplayRangeMaximumValue());
  display_range_max_ = boundValue<double>(
      max, getDisplayRangeMinimumValue(), getDisplayRangeMaximumValue());

  updateMapColors();

  redraw();
}

void HeatMapDataSource::setDrawBelowRangeMin(bool show)
{
  draw_below_min_display_range_ = show;

  redraw();
}

void HeatMapDataSource::setDrawAboveRangeMax(bool show)
{
  draw_above_max_display_range_ = show;

  redraw();
}

void HeatMapDataSource::setGridSizes(double x, double y)
{
  bool changed = false;
  if (grid_x_size_ != x) {
    grid_x_size_ = boundValue<double>(
        x, getGridSizeMinimumValue(), getGridSizeMaximumValue());
    changed = true;
  }
  if (grid_y_size_ != y) {
    grid_y_size_ = boundValue<double>(
        y, getGridSizeMinimumValue(), getGridSizeMaximumValue());
    changed = true;
  }

  if (changed) {
    destroyMap();
  }
}

void HeatMapDataSource::setLogScale(bool scale)
{
  log_scale_ = scale;
  updateMapColors();

  redraw();
}

void HeatMapDataSource::setReverseLogScale(bool reverse)
{
  reverse_log_ = reverse;
  updateMapColors();

  redraw();
}

void HeatMapDataSource::setShowNumbers(bool numbers)
{
  show_numbers_ = numbers;

  redraw();
}

void HeatMapDataSource::setShowLegend(bool legend)
{
  show_legend_ = legend;

  redraw();
}

const Painter::Color HeatMapDataSource::getColor(double value) const
{
  auto find_val
      = std::find_if(color_lower_bounds_.begin(),
                     color_lower_bounds_.end(),
                     [value](const double other) { return other >= value; });
  const double color_index
      = std::distance(color_lower_bounds_.begin(), find_val);
  return color_generator_.getColor(
      100.0 * color_index / color_generator_.getColorCount(), color_alpha_);
}

void HeatMapDataSource::showSetup()
{
  if (setup_ == nullptr) {
    setup_ = new HeatMapSetup(*this,
                              QString::fromStdString(name_),
                              use_dbu_,
                              block_->getDbUnitsPerMicron());

    QObject::connect(setup_, &QDialog::finished, &QObject::deleteLater);
    QObject::connect(
        setup_, &QObject::destroyed, [this]() { setup_ = nullptr; });

    setup_->show();
  } else {
    setup_->raise();
  }
}

const std::string HeatMapDataSource::formatValue(double value,
                                                 bool legend) const
{
  QString text;
  text.setNum(value, 'f', 2);
  if (legend) {
    text += "%";
  }
  return text.toStdString();
}

void HeatMapDataSource::addBooleanSetting(
    const std::string& name,
    const std::string& label,
    const std::function<bool(void)>& getter,
    const std::function<void(bool)>& setter)
{
  settings_.push_back(MapSettingBoolean{name, label, getter, setter});
}

void HeatMapDataSource::addMultipleChoiceSetting(
    const std::string& name,
    const std::string& label,
    const std::function<std::vector<std::string>(void)>& choices,
    const std::function<std::string(void)>& getter,
    const std::function<void(std::string)>& setter)
{
  settings_.push_back(
      MapSettingMultiChoice{name, label, choices, getter, setter});
}

const Renderer::Settings HeatMapDataSource::getSettings() const
{
  Renderer::Settings settings{{"DisplayMin", display_range_min_},
                              {"DisplayMax", display_range_max_},
                              {"GridX", grid_x_size_},
                              {"GridY", grid_y_size_},
                              {"Alpha", color_alpha_},
                              {"LogScale", log_scale_},
                              {"ReverseLog", reverse_log_},
                              {"ShowNumbers", show_numbers_},
                              {"ShowLegend", show_legend_}};

  for (const auto& setting : settings_) {
    if (std::holds_alternative<MapSettingBoolean>(setting)) {
      auto set = std::get<MapSettingBoolean>(setting);
      settings[set.name] = set.getter();
    } else if (std::holds_alternative<MapSettingMultiChoice>(setting)) {
      auto set = std::get<MapSettingMultiChoice>(setting);
      settings[set.name] = set.getter();
    }
  }

  return settings;
}

void HeatMapDataSource::setSettings(const Renderer::Settings& settings)
{
  Renderer::setSetting<double>(settings, "DisplayMin", display_range_min_);
  Renderer::setSetting<double>(settings, "DisplayMax", display_range_max_);
  Renderer::setSetting<double>(settings, "GridX", grid_x_size_);
  Renderer::setSetting<double>(settings, "GridY", grid_y_size_);
  Renderer::setSetting<int>(settings, "Alpha", color_alpha_);
  Renderer::setSetting<bool>(settings, "LogScale", log_scale_);
  Renderer::setSetting<bool>(settings, "ReverseLog", reverse_log_);
  Renderer::setSetting<bool>(settings, "ShowNumbers", show_numbers_);
  Renderer::setSetting<bool>(settings, "ShowLegend", show_legend_);

  for (const auto& setting : settings_) {
    if (std::holds_alternative<MapSettingBoolean>(setting)) {
      auto set = std::get<MapSettingBoolean>(setting);
      bool temp_value = set.getter();
      Renderer::setSetting<bool>(settings, set.name, temp_value);
      set.setter(temp_value);
    } else if (std::holds_alternative<MapSettingMultiChoice>(setting)) {
      auto set = std::get<MapSettingMultiChoice>(setting);
      std::string temp_value = set.getter();
      Renderer::setSetting<std::string>(settings, set.name, temp_value);
      set.setter(temp_value);
    }
  }

  // only reapply bounded value settings
  setDisplayRange(display_range_min_, display_range_max_);
  setGridSizes(grid_x_size_, grid_y_size_);
  setColorAlpha(color_alpha_);
}

void HeatMapDataSource::addToMap(const odb::Rect& region, double value)
{
  Box query(Point(region.xMin(), region.yMin()),
            Point(region.xMax(), region.yMax()));
  for (auto it = map_.qbegin(bgi::intersects(query)); it != map_.qend(); it++) {
    auto* map_pt = it->second.get();
    odb::Rect intersection;
    map_pt->rect.intersection(region, intersection);

    const double intersect_area = intersection.area();
    const double value_area = region.area();
    const double region_area = map_pt->rect.area();

    combineMapData(map_pt->has_value,
                   map_pt->value,
                   value,
                   value_area,
                   intersect_area,
                   region_area);
    map_pt->has_value = true;

    markColorsInvalid();
  }
}

void HeatMapDataSource::setupMap()
{
  if (getBlock() == nullptr) {
    return;
  }

  const int dx = getGridXSize() * getBlock()->getDbUnitsPerMicron();
  const int dy = getGridYSize() * getBlock()->getDbUnitsPerMicron();

  odb::Rect bounds = getBlock()->getBBox()->getBox();

  const int x_grid = std::ceil(bounds.dx() / static_cast<double>(dx));
  const int y_grid = std::ceil(bounds.dy() / static_cast<double>(dy));

  for (int x = 0; x < x_grid; x++) {
    const int xMin = bounds.xMin() + x * dx;
    const int xMax = std::min(xMin + dx, bounds.xMax());

    for (int y = 0; y < y_grid; y++) {
      const int yMin = bounds.yMin() + y * dy;
      const int yMax = std::min(yMin + dy, bounds.yMax());

      auto map_pt = std::make_shared<MapColor>();
      map_pt->rect = odb::Rect(xMin, yMin, xMax, yMax);
      map_pt->has_value = false;
      map_pt->value = 0.0;
      map_pt->color = getColor(0);

      Box bbox(Point(xMin, yMin), Point(xMax, yMax));
      map_.insert(std::make_pair(bbox, map_pt));
    }
  }
}

void HeatMapDataSource::destroyMap()
{
  destroy_map_ = true;

  redraw();
}

void HeatMapDataSource::ensureMap()
{
  if (destroy_map_) {
    map_.clear();
    destroy_map_ = false;
  }

  const bool build_map = map_.empty();
  if (build_map) {
    setupMap();
  }

  if (build_map || !isPopulated()) {
    populated_ = populateMap();

    if (isPopulated()) {
      correctMapScale(map_);
    }

    if (setup_ != nullptr) {
      // announce changes
      setIssueRedraw(false);
      setup_->changed();
      setIssueRedraw(true);
    }
  }

  if (!colors_correct_) {
    assignMapColors();
  }
}

void HeatMapDataSource::updateMapColors()
{
  const int color_count = color_generator_.getColorCount();
  color_lower_bounds_.clear();
  color_lower_bounds_.resize(color_count + 1);
  // generate ranges for colors
  if (log_scale_) {
    double range = display_range_max_;
    if (display_range_min_ != 0.0) {
      range = display_range_max_ / display_range_min_;
    }

    const double step = std::pow(range, 1.0 / color_count);

    for (int i = 0; i <= color_count; i++) {
      double start = display_range_max_ / std::pow(step, i);
      if (i == color_generator_.getColorCount()) {
        start = display_range_min_;
      }
      color_lower_bounds_[i] = start;
    }

    if (reverse_log_) {
      for (size_t i = 0; i < color_lower_bounds_.size(); i++) {
        color_lower_bounds_[i]
            = display_range_max_ - color_lower_bounds_[i] + display_range_min_;
      }
    } else {
      std::reverse(color_lower_bounds_.begin(), color_lower_bounds_.end());
    }
  } else {
    const double step = (display_range_max_ - display_range_min_) / color_count;
    for (int i = 0; i <= color_count; i++) {
      color_lower_bounds_[i] = display_range_min_ + i * step;
    }
  }

  markColorsInvalid();
}

void HeatMapDataSource::assignMapColors()
{
  for (auto& [bbox, map_pt] : map_) {
    map_pt->color = getColor(map_pt->value);
  }
  colors_correct_ = true;
}

double HeatMapDataSource::getRealRangeMinimumValue() const
{
  return color_lower_bounds_[0];
}

double HeatMapDataSource::getRealRangeMaximumValue() const
{
  return color_lower_bounds_[color_lower_bounds_.size() - 1];
}

const std::vector<std::pair<int, double>> HeatMapDataSource::getLegendValues()
    const
{
  const int color_count = color_generator_.getColorCount();
  const int count = 6;
  std::vector<std::pair<int, double>> values;
  const double index_incr = static_cast<double>(color_count) / (count - 1);
  const double linear_start = getRealRangeMinimumValue();
  const double linear_step
      = (getRealRangeMaximumValue() - linear_start) / (count - 1);
  for (int i = 0; i < count; i++) {
    int idx = std::round(i * index_incr);
    if (idx > color_count) {
      idx = color_count;
    }
    double value = color_lower_bounds_[idx];
    if (!log_scale_) {
      value = linear_step * i + linear_start;
    }

    values.push_back({idx, value});
  }
  return values;
}

void HeatMapDataSource::onShow()
{
  if (!isPopulated()) {
    logger_->warn(utl::GUI,
                  66,
                  "Heat map \"{}\" has not been populated with data.",
                  getName());
  }
}

void HeatMapDataSource::onHide()
{
  if (destroyMapOnNotVisible()) {
    setIssueRedraw(false);
    destroyMap();
    setIssueRedraw(true);
  }
}

///////////

HeatMapRenderer::HeatMapRenderer(HeatMapDataSource& datasource)
    : datasource_(datasource), first_paint_(true)
{
  addDisplayControl(datasource_.getName(),
                    false,
                    [this]() { datasource_.showSetup(); },
                    {""});  // mutually exclusive to all
}

void HeatMapRenderer::drawObjects(Painter& painter)
{
  if (!checkDisplayControl(datasource_.getName())) {
    if (!first_paint_) {
      first_paint_ = true;  // reset check
      // first time so announce onHide
      datasource_.onHide();
    }
    return;
  }

  datasource_.ensureMap();

  if (first_paint_) {
    first_paint_ = false;
    // first time so announce onShow
    datasource_.onShow();
  }

  if (!datasource_.isPopulated()) {
    // nothing to paint
    return;
  }

  const bool show_numbers = datasource_.getShowNumbers();
  const double min_value = datasource_.getRealRangeMinimumValue();
  const double max_value = datasource_.getRealRangeMaximumValue();
  const bool show_mins = datasource_.getDrawBelowRangeMin();
  const bool show_maxs = datasource_.getDrawAboveRangeMax();

  const odb::Rect& bounds = painter.getBounds();

  for (const auto& [bbox, map_pt] : datasource_.getMap()) {
    if (!map_pt->has_value) {  // value not set so nothing to draw
      continue;
    }
    if (!show_mins && map_pt->value < min_value) {
      continue;
    }
    if (!show_maxs && map_pt->value > max_value) {
      continue;
    }

    if (bounds.overlaps(map_pt->rect)) {
      painter.setPen(map_pt->color, true);
      painter.setBrush(map_pt->color);

      painter.drawRect(map_pt->rect);

      if (show_numbers) {
        const int x = 0.5 * (map_pt->rect.xMin() + map_pt->rect.xMax());
        const int y = 0.5 * (map_pt->rect.yMin() + map_pt->rect.yMax());
        const Painter::Anchor text_anchor = Painter::Anchor::CENTER;
        const double text_rect_margin = 0.8;

        const std::string text = datasource_.formatValue(map_pt->value, false);
        const odb::Rect text_bound
            = painter.stringBoundaries(x, y, text_anchor, text);
        bool draw = true;
        if (text_bound.dx() >= text_rect_margin * map_pt->rect.dx()
            || text_bound.dy() >= text_rect_margin * map_pt->rect.dy()) {
          // don't draw if text will be too small
          draw = false;
        }

        if (draw) {
          painter.setPen(Painter::white, true);
          painter.drawString(x, y, text_anchor, text);
        }
      }
    }
  }

  // legend
  if (datasource_.getShowLegend()) {
    std::vector<std::pair<int, std::string>> legend;
    for (const auto& [color_index, color_value] :
         datasource_.getLegendValues()) {
      legend.push_back(
          {color_index, datasource_.formatValue(color_value, true)});
    }

    datasource_.getColorGenerator().drawLegend(painter, legend);
  }
}

const std::string HeatMapRenderer::getSettingsGroupName()
{
  return groupname_prefix_ + datasource_.getSettingsGroupName();
}

const Renderer::Settings HeatMapRenderer::getSettings()
{
  Renderer::Settings settings = Renderer::getSettings();
  for (const auto& [name, value] : datasource_.getSettings()) {
    settings[datasource_prefix_ + name] = value;
  }
  return settings;
}

void HeatMapRenderer::setSettings(const Settings& settings)
{
  Renderer::setSettings(settings);
  Renderer::Settings data_settings;
  for (const auto& [name, value] : settings) {
    if (name.find(datasource_prefix_) == 0) {
      data_settings[name.substr(strlen(datasource_prefix_))] = value;
    }
  }
  datasource_.setSettings(data_settings);
}

//////////

RealValueHeatMapDataSource::RealValueHeatMapDataSource(
    utl::Logger* logger,
    const std::string& unit_suffix,
    const std::string& name,
    const std::string& short_name,
    const std::string& settings_group)
    : HeatMapDataSource(logger, name, short_name, settings_group),
      unit_suffix_(unit_suffix),
      units_(unit_suffix_),
      min_(0.0),
      max_(0.0),
      scale_(1.0)
{
}

void RealValueHeatMapDataSource::correctMapScale(HeatMapDataSource::Map& map)
{
  determineMinMax(map);
  determineUnits();
  min_ = roundData(min_);
  max_ = roundData(max_);

  for (auto& [bbox, map_pt] : map) {
    map_pt->value = convertValueToPercent(map_pt->value);
  }

  // reset since all data has been scaled by the appropriate amount
  scale_ = 1.0;
}

double RealValueHeatMapDataSource::roundData(double value) const
{
  const double precision = 1000.0;
  double new_value = value * scale_;
  return std::round(new_value * precision) / precision;
}

void RealValueHeatMapDataSource::determineMinMax(
    const HeatMapDataSource::Map& map)
{
  min_ = std::numeric_limits<double>::max();
  max_ = std::numeric_limits<double>::min();

  for (const auto& [bbox, map_pt] : map) {
    min_ = std::min(min_, map_pt->value);
    max_ = std::max(max_, map_pt->value);
  }
}

void RealValueHeatMapDataSource::determineUnits()
{
  const double range = max_ - min_;
  if (range > 1.0 || range == 0) {
    units_ = "";
    scale_ = 1.0;
  } else if (range > 1e-3) {
    units_ = "m";
    scale_ = 1e3;
  } else if (range > 1e-6) {
    units_ = "\u03BC";  // micro
    scale_ = 1e6;
  } else if (range > 1e-9) {
    units_ = "n";
    scale_ = 1e9;
  } else if (range > 1e-12) {
    units_ = "p";
    scale_ = 1e12;
  } else {
    units_ = "f";
    scale_ = 1e15;
  }

  units_ += unit_suffix_;
}

const std::string RealValueHeatMapDataSource::formatValue(double value,
                                                          bool legend) const
{
  int digits = legend ? 3 : 2;

  QString text;
  text.setNum(convertPercentToValue(value), 'f', digits);
  if (legend) {
    text += QString::fromStdString(getValueUnits());
  }
  return text.toStdString();
}

const std::string RealValueHeatMapDataSource::getValueUnits() const
{
  return units_;
}

double RealValueHeatMapDataSource::getValueRange() const
{
  double range = max_ - min_;
  if (range == 0.0) {
    range = 1.0;  // dummy numbers until drops has been populated
  }
  return range;
}

double RealValueHeatMapDataSource::convertValueToPercent(double value) const
{
  const double range = getValueRange();
  const double offset = min_;

  return roundData(100.0 * (value - offset) / range);
}

double RealValueHeatMapDataSource::convertPercentToValue(double percent) const
{
  const double range = getValueRange();
  const double offset = min_;

  return roundData(percent * range / 100.0 + offset);
}

double RealValueHeatMapDataSource::getDisplayRangeIncrement() const
{
  return getValueRange() / 100.0;
}

}  // namespace gui


text:
CONTACTO alevilar@gmail.com !!!!!!!!!!

Install
=======

Install Plugin for Ristorantino Mágico

Instrucciones
=======

1) - Borrar el database.php del /Config
2) - Copiar la carpeta Install en la carpeta /Plugin
3) - Incluir el llamado al plugin Install
CakePlugin::load('Install', array('bootstrap' => true, 'routes' => true)); en el Config/bootstrap.php
4) - Ingresar en el explorador la dirección url previamente configurada para acceder al ristorantino app


text:
require 'amvse-kit/commands/locations'
require 'amvse-kit/commands/login'
require 'amvse-kit/commands/releases'
require 'amvse-kit/commands/websites'

module AmvseKit

  module Commands

    def self.included(base)
      base.include AmvseKit::Commands::Locations
      base.include AmvseKit::Commands::Login
      base.include AmvseKit::Commands::Releases
      base.include AmvseKit::Commands::Websites
    end

  end

end


text:
package scaposer

import scala.util.parsing.combinator.RegexParsers

object PluralIndexExpressionParser extends RegexParsers {
  private def wholeExpr = nplurals ~ assign ~ integerConst ~ endExpr ~ plural ~ assign ~ subexpr ~ endExpr ^^ {
      case _ ~ _ ~ maxIndex ~ _ ~ _ ~ _ ~ f ~ _ => x: Long => Math.min(f(Math.max(x, 0L)), maxIndex)
    }

    def apply(input: String): ParseResult[Long => Long] = parseAll(wholeExpr, input)

    final private val assign = "="
    final private val equals = "=="
    final private val notEquals = "!="
    final private val greater = ">"
    final private val less = "<"
    final private val lessOrEquals = "<="
    final private val greaterOrEquals = ">="

    final private val multuply = "*"
    final private val divide = "/"
    final private val mod = "%"

    final private val plus = "+"
    final private val minus = "-"

    final private val logicalAnd = "&&"
    final private val logicalOr = "||"
    final private val negation = "!"

    final private val openBrace = "("
    final private val closeBrace = ")"

    final private val nplurals = "nplurals"
    final private val plural = "plural"
    final private val endExpr = ";"

    private def number = """\d+""".r ^^ { str =>
      x: Long => str.toLong
    }

    private def integerConst = """\d+""".r ^^ (_.toInt)

    private def n = "n" ^^ { _ =>
      x: Long => x.toLong
    }

    private def subexpr = ternary | logicToNumber | expr

    private def value: Parser[Long => Long] = number | n | (openBrace ~> subexpr <~ closeBrace)

    private def term: Parser[Long => Long] = value ~ rep(multuply ~ value | divide ~ value | mod ~ value) ^^ {
      case number ~ list => list.foldLeft(number) {
        case (x, `multuply` ~ y) => t: Long => x(t) * y(t)
        case (x, `divide` ~ y) => t: Long => x(t) / y(t)
        case (x, `mod` ~ y) => t: Long => x(t) % y(t)
      }
    }

    private def expr: Parser[Long => Long] = term ~ rep(plus ~ term | minus ~ term) ^^ {
      case number ~ list => list.foldLeft(number) {
        case (x, `plus` ~ y) => t: Long => x(t) + y(t)
        case (x, `minus` ~ y) => t: Long => x(t) - y(t)
      }
    }

    private def compare = expr ~ (greaterOrEquals| lessOrEquals | notEquals | equals | greater | less) ~ expr ^^ {
      case a ~ `greaterOrEquals` ~ b => x: Long => a(x) >= b(x)
      case a ~ `lessOrEquals` ~ b => x: Long => a(x) <= b(x)
      case a ~ `notEquals` ~ b => x: Long => a(x) != b(x)
      case a ~ `equals` ~ b => x: Long => a(x) == b(x)
      case a ~ `greater` ~ b => x: Long => a(x) > b(x)
      case a ~ `less` ~ b => x: Long => a(x) < b(x)
    }

    private def logic: Parser[Long => Boolean] = (openBrace ~> (logic) <~ closeBrace) | (compare ~ rep(logicalAnd ~ logic | logicalOr ~ logic) ^^ {
      case compare ~ list => list.foldLeft(compare) {
        case (x, `logicalAnd` ~ y) => t: Long => x(t) && y(t)
        case (x, `logicalOr` ~ y) => t: Long => x(t) || y(t)
      }
    })

    private def logicToNumber: Parser[Long => Long] = logic ^^ { x =>
      t: Long => if (x(t)) 1 else 0
    }

    private def negLogic = negation ~ openBrace ~ logic ~ closeBrace ^^ {
    	case _ ~ _ ~ x ~ _ => t: Long => !x(t)
    }

    private def ternary: Parser[Long => Long] = (logic | negLogic) ~ "?" ~ subexpr ~ ":" ~ subexpr ^^ {
      case logic ~ _ ~ yes ~ _ ~ no => x: Long => if (logic(x)) yes(x) else no(x)
    }
}