text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace HTLib2
{
    public static partial class HStatic
    {
        public static void Add(this Dictionary<string, HDynamic> dict, string key, object value)
        {
            dict.Add(key, new HDynamic(value));
        }
    }
    [Serializable]
    public class HDynamic
    {
        object value;
        public HDynamic(object value)
        {
            this.value = value;
        }

        public void Get<TYPE>(out TYPE value) { value = (TYPE)this.value; }
        public TYPE Get<TYPE>() { return (TYPE)value; }
        public void Set(object value) { this.value = value; }

        [DebuggerBrowsableAttribute(DebuggerBrowsableState.Never)] public object   Object  { get { return (object  )value; }       set { this.value = value; } }

        [DebuggerBrowsableAttribute(DebuggerBrowsableState.Never)] public int      Int     { get { return (int     )value; }       set { this.value = value; } }
        [DebuggerBrowsableAttribute(DebuggerBrowsableState.Never)] public double   Double  { get { return (double  )value; }       set { this.value = value; } }
        [DebuggerBrowsableAttribute(DebuggerBrowsableState.Never)] public string   String  { get { return (string  )value; }       set { this.value = value; } }
        [DebuggerBrowsableAttribute(DebuggerBrowsableState.Never)] public char     Char    { get { return (char    )value; }       set { this.value = value; } }
        [DebuggerBrowsableAttribute(DebuggerBrowsableState.Never)] public bool     Bool    { get { return (bool    )value; }       set { this.value = value; } }

        [DebuggerBrowsableAttribute(DebuggerBrowsableState.Never)] public Vector       Vector      { get { return (Vector      )value; } set { this.value = value; } }
        [DebuggerBrowsableAttribute(DebuggerBrowsableState.Never)] public MatrixByArr  MatrixByArr { get { return (MatrixByArr )value; } set { this.value = value; } }
        [DebuggerBrowsableAttribute(DebuggerBrowsableState.Never)] public HDictionary  Dictionary  { get { return (HDictionary )value; } set { this.value = value; } }
        [DebuggerBrowsableAttribute(DebuggerBrowsableState.Never)] public double[]     DoubleArr   { get { return (double[]    )value; } set { this.value = value; } }
        [DebuggerBrowsableAttribute(DebuggerBrowsableState.Never)] public double[,]    DoubleArr2D { get { return (double[,]   )value; } set { this.value = value; } }
        [DebuggerBrowsableAttribute(DebuggerBrowsableState.Never)] public double[][]   DoubleArrArr{ get { return (double[][]  )value; } set { this.value = value; } }

        [DebuggerBrowsableAttribute(DebuggerBrowsableState.Never)] public List<int>       ListInt         { get { return (List<int>      )value; }       set { this.value = value; } }
        [DebuggerBrowsableAttribute(DebuggerBrowsableState.Never)] public List<double>    ListDouble      { get { return (List<double>   )value; }       set { this.value = value; } }
        [DebuggerBrowsableAttribute(DebuggerBrowsableState.Never)] public List<Vector>    ListVector      { get { return (List<Vector>   )value; }       set { this.value = value; } }
        [DebuggerBrowsableAttribute(DebuggerBrowsableState.Never)] public List<Vector[]>  ListVectorArray { get { return (List<Vector[]> )value; }       set { this.value = value; } }

        [DebuggerBrowsableAttribute(DebuggerBrowsableState.Never)] public List<int[]>     ListArrayInt    { get { return (List<int[]>    )value; }       set { this.value = value; } }
        [DebuggerBrowsableAttribute(DebuggerBrowsableState.Never)] public Vector[]        ArrayVector     { get { return (Vector[]       )value; }       set { this.value = value; } }

        [DebuggerBrowsableAttribute(DebuggerBrowsableState.Never)] public dynamic        Dynamic     { get { return (dynamic)value; }       set { this.value = value; } }
        public int    DynamicLength   { get { return Dynamic.Length;     } }
        public string DynamicToString { get { return Dynamic.ToString(); } }
        public object DynamicObjectAt(int idx) { return Dynamic[idx]; }

        public override string ToString()
        {
            { var val=value as IList<int   >; if(val != null) return    "int["+val.Count()+"] "+val.HToVectorT().ToString(20); }
            { var val=value as IList<double>; if(val != null) return "double["+val.Count()+"] "+val.HToVectorT().ToString(20); }
            { var val=value as IList<Vector>; if(val != null) return "Vector["+val.Count()+"] "+val.HToVectorT().ToString(20); }
            { var val=value as IList<Tuple<int,int        >>; if(val != null) return         "Tuple<int,int>["+val.Count()+"] "+val.HToVectorT().ToString(20); }
            { var val=value as IList<Tuple<int,int,int    >>; if(val != null) return     "Tuple<int,int,int>["+val.Count()+"] "+val.HToVectorT().ToString(20); }
            { var val=value as IList<Tuple<int,int,int,int>>; if(val != null) return "Tuple<int,int,int,int>["+val.Count()+"] "+val.HToVectorT().ToString(20); }
            { var val=value as double[,]                    ; if(val != null) return (new MatrixByArr(value as double[,])).ToString().Replace("Matrix","double"); }
            return value.ToString();
        }
    }
}


text:
#ifndef _CD_VOID_
#define _CD_VOID_

#ifdef __cplusplus
extern "C" {
#endif

cdContext* cdContextVoid(void);

#define CD_VOID cdContextVoid()

#ifdef __cplusplus
}
#endif

#endif /* ifndef _CD_VOID_ */

redpajama_set_name: RedPajamaGithub


text:
#pragma once
#ifndef OGLPLUS_SHAPES_CUBE_1107121519_HPP
#define OGLPLUS_SHAPES_CUBE_1107121519_HPP

#include <oglplus/face_mode.hpp>
#include <oglplus/shapes/draw.hpp>

#include <oglplus/shapes/vert_attr_info.hpp>

#include <oglplus/math/sphere.hpp>

#include <cmath>

namespace oglplus {
namespace shapes {

/// Class providing vertex attributes and instructions for rendering of a cube
class Cube
 : public DrawingInstructionWriter
 , public DrawMode
{
private:
	GLdouble _sx, _sy, _sz;
	GLdouble _ox, _oy, _oz;
public:
	/// Constructs a unit cube centered at the origin
	Cube(void)
	 : _sx(1.0)
	 , _sy(1.0)
	 , _sz(1.0)
	 , _ox(0.0)
	 , _oy(0.0)
	 , _oz(0.0)
	{ }

	/// Constructs a cube with width, height, depth
	Cube(GLdouble w, GLdouble h, GLdouble d)
	 : _sx(w)
	 , _sy(h)
	 , _sz(d)
	 , _ox(0.0)
	 , _oy(0.0)
	 , _oz(0.0)
	{ }

	/// Constructs a cube with width, height, depth and x,y and z offsets
	Cube(
		GLdouble w,
		GLdouble h,
		GLdouble d,
		GLdouble x,
		GLdouble y,
		GLdouble z
	): _sx(w)
	 , _sy(h)
	 , _sz(d)
	 , _ox(x)
	 , _oy(y)
	 , _oz(z)
	{ }

	/// Returns the winding direction of faces
	FaceOrientation FaceWinding(void) const
	{
		return FaceOrientation::CW;
	}

	typedef GLuint (Cube::*VertexAttribFunc)(std::vector<GLfloat>&) const;

	std::vector<GLfloat> _positions(void) const;

	GLuint Positions(std::vector<GLfloat>& dest) const
	{
		dest = _positions();
		return 3;
	}

	/// Makes the vertices and returns the number of values per vertex
	template <typename T>
	GLuint Positions(std::vector<T>& dest) const
	{
		auto v = _positions();
		dest.assign(v.begin(), v.end());
		return 3;
	}

	std::vector<GLfloat> _normals(void) const;

	GLuint Normals(std::vector<GLfloat>& dest) const
	{
		dest = _normals();
		return 3;
	}

	/// Makes the normals and returns the number of values per vertex
	template <typename T>
	GLuint Normals(std::vector<T>& dest) const
	{
		auto v = _normals();
		dest.assign(v.begin(), v.end());
		return 3;
	}

	std::vector<GLfloat> _tangents(void) const;

	GLuint Tangents(std::vector<GLfloat>& dest) const
	{
		dest = _tangents();
		return 3;
	}

	/// Makes the tangents and returns the number of values per vertex
	template <typename T>
	GLuint Tangents(std::vector<T>& dest) const
	{
		auto v = _tangents();
		dest.assign(v.begin(), v.end());
		return 3;
	}

	std::vector<GLfloat> _tex_coords(void) const;

	GLuint TexCoordinates(std::vector<GLfloat>& dest) const
	{
		dest = _tex_coords();
		return 3;
	}

	/// Makes the texture coordinates and returns the number of values per vertex
	template <typename T>
	GLuint TexCoordinates(std::vector<T>& dest) const
	{
		auto v = _tex_coords();
		dest.assign(v.begin(), v.end());
		return 3;
	}

#if OGLPLUS_DOCUMENTATION_ONLY
	/// Vertex attribute information for this shape builder
	/** Cube provides build functions for the following named
	 *  vertex attributes:
	 *  - "Position" the vertex positions (Positions)
	 *  - "Normal" the vertex normal vectors (Normals)
	 *  - "Tangent" the vertex tangent vector (Tangents)
	 *  - "TexCoord" the ST texture coordinates (TexCoordinates)
	 */
	typedef VertexAttribsInfo<Cube> VertexAttribs;
#else
	typedef VertexAttribsInfo<
		Cube,
		std::tuple<
			VertexPositionsTag,
			VertexNormalsTag,
			VertexTangentsTag,
			VertexTexCoordinatesTag
		>
	> VertexAttribs;
#endif

	/// Queries the bounding sphere coordinates and dimensions
	template <typename T>
	void BoundingSphere(oglplus::Sphere<T>& bounding_sphere) const
	{
		bounding_sphere = oglplus::Sphere<T>(
			T(_ox),
			T(_oy),
			T(_oz),
			T(std::sqrt(_sx*_sx + _sy*_sy + _sz*_sz))
		);
	}

	/// The type of the index container returned by Indices()
	typedef std::vector<GLushort> IndexArray;

	/// Returns element indices that are used with the drawing instructions
	IndexArray Indices(Default = Default()) const
	{
		return IndexArray();
	}

	/// Returns the instructions for rendering of faces
	DrawingInstructions Instructions(Default = Default()) const;

	/// Returns element indices for the Cube's edges
	IndexArray Indices(Edges) const;

	/// Returns the instructions for rendering of edges
	DrawingInstructions Instructions(Edges) const;
};

} // shapes
} // oglplus

#if !OGLPLUS_LINK_LIBRARY || defined(OGLPLUS_IMPLEMENTING_LIBRARY)
#include <oglplus/shapes/cube.ipp>
#endif // OGLPLUS_LINK_LIBRARY

#endif // include guard


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

import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.packages.Attribute.attr;
import static com.google.devtools.build.lib.packages.BuildType.LABEL_LIST;
import static org.junit.Assert.assertThrows;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.analysis.util.BuildViewTestBase.AnalysisFailureRecorder;
import com.google.devtools.build.lib.analysis.util.BuildViewTestCase;
import com.google.devtools.build.lib.analysis.util.DummyTestFragment;
import com.google.devtools.build.lib.analysis.util.MockRule;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.packages.Attribute;
import com.google.devtools.build.lib.packages.Attribute.ComputedDefault;
import com.google.devtools.build.lib.packages.AttributeMap;
import com.google.devtools.build.lib.packages.BuildType;
import com.google.devtools.build.lib.packages.NoSuchTargetException;
import com.google.devtools.build.lib.packages.RuleClass.ToolchainResolutionMode;
import com.google.devtools.build.lib.packages.Type;
import com.google.devtools.build.lib.skyframe.ConfiguredTargetAndData;
import com.google.devtools.build.lib.testutil.TestRuleClassProvider;
import com.google.devtools.build.lib.util.FileTypeSet;
import java.io.IOException;
import java.util.Collection;
import java.util.Set;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * Integration tests for configurable attributes.
 */
@RunWith(JUnit4.class)
public class ConfigurableAttributesTest extends BuildViewTestCase {

  private void writeConfigRules() throws Exception {
    scratch.file(
        "conditions/BUILD",
        "config_setting(",
        "    name = 'a',",
        "    values = {'foo': 'a'})",
        "config_setting(",
        "    name = 'b',",
        "    values = {'foo': 'b'})");
  }

  private void writeHelloRules(boolean includeDefaultCondition) throws IOException {
    scratch.file("java/hello/BUILD",
        "java_binary(",
        "    name = 'hello',",
        "    srcs = ['hello.java'],",
        "    deps = select({",
        "        '//conditions:a': [':adep'],",
        "        '//conditions:b': [':bdep'],",
        includeDefaultCondition
            ? "        '" + BuildType.Selector.DEFAULT_CONDITION_KEY + "': [':defaultdep'],"
            : "",
        "    }))",
        "",
        "java_library(",
        "    name = 'adep',",
        "    srcs = ['adep.java'])",
        "java_library(",
        "    name = 'bdep',",
        "    srcs = ['bdep.java'])",
        "java_library(",
        "    name = 'defaultdep',",
        "    srcs = ['defaultdep.java'])");
  }

  private static final String ADEP_INPUT = "bin java/hello/libadep.jar";
  private static final String BDEP_INPUT = "bin java/hello/libbdep.jar";
  private static final String CDEP_INPUT = "bin java/hello/libcdep.jar";
  private static final String DEFAULTDEP_INPUT = "bin java/hello/libdefaultdep.jar";

  /**
   * Checks that, given the specified configuration parameters, the input rule *has* the expected
   * attribute values and *doesn't have* the unexpected attribute values.
   */
  private void checkRule(
      String ruleLabel,
      String attributeName,
      Collection<String> options,
      Iterable<String> expected,
      Iterable<String> notExpected)
      throws Exception {
    useConfiguration(options.toArray(new String[options.size()]));
    ConfiguredTarget binary = getConfiguredTarget(ruleLabel);
    assertThat(binary).isNotNull();
    Set<String> actualDeps = artifactsToStrings(getPrerequisiteArtifacts(binary, attributeName));
    expected.forEach(expectedInput -> assertThat(actualDeps).contains(expectedInput));
    notExpected.forEach(unexpectedInput -> assertThat(actualDeps).doesNotContain(unexpectedInput));
  }

  private void checkRule(String ruleLabel, String option,
      Iterable<String> expected, Iterable<String> notExpected) throws Exception {
    checkRule(ruleLabel, ImmutableList.of(option), expected, notExpected);
  }

  private void checkRule(
      String ruleLabel,
      Collection<String> options,
      Iterable<String> expected,
      Iterable<String> notExpected)
      throws Exception {
    checkRule(ruleLabel, "deps", options, expected, notExpected);
  }

  private static final MockRule RULE_WITH_OUTPUT_ATTR =
      () -> MockRule.define("rule_with_output_attr", attr("out", BuildType.OUTPUT));

  private static final MockRule RULE_WITH_COMPUTED_DEFAULT =
      () -> MockRule.define(
          "rule_with_computed_default",
          attr("string_attr", Type.STRING),
          attr("$computed_attr", Type.STRING).value(
              new ComputedDefault("string_attr") {
                @Override
                public Object getDefault(AttributeMap rule) {
                  return rule.get("string_attr", Type.STRING) + "2";
                }
            }));

  private static final MockRule RULE_WITH_BOOLEAN_ATTR =
      () -> MockRule.define("rule_with_boolean_attr", attr("boolean_attr", Type.BOOLEAN));

  private static final MockRule RULE_WITH_ALLOWED_VALUES =
      () -> MockRule.define(
          "rule_with_allowed_values",
          attr("one_two", Type.STRING)
              .allowedValues(new Attribute.AllowedValueSet("one", "two")));

  private static final MockRule RULE_WITH_LABEL_DEFAULT =
      () ->
          MockRule.define(
              "rule_with_label_default",
              (builder, env) ->
                  builder.add(
                      attr("dep", BuildType.LABEL)
                          .value(Label.parseAbsoluteUnchecked("//foo:default"))
                          .allowedFileTypes(FileTypeSet.ANY_FILE)));

  private static final MockRule RULE_WITH_NO_PLATFORM =
      () ->
          MockRule.define(
              "rule_with_no_platform",
              (builder, env) ->
                  builder
                      .add(attr("deps", LABEL_LIST).allowedFileTypes())
                      .useToolchainResolution(ToolchainResolutionMode.DISABLED));

  @Override
  protected ConfiguredRuleClassProvider createRuleClassProvider() {
    ConfiguredRuleClassProvider.Builder builder =
        new ConfiguredRuleClassProvider.Builder()
            .addRuleDefinition(RULE_WITH_OUTPUT_ATTR)
            .addRuleDefinition(RULE_WITH_COMPUTED_DEFAULT)
            .addRuleDefinition(RULE_WITH_BOOLEAN_ATTR)
            .addRuleDefinition(RULE_WITH_ALLOWED_VALUES)
            .addRuleDefinition(RULE_WITH_LABEL_DEFAULT)
            .addRuleDefinition(RULE_WITH_NO_PLATFORM);
    TestRuleClassProvider.addStandardRules(builder);
    // Allow use of --foo as a dummy flag
    builder.addConfigurationFragment(DummyTestFragment.class);
    return builder.build();
  }

  @Test
  public void basicConfigurability() throws Exception {
    writeHelloRules(/*includeDefaultCondition=*/true);
    writeConfigRules();
    checkRule(
        "//java/hello:hello",
        "--foo=a",
        /*expected:*/ ImmutableList.of(ADEP_INPUT),
        /*not expected:*/ ImmutableList.of(BDEP_INPUT, DEFAULTDEP_INPUT));
    checkRule(
        "//java/hello:hello",
        "--foo=b",
        /*expected:*/ ImmutableList.of(BDEP_INPUT),
        /*not expected:*/ ImmutableList.of(ADEP_INPUT, DEFAULTDEP_INPUT));
  }

  @Test
  public void configurabilityDefaults() throws Exception {
    writeHelloRules(/*includeDefaultCondition=*/true);
    writeConfigRules();
    checkRule(
        "//java/hello:hello",
        "--foo=something_random",
        /*expected:*/ ImmutableList.of(DEFAULTDEP_INPUT),
        /*not expected:*/ ImmutableList.of(ADEP_INPUT, BDEP_INPUT));
    checkRule("//java/hello:hello", "",
        /*expected:*/ ImmutableList.of(DEFAULTDEP_INPUT),
        /*not expected:*/ ImmutableList.of(ADEP_INPUT, BDEP_INPUT));
  }

  /**
   * Duplicate label definitions are fine as long as they're in different selection branches.
   */
  @Test
  public void depsWithDuplicatesInDifferentBranches() throws Exception {
    writeConfigRules();
    scratch.file("java/hello/BUILD",
        "java_binary(",
        "    name = 'hello',",
        "    srcs = ['hello.java'],",
        "    deps = select({",
        "        '//conditions:a': [':adep', ':cdep'],",
        "        '//conditions:b': [':bdep', ':cdep'],",
        "        '" + BuildType.Selector.DEFAULT_CONDITION_KEY + "': [':defaultdep'],",
        "    }))",
        "",
        "java_library(",
        "    name = 'adep',",
        "    srcs = ['adep.java'])",
        "java_library(",
        "    name = 'bdep',",
        "    srcs = ['bdep.java'])",
        "java_library(",
        "    name = 'cdep',",
        "    srcs = ['cdep.java'])");
    checkRule(
        "//java/hello:hello",
        "--foo=a",
        /*expected:*/ ImmutableList.of(ADEP_INPUT, CDEP_INPUT),
        /*not expected:*/ ImmutableList.of(BDEP_INPUT, DEFAULTDEP_INPUT));
  }

  /**
   * Duplicate label definitions are *not* fine within the same branch.
   */
  @Test
  public void depsWithDuplicatesInSameBranch() throws Exception {
    writeConfigRules();
    scratch.file("java/hello/BUILD",
        "java_binary(",
        "    name = 'hello',",
        "    srcs = ['hello.java'],",
        "    deps = select({",
        "        '//conditions:a': [':adep', ':cdep', ':adep'],",
        "        '//conditions:b': [':bdep', ':cdep'],",
        "        '" + BuildType.Selector.DEFAULT_CONDITION_KEY + "': [':defaultdep'],",
        "    }))",
        "",
        "java_library(",
        "    name = 'adep',",
        "    srcs = ['adep.java'])",
        "java_library(",
        "    name = 'bdep',",
        "    srcs = ['bdep.java'])",
        "java_library(",
        "    name = 'cdep',",
        "    srcs = ['cdep.java'])");

    reporter.removeHandler(failFastHandler); // Expect errors.
    useConfiguration("--foo=a");
    getConfiguredTarget("//java/hello:hello");
    assertContainsEvent(
        "Label '//java/hello:adep' is duplicated in the 'deps' attribute of rule 'hello'");
  }

  /**
   * When an attribute includes multiple selects, we don't allow duplicates even across
   * selects (this saves us from having to do possibly expensive value iteration since the
   * number of values can grow exponentially with respect to the number of selects).
   */
  @Test
  public void duplicatesAcrossMultipleSelects() throws Exception {
    writeConfigRules();
    scratch.file("java/hello/BUILD",
        "java_binary(",
        "    name = 'hello',",
        "    srcs = select({",
        "        '//conditions:a': ['a.java'],",
        "        '//conditions:b': ['b.java'],",
        "        })",
        "        + select({",
        "        '//conditions:c': ['c.java'],",
        "        '//conditions:d': ['a.java'],",
        "    }))");

    reporter.removeHandler(failFastHandler); // Expect errors.
    useConfiguration("--foo=a");
    getConfiguredTarget("//java/hello:hello");
    assertContainsEvent(
        "Label '//java/hello:a.java' is duplicated in the 'srcs' attribute of rule 'hello'");
  }

  /**
   * Even with multiple selects, duplicates are allowed within a *single* select as long as
   * they're in different branches (and thus mutually exclusive).
   */
  @Test
  public void duplicatesInDifferentBranchesMultipleSelects() throws Exception {
    writeConfigRules();
    scratch.file("java/hello/BUILD",
        "java_binary(",
        "    name = 'hello',",
        "    srcs = select({",
        "        '//conditions:a': ['a.java'],",
        "        '//conditions:b': ['a.java'],",
        "        })",
        "        + select({",
        "        '//conditions:a': ['b.java'],",
        "        '//conditions:b': ['b.java'],",
        "    }))");

    useConfiguration("--foo=a");
    getConfiguredTarget("//java/hello:hello");
    assertNoEvents();
  }

  /**
   * With multiple selects, a single select still can't duplicate labels within the same branch.
   */
  @Test
  public void duplicatesInSameBranchMultipleSelects() throws Exception {
    writeConfigRules();
    scratch.file("java/hello/BUILD",
        "java_binary(",
        "    name = 'hello',",
        "    srcs = select({",
        "        '//conditions:a': ['a.java', 'a.java'],",
        "        '//conditions:b': ['b.java'],",
        "        })",
        "        + select({",
        "        '//conditions:a': ['c.java'],",
        "        '//conditions:b': ['d.java'],",
        "    }))");

    reporter.removeHandler(failFastHandler); // Expect errors.
    useConfiguration("--foo=a");
    getConfiguredTarget("//java/hello:hello");
    assertContainsEvent(
        "Label '//java/hello:a.java' is duplicated in the 'srcs' attribute of rule 'hello'");
  }

  /**
   * Attributes of type {@link BuildType#OUTPUT} are not configurable.
   */
  @Test
  public void outputTypeNotConfigurable() throws Exception {
    writeConfigRules();
    scratch.file("foo/BUILD",
        "rule_with_output_attr(",
        "    name = 'has_an_out',",
        "    out = select({",
        "        '//conditions:a': 'a.out',",
        "        '" + BuildType.Selector.DEFAULT_CONDITION_KEY + "': 'default.out'})",
        ")");

    reporter.removeHandler(failFastHandler); // Expect errors.
    getConfiguredTarget("//foo:has_an_out");
    assertContainsEvent("attribute \"out\" is not configurable");
  }

  /**
   * Attributes of type {@link BuildType#OUTPUT_LIST} are not configurable.
   */
  @Test
  public void outputListTypeNotConfigurable() throws Exception {
    writeConfigRules();
    scratch.file("foo/BUILD",
        "genrule(",
        "    name = 'generator',",
        "    srcs = [],",
        "    outs = select({",
        "        '//conditions:a': ['a.out'],",
        "        '" + BuildType.Selector.DEFAULT_CONDITION_KEY + "': ['default.out']})",
        ")");

    reporter.removeHandler(failFastHandler); // Expect errors.
    getConfiguredTarget("//foo:generator");
    assertContainsEvent("attribute \"outs\" is not configurable");
  }

  /**
   * Tests that computed defaults faithfully reflect the values of the attributes they depend on.
   */
  @Test
  public void computedDefaults() throws Exception {
    writeConfigRules();
    scratch.file("test/BUILD",
        "rule_with_computed_default(",
        "    name = 'the_rule',",
        "    string_attr = select({",
        "        '//conditions:a': 'a',",
        "        '//conditions:b': 'b',",
        "        '" + BuildType.Selector.DEFAULT_CONDITION_KEY + "': 'default',",
        "    }))");

    // Configuration a:
    useConfiguration("--foo=a");
    ConfiguredTargetAndData binary = getConfiguredTargetAndData("//test:the_rule");
    AttributeMap attributes = getMapperFromConfiguredTargetAndTarget(binary);
    assertThat(attributes.get("$computed_attr", Type.STRING)).isEqualTo("a2");

    // configuration b:
    useConfiguration("--foo=b");
    binary = getConfiguredTargetAndData("//test:the_rule");
    attributes = getMapperFromConfiguredTargetAndTarget(binary);
    assertThat(attributes.get("$computed_attr", Type.STRING)).isEqualTo("b2");
  }

  @Test
  public void configKeyTypeChecking_Int() throws Exception {
    reporter.removeHandler(failFastHandler); // Expect errors.
    scratch.file(
        "java/foo/BUILD",
        "java_library(",
        "    name = 'int_key',",
        "    srcs = select({123: ['a.java']})",
        ")");
    assertTargetError("//java/foo:int_key", "select: got int for dict key, want a label string");
  }

  @Test
  public void configKeyTypeChecking_Bool() throws Exception {
    reporter.removeHandler(failFastHandler); // Expect errors.
    scratch.file(
        "java/foo/BUILD",
        "java_library(",
        "    name = 'bool_key',",
        "    srcs = select({True: ['a.java']})",
        ")");
    assertTargetError("//java/foo:bool_key", "select: got bool for dict key, want a label string");
  }

  @Test
  public void configKeyTypeChecking_None() throws Exception {
    reporter.removeHandler(failFastHandler); // Expect errors.
    scratch.file(
        "java/foo/BUILD",
        "java_library(",
        "    name = 'none_key',",
        "    srcs = select({None: ['a.java']})",
        ")");
    assertTargetError(
        "//java/foo:none_key", "select: got NoneType for dict key, want a label string");
  }

  @Test
  public void selectWithoutConditionsMakesNoSense() throws Exception {
    reporter.removeHandler(failFastHandler); // Expect errors.
    scratch.file(
        "foo/BUILD",
        "genrule(",
        "    name = 'nothing',",
        "    srcs = [],",
        "    outs = ['notmuch'],",
        "    cmd = select({})",
        ")");
    assertTargetError(
        "//foo:nothing",
        "select({}) with an empty dictionary can never resolve because it includes no conditions "
            + "to match");
  }

  /**
   * Tests that config keys must resolve to existent targets.
   */
  @Test
  public void missingConfigKey() throws Exception {
    reporter.removeHandler(failFastHandler); // Expect errors.
    // Only create one of two necessary configurability rules:
    scratch.file(
        "conditions/BUILD", "config_setting(", "    name = 'a',", "    values = {'foo': 'a'})");
    writeHelloRules(/*includeDefaultCondition=*/true);
    getConfiguredTarget("//java/hello:hello");
    assertContainsEvent("no such target '//conditions:b'");
  }

  /**
   * Tests that config keys must resolve to config_setting targets.
   */
  @Test
  public void invalidConfigKey() throws Exception {
    reporter.removeHandler(failFastHandler); // Expect errors.
    scratch.file(
        "conditions/BUILD",
        "config_setting(",
        "    name = 'a',",
        "    values = {'foo': 'a'})",
        "rule_with_output_attr(",
        "    name = 'b',",
        "    out = 'b.out')");
    writeHelloRules(/*includeDefaultCondition=*/true);
    assertThat(getConfiguredTarget("//java/hello:hello")).isNull();
    assertContainsEvent("//conditions:b is not a valid select() condition for //java/hello:hello");
    assertDoesNotContainEvent("//conditions:a"); // This one is legitimate..
  }

  @Test
  public void configKeyNonexistentTarget() throws Exception {
    reporter.removeHandler(failFastHandler); // Expect errors.
    scratch.file("foo/BUILD",
        "genrule(",
        "    name = 'g',",
        "    outs = ['g.out'],",
        "    cmd = select({':fake': ''})",
        ")");
    assertThat(getConfiguredTarget("//foo:g")).isNull();
    assertContainsEvent("//foo:fake is not a valid select() condition for //foo:g");
  }

  @Test
  public void configKeyNonexistentTarget_otherPackage() throws Exception {
    reporter.removeHandler(failFastHandler); // Expect errors.
    scratch.file(
        "conditions/BUILD", "config_setting(", "    name = 'a',", "    values = {'foo': 'a'})");
    scratch.file("bar/BUILD");
    scratch.file(
        "foo/BUILD",
        "genrule(",
        "    name = 'g',",
        "    outs = ['g.out'],",
        // With an invalid target and a real target, validate skyframe error handling.
        // See http://b/162021059 for details.
        "    cmd = select({'//bar:fake': '', '//conditions:a': ''})",
        ")");
    assertThat(getConfiguredTarget("//foo:g")).isNull();
    assertContainsEvent(
        "While resolving configuration keys for //foo:g: no such target '//bar:fake'");
  }

  /**
   * Tests config keys with multiple requirements.
   */
  @Test
  public void multiConditionConfigKeys() throws Exception {
    writeHelloRules(/*includeDefaultCondition=*/true);
    scratch.file(
        "conditions/BUILD",
        "config_setting(",
        "    name = 'a',",
        "    values = {",
        "        'foo': 'a',",
        "        'compilation_mode': 'dbg'",
        "    })",
        "config_setting(",
        "    name = 'b',",
        "    values = {'foo': 'b'})");
    checkRule(
        "//java/hello:hello",
        "--foo=a",
        /*expected:*/ ImmutableList.of(DEFAULTDEP_INPUT),
        /*not expected:*/ ImmutableList.of(ADEP_INPUT, BDEP_INPUT));
    checkRule(
        "//java/hello:hello",
        ImmutableList.of("--foo=a", "--compilation_mode=dbg"),
        /*expected:*/ ImmutableList.of(ADEP_INPUT),
        /*not expected:*/ ImmutableList.of(BDEP_INPUT, DEFAULTDEP_INPUT));
  }

  /**
   * Tests that changing a config_setting invalidates the rule that uses it.
   */
  @Test
  public void configKeyInvalidation() throws Exception {
    writeHelloRules(/*includeDefaultCondition=*/true);
    writeConfigRules();

    // Iteration 1: --test_args=a should apply //conditions:a.
    useConfiguration("--foo=a");
    checkRule(
        "//java/hello:hello",
        "--foo=a",
        /*expected:*/ ImmutableList.of(ADEP_INPUT),
        /*not expected:*/ ImmutableList.of(BDEP_INPUT, DEFAULTDEP_INPUT));

    // Rewrite the condition for //conditions:a.
    scratch.overwriteFile(
        "conditions/BUILD",
        "config_setting(",
        "    name = 'a',",
        "    values = {'foo': 'c'})",
        "config_setting(",
        "    name = 'b',",
        "    values = {'foo': 'b'})");

    // Iteration 2: same exact analysis should now apply the default condition.
    invalidatePackages();
    checkRule(
        "//java/hello:hello",
        "--foo=a",
        /*expected:*/ ImmutableList.of(DEFAULTDEP_INPUT),
        /*not expected:*/ ImmutableList.of(ADEP_INPUT, BDEP_INPUT));
  }

  /**
   * Tests that multiple matches are not allowed for conditions where one is not a specialization
   * of the other.
   */
  @Test
  public void multipleMatches() throws Exception {
    reporter.removeHandler(failFastHandler); // Expect errors.
    scratch.file("conditions/BUILD",
        "config_setting(",
        "    name = 'dup1',",
        "    values = {'compilation_mode': 'opt'})",
        "config_setting(",
        "    name = 'dup2',",
        "    values = {'define': 'foo=bar'})");
    scratch.file("a/BUILD",
        "genrule(",
        "    name = 'gen',",
        "    cmd = '',",
        "    outs = ['gen.out'],",
        "    srcs = select({",
        "        '//conditions:dup1': ['a.in'],",
        "        '//conditions:dup2': ['b.in'],",
        "        '" + BuildType.Selector.DEFAULT_CONDITION_KEY + "': [':default.in'],",
        "    }))");
    useConfiguration("-c", "opt", "--define", "foo=bar");
    assertThat(getConfiguredTarget("//a:gen")).isNull();
    assertContainsEvent(
        "Illegal ambiguous match on configurable attribute \"srcs\" in //a:gen:\n"
            + "//conditions:dup1\n"
            + "//conditions:dup2\n"
            + "Multiple matches are not allowed unless one is unambiguously more specialized.");
  }

  /**
   * Tests that when multiple conditions match and for every matching pair, one is
   * a specialization of the other, the most specialized match is chosen.
   */
  @Test
  public void multipleMatchesConditionAndSubcondition() throws Exception {
    scratch.file(
        "conditions/BUILD",
        "config_setting(",
        "    name = 'generic',",
        "    values = {'compilation_mode': 'opt'})",
        "config_setting(",
        "    name = 'precise',",
        "    values = {'compilation_mode': 'opt', 'define': 'foo=bar'})",
        "config_setting(",
        "    name = 'most_precise',",
        "    values = {'compilation_mode': 'opt', 'define': 'foo=bar', 'foo': 'baz'})");
        scratch.file("java/a/BUILD",
            "java_binary(",
            "    name = 'binary',",
            "    srcs = ['binary.java'],",
            "    deps = select({",
            "        '//conditions:generic': [':generic'],",
            "        '//conditions:precise': [':precise'],",
            "        '//conditions:most_precise': [':most_precise'],",
            "    }))",
            "java_library(",
            "    name = 'generic',",
            "    srcs = ['generic.java'])",
            "java_library(",
            "    name = 'precise',",
            "    srcs = ['precise.java'])",
            "java_library(",
            "    name = 'most_precise',",
            "    srcs = ['most_precise.java'])");
    checkRule(
        "//java/a:binary",
        ImmutableList.of("-c", "opt", "--define", "foo=bar", "--foo", "baz"),
        /*expected:*/ ImmutableList.of("bin java/a/libmost_precise.jar"),
        /*not expected:*/ ImmutableList.of(
            "bin java/a/libgeneric.jar", "bin java/a/libprecise.jar"));
  }

  /**
   * Tests that when multiple conditions match but one condition is more specialized than the
   * others, it is chosen and there is no error.
   */
  @Test
  public void multipleMatchesUnambiguous() throws Exception {
    scratch.file(
        "conditions/BUILD",
        "config_setting(",
        "    name = 'a',",
        "    values = {'define': 'a=1'})",
        "config_setting(",
        "    name = 'b',",
        "    values = {'compilation_mode': 'opt'})",
        "config_setting(",
        "    name = 'c',",
        "    values = {'foo': 'baz'})",
        "config_setting(",
        "    name = 'b_a_c',", // Named to come alphabetically after a and b but before c.
        "    values = {'define': 'a=1', 'foo': 'baz', 'compilation_mode': 'opt'})");
    scratch.file("java/a/BUILD",
        "java_binary(",
        "    name = 'binary',",
        "    srcs = ['binary.java'],",
        "    deps = select({",
        "        '//conditions:a': [':a'],",
        "        '//conditions:b': [':b'],",
        "        '//conditions:c': [':c'],",
        "        '//conditions:b_a_c': [':b_a_c'],",
        "    }))",
        "java_library(",
        "    name = 'a',",
        "    srcs = ['a.java'])",
        "java_library(",
        "    name = 'b',",
        "    srcs = ['b.java'])",
        "java_library(",
        "    name = 'c',",
        "    srcs = ['c.java'])",
        "java_library(",
        "    name = 'b_a_c',",
        "    srcs = ['b_a_c.java'])");
    checkRule(
        "//java/a:binary",
        ImmutableList.of("--define", "a=1", "--compilation_mode", "opt", "--foo", "baz"),
        /*expected:*/ ImmutableList.of("bin java/a/libb_a_c.jar"),
        /*not expected:*/ ImmutableList.of(
            "bin java/a/liba.jar", "bin java/a/libb.jar", "bin java/a/libc.jar"));
  }

  /** Tests that default conditions are only required when no main condition matches. */
  @Test
  public void noDefaultCondition() throws Exception {
    writeHelloRules(/*includeDefaultCondition=*/false);
    writeConfigRules();

    // An explicit configuration matches: all is well.
    checkRule(
        "//java/hello:hello",
        "--foo=a",
        /*expected:*/ ImmutableList.of(ADEP_INPUT),
        /*not expected:*/ ImmutableList.of(BDEP_INPUT, DEFAULTDEP_INPUT));

    // Nothing matches: expect an error.
    reporter.removeHandler(failFastHandler);
    useConfiguration("");
    assertThat(getConfiguredTarget("//java/hello:hello")).isNull();
    assertContainsEvent(
        "configurable attribute \"deps\" in //java/hello:hello doesn't match this configuration");
  }

  @Test
  public void noMatchCustomErrorMessage() throws Exception {
    writeConfigRules();
    scratch.file("java/hello/BUILD",
        "java_binary(",
        "    name = 'hello_default_no_match_error',",
        "    srcs = select({",
        "        '//conditions:a': ['not_chosen.java'],",
        "    }))",
        "java_binary(",
        "    name = 'hello_custom_no_match_error',",
        "    srcs = select({",
        "        '//conditions:a': ['not_chosen.java'],",
        "    },",
        "    no_match_error = 'You always have to choose condition a!'",
        "))");

    reporter.removeHandler(failFastHandler);
    AnalysisFailureRecorder analysisFailureRecorder = new AnalysisFailureRecorder();
    eventBus.register(analysisFailureRecorder);
    useConfiguration("");

    assertThat(getConfiguredTarget("//java/hello:hello_default_no_match_error")).isNull();
    assertContainsEvent(
        "configurable attribute \"srcs\" in //java/hello:hello_default_no_match_error doesn't"
            + " match this configuration. Would a default condition help?\n"
            + "\n"
            + "Conditions checked:");
    // Verify a Root Cause is reported when a target cannot be configured due to no matching config.
    assertThat(analysisFailureRecorder.causes).hasSize(1);
    AnalysisRootCauseEvent rootCause = analysisFailureRecorder.causes.get(0);
    assertThat(rootCause.getLabel())
        .isEqualTo(
            Label.parseAbsolute("//java/hello:hello_default_no_match_error", ImmutableMap.of()));

    eventBus.unregister(analysisFailureRecorder);
    analysisFailureRecorder = new AnalysisFailureRecorder();
    eventBus.register(analysisFailureRecorder);
    eventCollector.clear();

    assertThat(getConfiguredTarget("//java/hello:hello_custom_no_match_error")).isNull();
    assertContainsEvent(
        "configurable attribute \"srcs\" in //java/hello:hello_custom_no_match_error doesn't match "
            + "this configuration: You always have to choose condition a!");
    // Verify a Root Cause is reported when a target cannot be configured due to no matching config.
    assertThat(analysisFailureRecorder.causes).hasSize(1);
    rootCause = analysisFailureRecorder.causes.get(0);
    assertThat(rootCause.getLabel())
        .isEqualTo(
            Label.parseAbsolute("//java/hello:hello_custom_no_match_error", ImmutableMap.of()));
  }

  @Test
  public void nativeTypeConcatenatedWithSelect() throws Exception {
    writeConfigRules();
    scratch.file("java/foo/BUILD",
        "java_binary(",
        "    name = 'binary',",
        "    srcs = ['binary.java'],",
        "    deps = [':always'] + select({",
        "        '//conditions:a': [':a'],",
        "        '//conditions:b': [':b'],",
        "    })",
        ")",
        "java_library(",
        "    name = 'always',",
        "    srcs = ['always.java'])",
        "java_library(",
        "    name = 'a',",
        "    srcs = ['a.java'])",
        "java_library(",
        "    name = 'b',",
        "    srcs = ['b.java'])");

    checkRule(
        "//java/foo:binary",
        "--foo=b",
        /*expected:*/ ImmutableList.of("bin java/foo/libalways.jar", "bin java/foo/libb.jar"),
        /*not expected:*/ ImmutableList.of("bin java/foo/liba.jar"));
  }

  @Test
  public void selectConcatenatedWithNativeType() throws Exception {
    writeConfigRules();
    scratch.file("java/foo/BUILD",
        "java_binary(",
        "    name = 'binary',",
        "    srcs = ['binary.java'],",
        "    deps = select({",
        "        '//conditions:a': [':a'],",
        "        '//conditions:b': [':b'],",
        "    }) + [':always'])",
        "java_library(",
        "    name = 'always',",
        "    srcs = ['always.java'])",
        "java_library(",
        "    name = 'a',",
        "    srcs = ['a.java'])",
        "java_library(",
        "    name = 'b',",
        "    srcs = ['b.java'])");

    checkRule(
        "//java/foo:binary",
        "--foo=b",
        /*expected:*/ ImmutableList.of("bin java/foo/libalways.jar", "bin java/foo/libb.jar"),
        /*not expected:*/ ImmutableList.of("bin java/foo/liba.jar"));
  }

  @Test
  public void selectConcatenatedWithSelect() throws Exception {
    writeConfigRules();
    scratch.file("java/foo/BUILD",
        "java_binary(",
        "    name = 'binary',",
        "    srcs = ['binary.java'],",
        "    deps = select({",
        "        '//conditions:a': [':a'],",
        "        '//conditions:b': [':b'],",
        "    }) + select({",
        "        '//conditions:a': [':a2'],",
        "        '//conditions:b': [':b2'],",
        "    })",
        ")",
        "java_library(",
        "    name = 'a',",
        "    srcs = ['a.java'])",
        "java_library(",
        "    name = 'b',",
        "    srcs = ['b.java'])",
        "java_library(",
        "    name = 'a2',",
        "    srcs = ['a2.java'])",
        "java_library(",
        "    name = 'b2',",
        "    srcs = ['b2.java'])");

    checkRule(
        "//java/foo:binary",
        "--foo=b",
        /*expected:*/ ImmutableList.of("bin java/foo/libb.jar", "bin java/foo/libb2.jar"),
        /*not expected:*/ ImmutableList.of("bin java/foo/liba.jar", "bin java/foo/liba2.jar"));
  }

  @Test
  public void selectConcatenatedWithNonSupportingType() throws Exception {
    writeConfigRules();
    scratch.file("foo/BUILD",
        "rule_with_boolean_attr(",
        "    name = 'binary',",
        "    boolean_attr= 0 + select({",
        "        '//conditions:a': 0,",
        "        '//conditions:b': 1,",
        "    }))");

    reporter.removeHandler(failFastHandler);
    assertThat(getConfiguredTarget("//foo:binary")).isNull();
    assertContainsEvent("type 'boolean' doesn't support select concatenation");
  }

  @Test
  public void concatenationWithDifferentTypes() throws Exception {
    writeConfigRules();
    scratch.file("java/foo/BUILD",
        "java_binary(",
        "    name = 'binary',",
        "    srcs = select({",
        "        '//conditions:a': ['a.java'],",
        "        '//conditions:b': ['b.java'],",
        "    }) + 'always.java'",
        ")");

    reporter.removeHandler(failFastHandler);
    assertThrows(NoSuchTargetException.class, () -> getTarget("//java/foo:binary"));
    assertContainsEvent("'+' operator applied to incompatible types");
  }

  @Test
  public void selectsWithGlobs() throws Exception {
    writeConfigRules();
    scratch.file("java/foo/globbed/ceecee.java");
    scratch.file("java/foo/BUILD",
        "java_binary(",
        "    name = 'binary',",
        "    srcs = glob(['globbed/*.java']) + select({",
        "        '//conditions:a': ['a.java'],",
        "        '//conditions:b': ['b.java'],",
        "    }))");

    useConfiguration("--foo=b");
    ConfiguredTarget binary = getConfiguredTarget("//java/foo:binary");
    assertThat(binary).isNotNull();
    Set<String> sources = artifactsToStrings(getPrerequisiteArtifacts(binary, "srcs"));
    assertThat(sources).contains("src java/foo/b.java");
    assertThat(sources).contains("src java/foo/globbed/ceecee.java");
    assertThat(sources).doesNotContain("src java/foo/a.java");
  }

  @Test
  public void selectsWithGlobsWrongType() throws Exception {
    writeConfigRules();
    scratch.file("foo/BUILD",
        "genrule(",
        "    name = 'gen',",
        "    srcs = [],",
        "    outs = ['gen.out'],",
        "    cmd = 'echo' + select({",
        "        '//conditions:a': 'a',",
        "        '//conditions:b': 'b',",
        "    }) + glob(['globbed.java']))");

    reporter.removeHandler(failFastHandler);
    assertThrows(NoSuchTargetException.class, () -> getTarget("//foo:binary"));
    assertContainsEvent("'+' operator applied to incompatible types");
  }

  @Test
  public void globsInSelect() throws Exception {
    writeConfigRules();
    scratch.file("java/foo/globbed/ceecee.java");
    scratch.file("java/foo/BUILD",
        "java_binary(",
        "    name = 'binary',",
        "    srcs = ['binary.java'] + select({",
        "        '//conditions:a': glob(['globbed/*.java']),",
        "        '//conditions:b': ['b.java'],",
        "    }))");

    useConfiguration("--foo=a");
    ConfiguredTarget binary = getConfiguredTarget("//java/foo:binary");
    assertThat(binary).isNotNull();
    Set<String> sources = artifactsToStrings(getPrerequisiteArtifacts(binary, "srcs"));
    assertThat(sources).contains("src java/foo/binary.java");
    assertThat(sources).contains("src java/foo/globbed/ceecee.java");
    assertThat(sources).doesNotContain("src java/foo/b.java");
  }

  @Test
  public void selectAcceptedInAttributeWithAllowedValues() throws Exception {
    scratch.file("foo/BUILD",
        "rule_with_allowed_values(",
        "    name = 'rule',",
        "    one_two = select({",
        "        '//conditions:default': 'one',",
        "    }))");
    assertThat(getConfiguredTarget("//foo:rule")).isNotNull();
  }

  @Test
  public void selectWithNonAllowedValueCausesError() throws Exception {
    scratch.file("foo/BUILD",
        "rule_with_allowed_values(",
        "    name = 'rule',",
        "    one_two = select({",
        "        '//conditions:default': 'TOTALLY_ILLEGAL_VALUE',",
        "    }))");
    reporter.removeHandler(failFastHandler); // Expect errors.
    getConfiguredTarget("//foo:rule");
    assertContainsEvent(
        "invalid value in 'one_two' attribute: "
        + "has to be one of 'one' or 'two' instead of 'TOTALLY_ILLEGAL_VALUE'");
  }

  @Test
  public void selectWithMultipleNonAllowedValuesCausesMultipleErrors() throws Exception {
    scratch.file("foo/BUILD",
        "rule_with_allowed_values(",
        "    name = 'rule',",
        "    one_two = select({",
        "        '//conditions:a': 'TOTALLY_ILLEGAL_VALUE',",
        "        '//conditions:default': 'DIFFERENT_BUT_STILL_ILLEGAL',",
        "    }))");
    reporter.removeHandler(failFastHandler); // Expect errors.
    getConfiguredTarget("//foo:rule");
    assertContainsEvent(
        "invalid value in 'one_two' attribute: "
        + "has to be one of 'one' or 'two' instead of 'TOTALLY_ILLEGAL_VALUE'");
    assertContainsEvent(
        "invalid value in 'one_two' attribute: "
        + "has to be one of 'one' or 'two' instead of 'DIFFERENT_BUT_STILL_ILLEGAL'");
  }

  @Test
  public void selectConcatenationWithAllowedValues() throws Exception {
    scratch.file("foo/BUILD",
           "rule_with_allowed_values(",
           "    name = 'rule',",
           "    one_two = 'on' + select({",
           "        '//conditions:default': 'e',",
           "    }))");
    assertThat(getConfiguredTarget("//foo:rule")).isNotNull();
  }

  @Test
  public void selectConcatenationWithNonAllowedValues() throws Exception {
    scratch.file("foo/BUILD",
           "rule_with_allowed_values(",
           "    name = 'rule',",
           "    one_two = 'on' + select({",
           "        '//conditions:default': 'o',",
           "    }))");
    reporter.removeHandler(failFastHandler); // Expect errors.
    getConfiguredTarget("//foo:binary");
    assertContainsEvent(
        "invalid value in 'one_two' attribute: "
        + "has to be one of 'one' or 'two' instead of 'ono'");
  }

  @Test
  public void computedDefaultAttributesCanReferenceConfigurableAttributes() throws Exception {
    scratch.file(
        "test/selector_rules.bzl",
        "def _impl(ctx):",
        "  ctx.actions.write(",
        "      output=ctx.outputs.out_file,",
        "      content=ctx.attr.string_value,",
        "  )",
        "  return []",
        "",
        "def _derived_value(string_value):",
        "  return Label(\"//test:%s\" % string_value)",
        "",
        "selector_rule = rule(",
        "  attrs = {",
        "      \"string_value\": attr.string(default = \"\"),",
        "      \"out_file\": attr.output(),",
        "      \"_derived\": attr.label(default = _derived_value),",
        "  },",
        "implementation = _impl,",
        ")");
    scratch.file("test/BUILD",
        "genrule(name = \"foo\", srcs = [], outs = [\"foo.out\"], cmd = \"\")");
    scratch.file(
        "foo/BUILD",
        "load('//test:selector_rules.bzl', \"selector_rule\")",
        "selector_rule(",
        "    name = \"rule\",",
        "    out_file = \"rule.out\",",
        "    string_value = select({\"//conditions:default\": \"foo\"}),",
        ")");
    getConfiguredTarget("//foo:rule");
    assertNoEvents();
  }

  @Test
  public void selectableDefaultValueWithTypeDefault() throws Exception {
    writeConfigRules();
    scratch.file("srctest/BUILD",
        "genrule(",
        "    name = 'gen',",
        "    cmd = '',",
        "    outs = ['gen.out'],",
        "    srcs = select({",
        "        '//conditions:a': None,",
        "    }))");

    useConfiguration("--foo=a");
    ConfiguredTargetAndData ctad = getConfiguredTargetAndData("//srctest:gen");
    AttributeMap attributes = getMapperFromConfiguredTargetAndTarget(ctad);
    assertThat(attributes.get("srcs", LABEL_LIST)).isEmpty();
  }

  @Test
  public void selectableDefaultValueWithRuleDefault() throws Exception {
    writeConfigRules();
    scratch.file("foo/BUILD",
        "rule_with_label_default(",
        "    name = 'rule',",
        "    dep = select({",
        "        '//conditions:a': None,",
        "    }))",
        "rule_with_boolean_attr(",
        "    name = 'default',",
        "    boolean_attr = 1)");

    useConfiguration("--foo=a");
    ConfiguredTargetAndData ctad = getConfiguredTargetAndData("//foo:rule");
    AttributeMap attributes = getMapperFromConfiguredTargetAndTarget(ctad);
    assertThat(attributes.get("dep", BuildType.LABEL))
        .isEqualTo(Label.parseAbsolute("//foo:default", ImmutableMap.of()));
  }

  @Test
  public void noneValuesWithMultipleSelectsMixedValues() throws Exception {
    writeConfigRules();
    scratch.file("a/BUILD",
        "genrule(",
        "    name = 'gen',",
        "    srcs = [],",
        "    outs = ['out'],",
        "    cmd = '',",
        "    message = select({",
        "        '//conditions:a': 'defined message 1',",
        "        '//conditions:b': None,",
        "    }) + select({",
        "        '//conditions:a': None,",
        "        '//conditions:b': 'defined message 2',",
        "    }),",
        ")");

    reporter.removeHandler(failFastHandler);
    useConfiguration("--define", "mode=a");
    assertThat(getConfiguredTarget("//a:gen")).isNull();
    assertContainsEvent(
        "'+' operator applied to incompatible types (select of string, select of NoneType)");
  }

  @Test
  public void emptySelectCannotBeConcatenated() throws Exception {
    scratch.file("a/BUILD",
        "genrule(",
        "    name = 'gen',",
        "    srcs = [],",
        "    outs = ['out'],",
        "    cmd = select({}) + ' always include'",
        ")");

    reporter.removeHandler(failFastHandler);
    assertThat(getConfiguredTarget("//a:gen")).isNull();
    assertContainsEvent(
        "select({}) with an empty dictionary can never resolve because it includes no conditions "
            + "to match");
  }

  @Test
  public void selectOnConstraints() throws Exception {
    // create some useful constraints and platforms.
    scratch.file(
        "conditions/BUILD",
        "constraint_setting(name = 'fruit')",
        "constraint_value(name = 'apple', constraint_setting = 'fruit')",
        "constraint_value(name = 'banana', constraint_setting = 'fruit')",
        "platform(",
        "    name = 'apple_platform',",
        "    constraint_values = [':apple'],",
        ")",
        "platform(",
        "    name = 'banana_platform',",
        "    constraint_values = [':banana'],",
        ")",
        "config_setting(",
        "    name = 'a',",
        "    constraint_values = [':apple']",
        ")",
        "config_setting(",
        "    name = 'b',",
        "    constraint_values = [':banana']",
        ")");
    scratch.file(
        "check/BUILD",
        "filegroup(name = 'adep', srcs = ['afile'])",
        "filegroup(name = 'bdep', srcs = ['bfile'])",
        "filegroup(name = 'defaultdep', srcs = ['defaultfile'])",
        "filegroup(name = 'hello',",
        "    srcs = select({",
        "        '//conditions:a': [':adep'],",
        "        '//conditions:b': [':bdep'],",
        "        '" + BuildType.Selector.DEFAULT_CONDITION_KEY + "': [':defaultdep'],",
        "    }))");
    checkRule(
        "//check:hello",
        "srcs",
        ImmutableList.of("--experimental_platforms=//conditions:apple_platform"),
        /*expected:*/ ImmutableList.of("src check/afile"),
        /*not expected:*/ ImmutableList.of("src check/bfile", "src check/defaultfile"));
  }

  @Test
  public void selectDirectlyOnConstraints() throws Exception {
    // Tests select()ing directly on a constraint_value (with no intermediate config_setting).
    scratch.file(
        "conditions/BUILD",
        "constraint_setting(name = 'fruit')",
        "constraint_value(name = 'apple', constraint_setting = 'fruit')",
        "constraint_value(name = 'banana', constraint_setting = 'fruit')",
        "platform(",
        "    name = 'apple_platform',",
        "    constraint_values = [':apple'],",
        ")",
        "platform(",
        "    name = 'banana_platform',",
        "    constraint_values = [':banana'],",
        ")");
    scratch.file(
        "check/defs.bzl",
        "def _impl(ctx):",
        "  pass",
        "simple_rule = rule(",
        "  implementation = _impl,",
        "  attrs = {'srcs': attr.label_list(allow_files = True)}",
        ")");
    scratch.file(
        "check/BUILD",
        "load('//check:defs.bzl', 'simple_rule')",
        "filegroup(name = 'adep', srcs = ['afile'])",
        "filegroup(name = 'bdep', srcs = ['bfile'])",
        "simple_rule(name = 'hello',",
        "    srcs = select({",
        "        '//conditions:apple': [':adep'],",
        "        '//conditions:banana': [':bdep'],",
        "    }))");
    checkRule(
        "//check:hello",
        "srcs",
        ImmutableList.of("--platforms=//conditions:apple_platform"),
        /*expected:*/ ImmutableList.of("src check/afile"),
        /*not expected:*/ ImmutableList.of("src check/bfile", "src check/defaultfile"));
    checkRule(
        "//check:hello",
        "srcs",
        ImmutableList.of("--platforms=//conditions:banana_platform"),
        /*expected:*/ ImmutableList.of("src check/bfile"),
        /*not expected:*/ ImmutableList.of("src check/afile", "src check/defaultfile"));
  }

  @Test
  public void nonToolchainResolvingTargetsCantSelectDirectlyOnConstraints() throws Exception {
    // Tests select()ing directly on a constraint_value (with no intermediate config_setting).
    scratch.file(
        "conditions/BUILD",
        "constraint_setting(name = 'fruit')",
        "constraint_value(name = 'apple', constraint_setting = 'fruit')",
        "platform(",
        "    name = 'apple_platform',",
        "    constraint_values = [':apple'],",
        ")");
    scratch.file(
        "check/BUILD",
        "filegroup(name = 'adep', srcs = ['afile'])",
        "rule_with_no_platform(name = 'hello',",
        "    deps = select({",
        "        '//conditions:apple': [':adep'],",
        "    })",
        ")");
    reporter.removeHandler(failFastHandler);
    useConfiguration("--platforms=//conditions:apple_platform");
    assertThat(getConfiguredTarget("//check:hello")).isNull();
    assertContainsEvent("//conditions:apple is not a valid select() condition for //check:hello");
  }

  @Test
  public void multipleMatchErrorWhenAliasResolvesToSameSetting() throws Exception {
    scratch.file(
        "a/BUILD",
        "config_setting(",
        "    name = 'foo',",
        "    define_values = { 'foo': '1' })",
        "alias(",
        "    name = 'alias_to_foo',",
        "    actual = ':foo')",
        "rule_with_boolean_attr(",
        "    name = 'binary',",
        "    boolean_attr= select({",
        "        ':foo': 0,",
        "        'alias_to_foo': 1,",
        "    }))");
    reporter.removeHandler(failFastHandler);
    assertThat(getConfiguredTarget("//a:binary")).isNull();
    assertContainsEvent(
        "configurable attribute \"boolean_attr\" in //a:binary doesn't match this configuration. "
            + "Would a default condition help?\n\n"
            + "Conditions checked:\n"
            + " //a:foo\n"
            + " //a:alias_to_foo");
  }

  @Test
  public void defaultVisibilityConfigSetting_noVisibilityEnforcement() throws Exception {
    // Production builds default to private visibility, but BuildViewTestCase defaults to public.
    setPackageOptions("--default_visibility=private",
        "--incompatible_enforce_config_setting_visibility=false");
    scratch.file("c/BUILD", "config_setting(name = 'foo', define_values = { 'foo': '1' })");
    scratch.file(
        "a/BUILD",
        "rule_with_boolean_attr(",
        "    name = 'binary',",
        "    boolean_attr= select({",
        "        '//c:foo': 0,",
        "        '//conditions:default': 1",
        "    }))");
    reporter.removeHandler(failFastHandler);
    assertThat(getConfiguredTarget("//a:binary")).isNotNull();
    assertNoEvents();
  }

  @Test
  public void privateVisibilityConfigSetting_noVisibilityEnforcement() throws Exception {
    // Production builds default to private visibility, but BuildViewTestCase defaults to public.
    setPackageOptions("--default_visibility=private",
        "--incompatible_enforce_config_setting_visibility=false");
    scratch.file(
        "c/BUILD",
        "config_setting(",
        "    name = 'foo',",
        "    define_values = { 'foo': '1' },",
        "    visibility = ['//visibility:private']",
        ")");
    scratch.file(
        "a/BUILD",
        "rule_with_boolean_attr(",
        "    name = 'binary',",
        "    boolean_attr= select({",
        "        '//c:foo': 0,",
        "        '//conditions:default': 1",
        "    }))");
    reporter.removeHandler(failFastHandler);
    assertThat(getConfiguredTarget("//a:binary")).isNotNull();
    assertNoEvents();
  }

  @Test
  public void publicVisibilityConfigSetting__noVisibilityEnforcement() throws Exception {
    // Production builds default to private visibility, but BuildViewTestCase defaults to public.
    setPackageOptions("--default_visibility=private",
        "--incompatible_enforce_config_setting_visibility=false");
    scratch.file(
        "c/BUILD",
        "config_setting(",
        "    name = 'foo',",
        "    define_values = { 'foo': '1' },",
        "    visibility = ['//visibility:public']",
        ")");
    scratch.file(
        "a/BUILD",
        "rule_with_boolean_attr(",
        "    name = 'binary',",
        "    boolean_attr= select({",
        "        '//c:foo': 0,",
        "        '//conditions:default': 1",
        "    }))");
    reporter.removeHandler(failFastHandler);
    assertThat(getConfiguredTarget("//a:binary")).isNotNull();
    assertNoEvents();
  }
  @Test
  public void defaultVisibilityConfigSetting_defaultIsPublic() throws Exception {
    // Production builds default to private visibility, but BuildViewTestCase defaults to public.
    setPackageOptions("--default_visibility=private",
        "--incompatible_enforce_config_setting_visibility=true",
        "--incompatible_config_setting_private_default_visibility=false");
    scratch.file("c/BUILD", "config_setting(name = 'foo', define_values = { 'foo': '1' })");
    scratch.file(
        "a/BUILD",
        "rule_with_boolean_attr(",
        "    name = 'binary',",
        "    boolean_attr= select({",
        "        '//c:foo': 0,",
        "        '//conditions:default': 1",
        "    }))");
    reporter.removeHandler(failFastHandler);
    assertThat(getConfiguredTarget("//a:binary")).isNotNull();
    assertNoEvents();
  }

  @Test
  public void privateVisibilityConfigSetting_defaultIsPublic() throws Exception {
    // Production builds default to private visibility, but BuildViewTestCase defaults to public.
    setPackageOptions("--default_visibility=private",
        "--incompatible_enforce_config_setting_visibility=true",
        "--incompatible_config_setting_private_default_visibility=false");
    scratch.file(
        "c/BUILD",
        "config_setting(",
        "    name = 'foo',",
        "    define_values = { 'foo': '1' },",
        "    visibility = ['//visibility:private']",
        ")");
    scratch.file(
        "a/BUILD",
        "rule_with_boolean_attr(",
        "    name = 'binary',",
        "    boolean_attr= select({",
        "        '//c:foo': 0,",
        "        '//conditions:default': 1",
        "    }))");
    reporter.removeHandler(failFastHandler);
    assertThat(getConfiguredTarget("//a:binary")).isNull();
    assertContainsEvent("'//c:foo' is not visible from target '//a:binary'");
  }

  @Test
  public void publicVisibilityConfigSetting_defaultIsPublic() throws Exception {
    // Production builds default to private visibility, but BuildViewTestCase defaults to public.
    setPackageOptions("--default_visibility=private",
        "--incompatible_enforce_config_setting_visibility=true",
        "--incompatible_config_setting_private_default_visibility=false");
    scratch.file(
        "c/BUILD",
        "config_setting(",
        "    name = 'foo',",
        "    define_values = { 'foo': '1' },",
        "    visibility = ['//visibility:public']",
        ")");
    scratch.file(
        "a/BUILD",
        "rule_with_boolean_attr(",
        "    name = 'binary',",
        "    boolean_attr= select({",
        "        '//c:foo': 0,",
        "        '//conditions:default': 1",
        "    }))");
    reporter.removeHandler(failFastHandler);
    assertThat(getConfiguredTarget("//a:binary")).isNotNull();
    assertNoEvents();
  }
  @Test
  public void defaultVisibilityConfigSetting_defaultIsPrivate() throws Exception {
    // Production builds default to private visibility, but BuildViewTestCase defaults to public.
    setPackageOptions("--default_visibility=private",
        "--incompatible_enforce_config_setting_visibility=true",
        "--incompatible_config_setting_private_default_visibility=true");
    scratch.file("c/BUILD", "config_setting(name = 'foo', define_values = { 'foo': '1' })");
    scratch.file(
        "a/BUILD",
        "rule_with_boolean_attr(",
        "    name = 'binary',",
        "    boolean_attr= select({",
        "        '//c:foo': 0,",
        "        '//conditions:default': 1",
        "    }))");
    reporter.removeHandler(failFastHandler);
    assertThat(getConfiguredTarget("//a:binary")).isNull();
    assertContainsEvent("'//c:foo' is not visible from target '//a:binary'");
  }

  @Test
  public void privateVisibilityConfigSetting_defaultIsPrivate() throws Exception {
    // Production builds default to private visibility, but BuildViewTestCase defaults to public.
    setPackageOptions("--default_visibility=private",
        "--incompatible_enforce_config_setting_visibility=true",
        "--incompatible_config_setting_private_default_visibility=true");
    scratch.file(
        "c/BUILD",
        "config_setting(",
        "    name = 'foo',",
        "    define_values = { 'foo': '1' },",
        "    visibility = ['//visibility:private']",
        ")");
    scratch.file(
        "a/BUILD",
        "rule_with_boolean_attr(",
        "    name = 'binary',",
        "    boolean_attr= select({",
        "        '//c:foo': 0,",
        "        '//conditions:default': 1",
        "    }))");
    reporter.removeHandler(failFastHandler);
    assertThat(getConfiguredTarget("//a:binary")).isNull();
    assertContainsEvent("'//c:foo' is not visible from target '//a:binary'");
  }

  @Test
  public void publicVisibilityConfigSetting_defaultIsPrivate() throws Exception {
    // Production builds default to private visibility, but BuildViewTestCase defaults to public.
    setPackageOptions("--default_visibility=private",
        "--incompatible_enforce_config_setting_visibility=true",
        "--incompatible_config_setting_private_default_visibility=true");
    scratch.file(
        "c/BUILD",
        "config_setting(",
        "    name = 'foo',",
        "    define_values = { 'foo': '1' },",
        "    visibility = ['//visibility:public']",
        ")");
    scratch.file(
        "a/BUILD",
        "rule_with_boolean_attr(",
        "    name = 'binary',",
        "    boolean_attr= select({",
        "        '//c:foo': 0,",
        "        '//conditions:default': 1",
        "    }))");
    reporter.removeHandler(failFastHandler);
    assertThat(getConfiguredTarget("//a:binary")).isNotNull();
    assertNoEvents();
  }
}


text:
var AccountManualNewForm = {
	init: function(){
		$('#new_account_date').datepicker({dateFormat: 'mm/dd/yy', altField: '#account_initial_balance_date', altFormat: 'yy-mm-dd'});
	}
};

var AccountEditForm = {
	init: function(){
		$('#transaction_date').datepicker({dateFormat: 'mm/dd/yy', altField: '#account_initial_balance_date', altFormat: 'yy-mm-dd'});
		$('#unlink-account').click(function(){
			$('#account_bank_id').val('');
			$(this).hide();
			$('#linked-fields').hide();
		});
	}
}

var AccountLinkedForm = {
	isNew: false,
	init: function(isNew){
		AccountLinkedForm.isNew = isNew;
		$('#new_account_date').datepicker({dateFormat: 'mm/dd/yy', altField: '#account_initial_balance_date', altFormat: 'yy-mm-dd'});

		$('#account_bank_id').change(function(){
			var selected_option = $('#account_bank_id option:selected');
			$('#bank_standard_ofx_note, #bank_notes').hide();

			if (selected_option.attr("notes") == "true") {
				$.getJSON("banks/" + $(this).val() + "/notes", function( data ) {
					$('#bank_notes').html(data.notes).show();
				});
			} else if (selected_option.attr("ofx") == "true") {
				$('#bank_standard_ofx_note').show();
			}
		});

		$('form#linked_account').submit(function(e){
			var form = $(this);
			$.ajax({
				url: form.attr("action"),
				type: form.attr("method"),
				data: form.serialize(),
				beforeSend:function(data){
    			  $('#modal').html('
Saving...
');
    			}
			}).done(function(data) {
				$('#modal').dialog('close');
				Main.handle_json_response(data);
			}).fail(function(xhr) {
			  	$('#modal').html(xhr.responseText).scrollTop(0).find('.alert-error').effect('bounce');
			  	$('#linked_account_bank_info').hide();
				$('#linked_account_confirm').show();
			});

			e.preventDefault();
		});

		AccountLinkedForm.linkedAdvanceToBankInfo();
	},
	linkedAdvanceToBankInfo: function(){
		 $('form#linked_account fieldset').hide();
		 $('#linked_account_bank_info').show();

		Common.setModalButtons([
				{ text: "Next", class: 'btn btn-success', click: function() { AccountLinkedForm.linkedAdvanceToAccounts(); } },
				{ text: "Cancel", class: 'btn', click: function() { $(this).dialog("close"); } }
			]);

	},
	linkedAdvanceToAccounts: function(){
		$('#linkedaccount_error').hide();

		if ($('#account_bank_id').val() == "") {
			$('#linked_account_error').text("A bank must be selected.").show();
		}
		else if($('#account_linked_user_id').val() == "") {
			$('#linked_account_error').text("A username must be specified.").show();
		}
		else if($('#account_linked_password').val() == "") {
			$('#linked_account_error').text("A password must be specified.").show();
		}
		else{
			$('#linked_account_wait').text('Contacting your bank to get a list of accounts.  Please wait...').show();
			$.post('accounts/linked_bank_accounts', {
				account_bank_id: $('#account_bank_id').val(),
				user_id: $('#account_linked_user_id').val(),
				password: $('#account_linked_password').val(),
				security_answers: $('#account_linked_security_answers').val()
			})
			.done(function( json ) {
				$('#linked_account_wait').hide();

			  	if (json.accounts === undefined || json.accounts.length == 0){
			  		$('#linked_account_error').text('No accounts are available.').show();
			  	}
			  	else {
			  		$('#ofx_bank_accounts').empty();
				  	$.each(json.accounts, function( key, acct ) {
				  		 $('#ofx_bank_accounts').append($('<option>', {
					        value: acct.account_id,
					        text : acct.description,
					        bank_id : acct.bank_id,
					        account_type : acct.account_type
					     	})
				  		 );
					 });

				  	 //everything is good, do the advance now
				  	 $('form#linked_account fieldset').hide();
					 $('#linked_account_select_account').show();

					 if ( AccountLinkedForm.isNew === true ) {
						 Common.setModalButtons([
							{ text: "Next", class: 'btn btn-success', click: function() { AccountLinkedForm.linkedAdvanceToConfirm(); } },
							{ text: "Go Back", class: 'btn', click: function() { AccountLinkedForm.linkedAdvanceToBankInfo(); } },
							{ text: "Cancel", class: 'btn', click: function() { $(this).dialog("close"); } }
						]);
					} else {
						Common.setModalButtons([
						  { text: "Finish", class: 'btn btn-success', click: function() { AccountLinkedForm.setSelectedAccountFields(); $('form#linked_account').submit(); } },
						  { text: "Cancel", class: 'btn', click: function() { $(this).dialog("close"); } }
						]);
					}
			  	}
			})
		    .fail(function( jqxhr, textStatus, error ) {
		    	$('#linked_account_wait').hide();
		    	var response = JSON.parse(jqxhr.responseText);

		  		if (response.is_security_question_asked === true) {
		  			AccountLinkedForm.linkedAdvanceToSecurityQuestion(response.friendly_error);
		  		} else {
		  			$('#linked_account_error').text(response.friendly_error).show();
		  		}
		  	});
		 }
	},
	linkedAdvanceToSecurityQuestion: function(question){
		$('#linked_account_error').hide();
		$('#security_question').text(question);
		$('#account_linked_security_answers').val('');
		$('form#linked_account fieldset').hide();
		$('#linked_account_security_question').show();

		 Common.setModalButtons([
			{ text: "Next", class: 'btn btn-success', click: function() { AccountLinkedForm.linkedAdvanceToAccounts(); } },
			{ text: "Go Back", class: 'btn', click: function() { AccountLinkedForm.linkedAdvanceToBankInfo(); } },
			{ text: "Cancel", class: 'btn', click: function() { $(this).dialog("close"); } }
		]);
	},
	linkedAdvanceToConfirm: function(){
		$('#linked_account_error').hide();
		$('#linked_account_wait').text('Contacting your bank to get latest account balance.  Please wait...').show();

		var selected_account = $('#ofx_bank_accounts option:selected');

		$.post('accounts/linked_bank_balance', {
			account_bank_id: $('#account_bank_id').val(),
			user_id: $('#account_linked_user_id').val(),
			password: $('#account_linked_password').val(),
			bank_id: selected_account.attr('bank_id'),
			account_id: selected_account.val(),
			account_type: selected_account.attr('account_type'),
		})
	    .done(function( json ) {
	    	$('#linked_account_wait').hide();

		  	if (json === undefined || json === null){
		  		$('#linked_account_error').text('Account balance could not be retrieved.').show();
		  	}
		  	else {
		  		$('#account_name').val(selected_account.text());
		  		$('#new_account_date').datepicker( "setDate", $.datepicker.parseDate("yy-mm-dd", json.balance_date ) );
		  		$('#account_initial_balance_amount').val(parseFloat(json.balance).toFixed(2));
			  	$('#account_linked_initial_balance_bank_transaction_ids').val(json.balance_transaction_ids);

			  	AccountLinkedForm.setSelectedAccountFields();

			  	if ($('#save_password').prop('checked') === false) {
			  		$('#account_linked_password').val('');
			  	}

			  	 //everything is good, do the advance now
			  	 $('form#linked_account fieldset').hide();
				$('#linked_account_confirm').show();

				Common.setModalButtons([
				  { text: "Finish", class: 'btn btn-success', click: function() { $('form#linked_account').submit(); } },
				  { text: "Cancel", class: 'btn', click: function() { $(this).dialog("close"); } }
				]);
		  	}
	  	})
	    .fail(function( jqxhr, textStatus, error ) {
		  	$('#linked_account_wait').hide();
		  	$('#linked_account_error').text(JSON.parse(jqxhr.responseText).friendly_error).show();
		});
	},
	setSelectedAccountFields: function(){
		var selected_account = $('#ofx_bank_accounts option:selected');
		$('#account_linked_account_number').val(selected_account.val());
		$('#account_linked_bank_code').val(selected_account.attr('bank_id'));
		$('#account_account_type').val(selected_account.attr('account_type'));
	}
};

var AccountsList = {
	currentAccountID: null,
	init : function(){
		$('#accounts').on('click', 'li', function(e){
			AccountsList.select($(this).attr('account_id'));
		}).disableSelection();

		$('#accounts').on('dblclick', 'li', function(e){
			Common.openModalLink('/accounts/' + $(this).attr('account_id') + '/edit', 'Edit Account');
		});

		AccountsList.refresh();
	},
	select: function(id){
		$('#envelope-tree li').removeClass('ui-selected');
		AccountsList.currentAccountID = id;
		EnvelopesList.currentEnvelopeID = null;
		var acct = $('#account-tree li.account[account_id=' + id + ']');
		$('#account-tree li.account').not(acct).removeClass('ui-selected');
		acct.addClass('ui-selected');
		TransactionsList.load(id, 'account');
		$('#transactions-title').text(acct.find('.account-name').text());
	},
	refresh: function(handler){
		$('#accounts').load('/accounts/');
	},
	update: function (accounts) {
		$.each(accounts, function(i, item){
			var account = $('#account-tree li[account_id="' + item.id + '"]');
			$('div.account-name', account).text(item.name);
			if (account.hasClass('ui-selected')){
				$('#transactions-title').text(item.name);
			}
			if (item.balance !== undefined) {
				$('.account-balance', account)
					.html(parseFloat(item.balance).toFixed(2))
					.effect('highlight', { color: '#9BFFA3' }, 2000);
			}
		});
	}
};


text:
require 'json'

# twilio related routes
class WsApp < Sinatra::Application

  post '/twilio/door' do
    num = Number.get(:number => params['From'])
    if num && num['authorized']
      answer_and_open(num)
    else
      answer_and_redirect(num)
    end
  end

  get '/twilio/human' do
    redirect '/twilio/door' unless params['Digits'] == '1'
    Twilio::TwiML::Response.new do |r|
      r.Dial Number.on_duty ### Connect the caller to a human
      r.Say 'The call failed or the remote party hung up. Goodbye.'
    end.text
  end

  private
  def answer_and_open(num)
    all_lang_msg = messages_yml
    Door.open
    Notifier.notify num['name']
    Twilio::TwiML::Response.new do |r|
      lang = ['fr', 'it', 'es', 'en'].shuffle.first
      lang = num['lang'] if num['lang'] != 'rand'
      speaker = ['woman','man'].shuffle.first
      messages = all_lang_msg[lang || 'en']
      r.Say "#{messages['hello']} #{num['name']}, #{messages['hello1']}",
        :voice => speaker, :language => lang || 'en'
      r.Say "#{messages['hello2']}",
        :voice => speaker, :language => lang || 'en'
      r.Say Quote.random(lang || 'en')
    end.text
  end

  def answer_and_redirect(num)
    Twilio::TwiML::Response.new do |r|
      r.Gather :numDigits => '1',
        :action => '/twilio/human', :method => 'get' do |g|
        g.Say "I don't know you, Do you want to speak \
          to a human ? Press 1 if you do."
        g.Say 'Press any other key to start over.'
      end
    end.text
  end

  def messages_yml
    YAML.load_file File.expand_path("../../../config/messages.yml", __FILE__)
  end

end


text:
export declare const Glyphs: string[];
/**
 * CalculateStringSize
 * @param selector
 * @param string
 * @constructor
 */
export declare function CalculateStringSize(selector: string, string: string): number;
/**
 * MeasureGlyphSize
 * @param element
 * @param glyph
 * @returns {number}
 * @constructor
 */
export declare function MeasureGlyphSize(element: HTMLSpanElement, glyph: string): number;


text:
package poll

var CAPI = map[string]struct{}{}


text:
const chai = require('chai');
const expect = chai.expect;
const getHeadersInFolder = require('../../src/ios/getHeadersInFolder');
const mock = require('mock-fs');

describe('ios::getHeadersInFolder', () => {

  it('should return an array of all headers in given folder', () => {
    mock({
      'FileA.h': '',
      'FileB.h': '',
    });

    const foundHeaders = getHeadersInFolder(process.cwd());

    expect(foundHeaders.length).to.equals(2);

    getHeadersInFolder(process.cwd()).forEach(headerPath => {
      expect(headerPath).to.contain(process.cwd());
    });
  });

  it('should ignore all headers in Pods, Examples & node_modules', () => {
    mock({
      'FileA.h': '',
      'FileB.h': '',
      Pods: {
        'FileC.h': '',
      },
      Examples: {
        'FileD.h': '',
      },
      node_modules: {
        'FileE.h': '',
      },
    });

    expect(getHeadersInFolder(process.cwd()).length).to.equals(2);
  });

  afterEach(() => {
    mock.restore();
  });

});


text:
package com.mycompany.cevent.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(name = "websocket")
public class WebSocketConfigProperties {

	private int port;

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

}


text:
package pl.sutkowski.storageconnector.googledrive.authorization;

import com.google.api.client.auth.oauth2.Credential;

public interface GoogleAuthorization {

    Credential authorize();
}


text:
package cmwell.build

import com.github.tkawachi.doctest.DoctestPlugin
import coursier.cache.Cache
import coursier.util.Task
import coursier.{Fetch, Resolve}
//import org.scalafmt.sbt.ScalafmtPlugin
import org.scalastyle.sbt.ScalastylePlugin
import sbtdynver.DynVerPlugin
import coursier.sbtcoursier.CoursierPlugin
import net.virtualvoid.sbt.graph.DependencyGraphPlugin
import sbt.Keys._
import sbt._

import scala.concurrent._
import scala.util.{Failure, Success, Try}

object CMWellBuild extends AutoPlugin {

	type PartialFunction2[-T1,-T2,+R] = PartialFunction[Tuple2[T1,T2],R]

	object autoImport {
//  val configSettingsResource = TaskKey[Seq[sbt.File]]("config-settings-resource", "gets the .conf resource")
		val dependenciesManager = settingKey[PartialFunction2[String, String, ModuleID]]("a setting containing versions for dependencies. if we only use it to declare " +
			"dependencies, we can avoid a lot of version collisions.")
		// scalastyle:off
    val iTestsLightMode = settingKey[Boolean]("a flag, which if turns on, does not take cm-well down after integration tests, but rather purge everything in it, so it will be ready for next time. on startup, it checks if there is an instance running, and if so, does not re-install cm-well.")
		// scalastyle:on
		val peScript = TaskKey[sbt.File]("pe-script", "returns the script that executes cmwell in PE mode.")
		val uploadInitContent = TaskKey[sbt.File]("upload-init-content", "returns the script that uploads the initial content in to PE Cm-Well.")
		val packageCMWell = TaskKey[Seq[java.io.File]]("package-cmwell", "get components from dependencies and sibling projects.")
		val getLib = TaskKey[java.io.File]("get-lib", "creates a lib directory in cmwell-cons/app/ that has all cm-wll jars and their dependency jars.")
		val getCons = TaskKey[java.io.File]("get-cons", "get cons from cons project.")
		val getWs = TaskKey[java.io.File]("get-ws", "get ws from ws project.")
		val getTlog = TaskKey[java.io.File]("get-tlog", "get tlog tool tlog project.")
		val getBg = TaskKey[java.io.File]("get-bg", "get bg from batch project.")
		val getCtrl = TaskKey[java.io.File]("get-ctrl", "get ctrl from ctrl project.")
		val getDc = TaskKey[java.io.File]("get-dc", "get dc from dc project.")
		val getGremlin = TaskKey[java.io.File]("get-gremlin", "get gremlin plugin into cons.")
		val install = TaskKey[Map[Artifact, File]]("install", "build + test, much like 'mvn install'")
		val dataFolder = TaskKey[File]("data-folder", "returns the directory of static data to be uploaded")
		val printDate = TaskKey[Unit]("print-date", "prints the date")
		val fullTest = TaskKey[Unit]("full-test", "executes all tests in project in parallel (with respect to dependent tests)")
		val getData = TaskKey[Seq[java.io.File]]("get-data", "get data to upload to cm-well")
		val getExternalComponents = TaskKey[Iterable[File]]("get-external-components", "get external dependencies binaries")
		val testScalastyle = taskKey[Unit]("testScalastyle")
		val itScalastyle = taskKey[Unit]("itScalastyle")
		val compileScalastyle = taskKey[Unit]("compileScalastyle")
		val versionCheck = taskKey[Unit]("test dyn version task")
	}

	import autoImport._
	import DoctestPlugin.autoImport._
	import coursier.sbtcoursier.CoursierPlugin.autoImport._
//import ScalafmtPlugin.autoImport._
	import ScalastylePlugin.autoImport._
	import DynVerPlugin.autoImport._

	lazy val apacheMirror = {
    val zoneID = java.util.TimeZone
      .getDefault()
      .getID
    if(zoneID.startsWith("America") || zoneID.startsWith("Pacific") || zoneID.startsWith("Etc")) "us"
		else "eu"
  }

	def fetchZookeeperApacheMirror(version: String)(implicit ec: ExecutionContext): Future[File] = {
		val ext = "tar.gz"
		val url = s"http://www-$apacheMirror.apache.org/dist/zookeeper/zookeeper-$version/zookeeper-$version.$ext"
		fetchArtifact(url)
	}

	def fetchZookeeperApacheArchive(version: String)(implicit ec: ExecutionContext): Future[File] = {
		val ext = "tar.gz"
		val url = s"https://archive.apache.org/dist/zookeeper/zookeeper-$version/zookeeper-$version.$ext"
		fetchArtifact(url)
	}

	def fetchZookeeperSourcesFromGithub(version: String, ext: String)(implicit ec: ExecutionContext): Future[File] = {
		require(ext == "zip" || ext == "tar.gz", s"invalid sources extension [$ext]")
		alternateUnvalidatedFetchArtifact(s"https://github.com/apache/zookeeper/archive/release-$version.$ext", ext)
	}

	def fetchZookeeper(version: String, buildFromSources: Option[(String,File => Future[File])] = None) = {
		import scala.concurrent.ExecutionContext.Implicits.global
		import CMWellCommon.combineThrowablesAsCauseAsync

		fetchZookeeperApacheMirror(version).recoverWith {
			case err1: Throwable => fetchZookeeperApacheArchive(version).recoverWith {
				case err2: Throwable => {
					buildFromSources.fold(combineThrowablesAsCauseAsync[File](err1, err2){ cause =>
						new Exception("was unable to fetch zookeeper binaries, and build from sources function isn't supplied", cause)
					}) {
						case (ext, build) => fetchZookeeperSourcesFromGithub(version, ext).flatMap(build)
					}
				}
			}
		}
	}

	def fetchKafkaApacheMirror(scalaVersion: String, version: String)(implicit ec: ExecutionContext): Future[File] = {
		val ext = "tgz"
    val url = s"http://www-$apacheMirror.apache.org/dist/kafka/$version/kafka_$scalaVersion-$version.$ext"
		fetchArtifact(url)
	}

	def fetchKafkaApacheArchive(scalaVersion: String, version: String)(implicit ec: ExecutionContext): Future[File] = {
		val ext = "tgz"
    val url = s"https://archive.apache.org/dist/kafka/$version/kafka_$scalaVersion-$version.$ext"
		fetchArtifact(url)
	}

	def fetchKafkaSourcesFromGithub(version: String, ext: String)(implicit ec: ExecutionContext): Future[File] = {
		require(ext == "zip" || ext == "tar.gz", s"invalid sources extension [$ext]")
		alternateUnvalidatedFetchArtifact(s"https://github.com/apache/kafka/archive/$version.$ext", ext)
	}

  def fetchKafka(scalaVersion: String, version: String, buildFromSources: Option[(String,File => Future[File])] = None) = {
		import scala.concurrent.ExecutionContext.Implicits.global
		import CMWellCommon.combineThrowablesAsCauseAsync

		fetchKafkaApacheMirror(scalaVersion, version).recoverWith {
			case err1: Throwable => fetchKafkaApacheArchive(scalaVersion, version).recoverWith {
				case err2: Throwable => {
					buildFromSources.fold(combineThrowablesAsCauseAsync[File](err1, err2) { cause =>
						new Exception("was unable to fetch kafka binaries, and build from sources function isn't supplied", cause)
					}) {
						case (ext, build) => fetchKafkaSourcesFromGithub(version, ext).flatMap(build)
					}
				}
			}
		}
	}

	def fetchCassandraApacheMirror(version: String, fileName: String)(implicit ec: ExecutionContext): Future[File] = {
    val url = s"http://www-$apacheMirror.apache.org/dist/cassandra/$version/$fileName"
		fetchArtifact(url)
	}

	def fetchCassandraApacheArchive(version: String, fileName: String)(implicit ec: ExecutionContext): Future[File] = {
    val url = s"https://archive.apache.org/dist/cassandra/$version/$fileName"
		fetchArtifact(url)
	}

  def fetchCassandra(version: String, logger: Logger)(implicit ec: ExecutionContext): Future[(String, File)] = {
		val ext = "tar.gz"
		val fileName = s"apache-cassandra-$version-bin.$ext"
		fetchCassandraApacheMirror(version, fileName).recoverWith {
			case ex: Throwable =>
				logger.error(s"Fetching cassandra from the main mirror failed due to ${ex.getMessage} going to fetch it from apache archive.")
				fetchCassandraApacheArchive(version, fileName)
		}
			.map(fileName -> _)
	}

	def fetchElasticSearch(version: String)(implicit ec: ExecutionContext): Future[(String, File)] = {
		val ext = "tar.gz"
		val osType = OsCheck.getOperatingSystemType match {
			case OSType.Linux => "linux"
			case OSType.MacOS => "darwin"
			case other => throw new Exception(s"Operating system $other is not supported")
		}
		val fileName = s"elasticsearch-oss-$version-$osType-x86_64.$ext"
		val url = s"https://artifacts.elastic.co/downloads/elasticsearch/$fileName"
		fetchArtifact(url).map(fileName -> _)
	}

	def fetchArtifact(url: String)(implicit es: ExecutionContext): Future[java.io.File] = {
		import coursier.core.{Artifact, Attributes}
		val sig = Artifact(
			url + ".asc",
			Map.empty,
			Map.empty,
			changing = false,
			optional = false,
			authentication = None
		)

		val art = Artifact(
			url,
			Map(
				"MD5" -> (url + ".md5"),
				"SHA-1" -> (url + ".sha1"),
				"SHA-256" -> (url + ".sha256")
				//SHA-512 is disabled until https://github.com/coursier/coursier/issues/1108 will be fixed
				//(coursier parser doesn't recognize sha512 hash length, see above issue)
				//This means that fetching ES currently doesn't have any checksum check!
				//"SHA-512" -> (url + ".sha512")
			),
			Map("sig" -> sig),
			changing = false,
			optional = false,
			None)

		val checksums = Seq(Some("MD5"),Some("SHA-1"),Some("SHA-256"),Some("SHA-512"), None)
		val fileCache: Cache[Task] = coursier.cache.FileCache().withChecksums(checksums)
		fileCache.file(art).run.future.transform {
			case Success(Left(artifactError)) => Failure(new Exception(artifactError.message + ": " + artifactError.describe))
			case Success(Right(file)) => Success(file)
			case Failure(exception) => Failure(exception)
		}
	}

	def alternateUnvalidatedFetchArtifact(url: String, ext: String)(implicit es: ExecutionContext): Future[java.io.File] = {
		import coursier.core.{Artifact, Attributes}

		val art = Artifact(
			url,
			Map.empty,
			Map.empty,
			changing = false,
			optional = false,
			None)

		coursier.cache.Cache.default.file(art).run.future.transform {
			case Success(Left(artifactError)) => Failure(new Exception(artifactError.message + ": " + artifactError.describe))
			case Success(Right(file)) => Success(file)
			case Failure(exception) => Failure(exception)
		}
	}

	override def requires = CoursierPlugin && ScalastylePlugin /*&& ScalafmtPlugin*/ && DoctestPlugin && DependencyGraphPlugin

	override def projectSettings = Seq(
		scalastyleFailOnError := true,
		testScalastyle in ThisProject := (scalastyle in ThisProject).in(Test).toTask("").value,
		(test in Test) := ((test in Test) dependsOn testScalastyle).value,
		compileScalastyle in ThisProject := (scalastyle in ThisProject).in(Compile).toTask("").value,
		(compile in Compile) := ((compile in Compile) dependsOn compileScalastyle).value,
		(compile in Compile) := ((compile in Compile) dependsOn versionCheck).value,
		logLevel in (scalastyle in Compile) := Level.Warn,
		//scalafmtOnCompile := true,
		//doctestWithDependencies := false,
    coursierMaxIterations := 200,
		Keys.fork in Test := true,
		libraryDependencies ++= {
			val dm = dependenciesManager.value
			Seq(
				dm("org.scalatest","scalatest") % "test",
				dm("org.scalacheck","scalacheck") % "test")
		},
		versionCheck := {
			val dynamicVersion = dynver.value
			val staticVersion = version.value
			if (dynamicVersion != staticVersion)
				sys.error(s"The version setting ($staticVersion) is different from the dynamic (dynver) one ($dynamicVersion). " +
					s"Please use the refreshVersion command to refresh the setting.")
		},
		testListeners := Seq(new sbt.JUnitXmlTestsListener(target.value.getAbsolutePath)),
		doctestTestFramework := DoctestTestFramework.ScalaTest,
		exportJars := true,
		shellPrompt := { s => Project.extract(s).currentProject.id + " > " },
		fullTest := {},
		install in Compile := {
			fullTest.value
			packagedArtifacts.value
		},
		concurrentRestrictions in ThisBuild ++= Seq(
			Tags.limit(CMWellCommon.Tags.ES, 1),
			Tags.limit(CMWellCommon.Tags.Cassandra, 1),
			Tags.limit(CMWellCommon.Tags.Kafka, 1),
			Tags.limit(CMWellCommon.Tags.Grid, 1),
			Tags.exclusive(CMWellCommon.Tags.IntegrationTests)
		)
	)
}


text:
@interface PodsDummy_Pods_Uchat : NSObject
@end
@implementation PodsDummy_Pods_Uchat
@end


text:
<?php

namespace Pablodip\ModuleBundle\Routing;

use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Config\Resource\DirectoryResource;

/**
 * ModuleLoader.
 *
 * Based on the AnnotationDirectoryLoader.
 *
 * @author Pablo Díez <pablodip@gmail.com>
 */
class ModuleDirectoryLoader extends ModuleFileLoader
{
    /**
     * Loads from annotations from a directory.
     *
     * @param string $path A directory path
     * @param string $type The resource type
     *
     * @return RouteCollection A RouteCollection instance
     */
    public function load($path, $type = null)
    {
        $dir = $this->locator->locate($path);

        $collection = new RouteCollection();
        $collection->addResource(new DirectoryResource($dir, '/\.php$/'));
        foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
            if (!$file->isFile() || '.php' !== substr($file->getFilename(), -4)) {
                continue;
            }

            if ($class = $this->findClass($file)) {
                $refl = new \ReflectionClass($class);
                if ($refl->isAbstract() || !$refl->implementsInterface('Pablodip\ModuleBundle\Module\ModuleInterface')) {
                    continue;
                }

                $collection->addCollection(parent::load($file->getRealPath(), $type));
            }
        }

        return $collection;
    }

    /**
     * Returns true if this class supports the given resource.
     *
     * @param mixed  $resource A resource
     * @param string $type     The resource type
     *
     * @return Boolean True if this class supports the given resource, false otherwise
     */
    public function supports($resource, $type = null)
    {
        try {
            $path = $this->locator->locate($resource);
        } catch (\Exception $e) {
            return false;
        }

        return 'module' === $type && is_string($resource) && is_dir($path);
    }
}


text:
package testing;

import testing.rename.C;

class JavaClient {
    public void foo(C c) {
        int n = c.second;
        c.second = 2;
    }
}