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

// Author: Chris Seeley (https://github.com/Narwalter)

using Google.Api.Ads.Common.Util;
using Google.Api.Ads.Dfp.Lib;
using Google.Api.Ads.Dfp.Util.v201408;
using Google.Api.Ads.Dfp.v201408;

using System;

namespace Google.Api.Ads.Dfp.Examples.CSharp.v201408 {
  /// <summary>
  /// This code example gets all content metadata key hierarchies. To create
  /// content metadata key hierarchies, run
  /// CreateContentMetadataKeyHierarchies.cs.
  ///
  /// Tags: ContentMetadataKeyHierarchyService.getContentMetadataKeyHierarchiesByStatement
  /// </summary>
  class GetAllContentMetadataKeyHierarchies : SampleBase {
    /// <summary>
    /// Returns a description about the code example.
    /// </summary>
    public override string Description {
      get {
        return "This code example gets all content metadata key hierarchies. To create " +
            "content metadata key hierarchies, run CreateContentMetadataKeyHierarchies.cs.";
      }
    }

    /// <summary>
    /// Main method, to run this code example as a standalone application.
    /// </summary>
    /// <param name="args">The command line arguments.</param>
    public static void Main(string[] args) {
      SampleBase codeExample = new GetAllContentMetadataKeyHierarchies();
      Console.WriteLine(codeExample.Description);
      codeExample.Run(new DfpUser());
    }

    /// <summary>
    /// Run the code example.
    /// </summary>
    /// <param name="user">The DFP user object running the code example.</param>
    public override void Run(DfpUser user) {
      // Get the ContentMetadataKeyHierarchy service.
      ContentMetadataKeyHierarchyService contentMetadataKeyHierarchyService =
          (ContentMetadataKeyHierarchyService) user.GetService(
           DfpService.v201408.ContentMetadataKeyHierarchyService);

      // Create a statement to get all content metadata key hierarchies
      StatementBuilder statementBuilder = new StatementBuilder()
        .OrderBy("id ASC")
        .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT);

      try {
        int totalResultSetSize = 0;
        do {
          // Get content metadata key hierarchies by statement.
          ContentMetadataKeyHierarchyPage page = contentMetadataKeyHierarchyService
              .getContentMetadataKeyHierarchiesByStatement(statementBuilder.ToStatement());

          if (page.results != null) {
            totalResultSetSize = page.totalResultSetSize;
            int i = page.startIndex;
            foreach (ContentMetadataKeyHierarchy contentMetadataKeyHierarchy in page.results) {
              Console.WriteLine("{0}) Content metadata key hierarchy with ID \"{1}\", " +
                  "and name \"{2}\" was found.", i++, contentMetadataKeyHierarchy.id,
                  contentMetadataKeyHierarchy.name);
            }
          }

          statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
        } while (statementBuilder.GetOffset() < totalResultSetSize);
        Console.WriteLine("Number of results found: {0}", totalResultSetSize);
      } catch (Exception ex) {
        Console.WriteLine("Failed to get content metadata key hierarchies. Exception " +
            "says \"{0}\"", ex.Message);
      }
    }
  }
}


text:
package dev.chromeos.lowlatencystylusdemo.cpu;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.util.SparseArray;
import android.view.MotionEvent;
import androidx.annotation.NonNull;
import com.google.chromeos.lowlatencystylus.BatchedMotionEvent;
import com.google.chromeos.lowlatencystylus.InkDelegate;
import java.util.ArrayList;
import java.util.List;

/** A Gesture represents a set of MotionEvents between ACTION_DOWN to ACTION_UP. */
public class Gesture {
    // List of received events
    private final List<PaintedEvent> paintedEvents = new ArrayList<>();

    /**
     * Adds a MotionEvent to Gesture. The MotionEvent will be copied, therefore {@code clear()} or
     * {@code clearButRetainLast()} should be explicitly called to recycle them.
     *
     * @param event added MotionEvent
     */
    public void add(MotionEvent event, Paint paint) {
        paintedEvents.add(new PaintedEvent(MotionEvent.obtain(event), paint));
    }

    /** Clears all the MotionEvents. It calls {@code recycle()} of all the MotionEvents. */
    public void clear() {
        for (PaintedEvent gesture : paintedEvents) {
            gesture.event.recycle();
        }
        paintedEvents.clear();
    }

    /** Clears all the MotionEvents except the last one. */
    public void clearButRetainLast() {
        if (paintedEvents.isEmpty()) {
            return;
        }
        PaintedEvent last = paintedEvents.get(paintedEvents.size() - 1);
        for (int i = 0; i < paintedEvents.size() - 1; i++) {
            paintedEvents.get(i).event.recycle();
        }
        paintedEvents.clear();
        paintedEvents.add(last);
    }

    /**
     * Draws the lines defined by the consecutive MotionEvents.
     *
     * @param canvas the lines are drawn to
     * @return the damage {@link Rect}
     */
    @NonNull
    public Rect draw(@NonNull Canvas canvas) {
        Rect damageRect = new Rect();
        SparseArray<Path> paths = new SparseArray<>();
        for (PaintedEvent gesture : paintedEvents) {
            for (int i = 0; i < gesture.event.getPointerCount(); i++) {
                final int id = gesture.event.getPointerId(i);
                Path path = paths.get(id);
                if (path == null) {
                    path = new Path();
                    paths.put(id, path);
                }
                for (BatchedMotionEvent motionEvent : BatchedMotionEvent.iterate(gesture.event)) {
                    float x = motionEvent.getCoords()[i].x;
                    float y = motionEvent.getCoords()[i].y;
                    if (path.isEmpty()) {
                        path.moveTo(x, y);
                    } else {
                        path.lineTo(x, y);
                    }
                    InkDelegate.unionRect(damageRect, x, y, gesture.paint.getStrokeWidth());
                }
            }
        }
        for (int i = 0; i < paths.size(); i++) {
            if (paintedEvents.size() > i) {
                canvas.drawPath(paths.valueAt(i), paintedEvents.get(i).paint);
            }
        }
        paths.clear();
        return damageRect;
    }

    /**
     * Draws the lines defined by {@code event}. Same as creating a new {@link Gesture} object with
     * {@code event} and calling the {@code draw()} method.
     *
     * @param canvas the lines are drawn to
     * @param paint style of the lines
     * @param event predicted MotionEvent
     * @return the damage {@link Rect}
     */
    @NonNull
    public static Rect drawMotionEvent(
            @NonNull Canvas canvas, @NonNull Paint paint, @NonNull MotionEvent event) {
        Gesture gesture = new Gesture();
        // As the gesture object is temporary, do not obtain() the event.
        gesture.paintedEvents.add(new PaintedEvent(event, paint));
        return gesture.draw(canvas);
    }

    // Convenience class to hold a motion event and a paint
    private static class PaintedEvent {
        MotionEvent event;
        Paint paint;

        public PaintedEvent(MotionEvent event, Paint paint) {
            this.event = event;
            this.paint = paint;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    android:id="@+id/framelayout_main"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/linearlayout_loading"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical"
        android:visibility="gone">

        <ProgressBar
            android:id="@+id/progressbar_loading"
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

        <TextView
            android:id="@+id/textview_loading"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:text="@string/default_progress_message"/>
    </LinearLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerview_history"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</FrameLayout>


text:
package be.testing;

import be.stilkin.StartingHands;
import poker.Card;

/**
 * This class contains a main method. Do not include when packing bot.
 * @author stilkin
 *
 */
public class StartingHandsTest {

    public static void main(String[] args) {

	System.out.println("" + StartingHands.getOdds(new Card(12), new Card(8)));
	System.out.println("" + StartingHands.getOdds("TA="));

    }

}


text:
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<items>
  <item>
    <name>Warcraft marathon</name>
    <description>Still missing a few books though.</description>
  </item>
  <item>
    <name>Song of Ice and Fire: Game of Thrones</name>
    <description>First book, much more awesome than series.</description>
  </item>
</items>


text:
<ion-side-menus enable-menu-with-back-views="false">
<ion-side-menu-content>
<ion-nav-bar class="bar-stable">
<ion-nav-back-button>
</ion-nav-back-button>

<ion-nav-buttons side="left">
<button class="button button-icon button-clear ion-navicon" menu-toggle="left">
</button>
</ion-nav-buttons>
</ion-nav-bar>
<ion-nav-view name="menuContent"></ion-nav-view>
</ion-side-menu-content>

<ion-side-menu side="left">
<ion-header-bar class="bar-stable">

Menu

</ion-header-bar>
<ion-content>
<ion-list>
<ion-item menu-close href="#/app/index">
Inicio
</ion-item>
<ion-item menu-close href="#/app/pintar">
Pintura libre
</ion-item>
<ion-item menu-close href="#/app/mezclador">
Mezclador
</ion-item>
</ion-list>
</ion-content>
</ion-side-menu>
</ion-side-menus>


text:
package com.tectonica.jonix.onix2;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.tectonica.jonix.JPU;
import com.tectonica.jonix.OnixComposite.OnixSuperComposite;
import com.tectonica.jonix.codelist.LanguageCodes;
import com.tectonica.jonix.codelist.PersonNameIdentifierTypes;
import com.tectonica.jonix.codelist.PersonOrganizationNameTypes;
import com.tectonica.jonix.codelist.RecordSourceTypes;
import com.tectonica.jonix.codelist.TextCaseFlags;
import com.tectonica.jonix.codelist.TextFormats;
import com.tectonica.jonix.codelist.TransliterationSchemes;
import com.tectonica.jonix.struct.JonixPersonNameIdentifier;

/*
 * NOTE: THIS IS AN AUTO-GENERATED FILE, DON'T EDIT MANUALLY
 */

@SuppressWarnings("serial")
public class Name implements OnixSuperComposite, Serializable
{
	public static final String refname = "Name";
	public static final String shortname = "name";

	public TextFormats textformat;

	public TextCaseFlags textcase;

	public LanguageCodes language;

	public TransliterationSchemes transliteration;

	/**
	 * (type: DateOrDateTime)
	 */
	public String datestamp;

	public RecordSourceTypes sourcetype;

	public String sourcename;

	/**
	 * (this field is required)
	 */
	public PersonNameType personNameType;

	/**
	 * (this field is required)
	 */
	public PersonName personName;

	/**
	 * (this field is optional)
	 */
	public PersonNameInverted personNameInverted;

	/**
	 * (this field is optional)
	 */
	public TitlesBeforeNames titlesBeforeNames;

	/**
	 * (this field is optional)
	 */
	public NamesBeforeKey namesBeforeKey;

	/**
	 * (this field is optional)
	 */
	public PrefixToKey prefixToKey;

	/**
	 * (this field is optional)
	 */
	public KeyNames keyNames;

	/**
	 * (this field is optional)
	 */
	public NamesAfterKey namesAfterKey;

	/**
	 * (this field is optional)
	 */
	public SuffixToKey suffixToKey;

	/**
	 * (this field is optional)
	 */
	public LettersAfterNames lettersAfterNames;

	/**
	 * (this field is optional)
	 */
	public TitlesAfterNames titlesAfterNames;

	/**
	 * (this list may be empty)
	 */
	public List<PersonNameIdentifier> personNameIdentifiers;

	public Name()
	{}

	public Name(org.w3c.dom.Element element)
	{
		textformat = TextFormats.byValue(JPU.getAttribute(element, "textformat"));
		textcase = TextCaseFlags.byValue(JPU.getAttribute(element, "textcase"));
		language = LanguageCodes.byValue(JPU.getAttribute(element, "language"));
		transliteration = TransliterationSchemes.byValue(JPU.getAttribute(element, "transliteration"));
		datestamp = JPU.getAttribute(element, "datestamp");
		sourcetype = RecordSourceTypes.byValue(JPU.getAttribute(element, "sourcetype"));
		sourcename = JPU.getAttribute(element, "sourcename");

		JPU.forElementsOf(element, new JPU.ElementListener()
		{
			@Override
			public void onElement(org.w3c.dom.Element element)
			{
				final String name = element.getNodeName();
				if (name.equals(PersonNameType.refname) || name.equals(PersonNameType.shortname))
					personNameType = new PersonNameType(element);
				else if (name.equals(PersonName.refname) || name.equals(PersonName.shortname))
					personName = new PersonName(element);
				else if (name.equals(PersonNameInverted.refname) || name.equals(PersonNameInverted.shortname))
					personNameInverted = new PersonNameInverted(element);
				else if (name.equals(TitlesBeforeNames.refname) || name.equals(TitlesBeforeNames.shortname))
					titlesBeforeNames = new TitlesBeforeNames(element);
				else if (name.equals(NamesBeforeKey.refname) || name.equals(NamesBeforeKey.shortname))
					namesBeforeKey = new NamesBeforeKey(element);
				else if (name.equals(PrefixToKey.refname) || name.equals(PrefixToKey.shortname))
					prefixToKey = new PrefixToKey(element);
				else if (name.equals(KeyNames.refname) || name.equals(KeyNames.shortname))
					keyNames = new KeyNames(element);
				else if (name.equals(NamesAfterKey.refname) || name.equals(NamesAfterKey.shortname))
					namesAfterKey = new NamesAfterKey(element);
				else if (name.equals(SuffixToKey.refname) || name.equals(SuffixToKey.shortname))
					suffixToKey = new SuffixToKey(element);
				else if (name.equals(LettersAfterNames.refname) || name.equals(LettersAfterNames.shortname))
					lettersAfterNames = new LettersAfterNames(element);
				else if (name.equals(TitlesAfterNames.refname) || name.equals(TitlesAfterNames.shortname))
					titlesAfterNames = new TitlesAfterNames(element);
				else if (name.equals(PersonNameIdentifier.refname) || name.equals(PersonNameIdentifier.shortname))
					personNameIdentifiers = JPU.addToList(personNameIdentifiers, new PersonNameIdentifier(element));
			}
		});
	}

	public PersonOrganizationNameTypes getPersonNameTypeValue()
	{
		return (personNameType == null) ? null : personNameType.value;
	}

	public String getPersonNameValue()
	{
		return (personName == null) ? null : personName.value;
	}

	public String getPersonNameInvertedValue()
	{
		return (personNameInverted == null) ? null : personNameInverted.value;
	}

	public String getTitlesBeforeNamesValue()
	{
		return (titlesBeforeNames == null) ? null : titlesBeforeNames.value;
	}

	public String getNamesBeforeKeyValue()
	{
		return (namesBeforeKey == null) ? null : namesBeforeKey.value;
	}

	public String getPrefixToKeyValue()
	{
		return (prefixToKey == null) ? null : prefixToKey.value;
	}

	public String getKeyNamesValue()
	{
		return (keyNames == null) ? null : keyNames.value;
	}

	public String getNamesAfterKeyValue()
	{
		return (namesAfterKey == null) ? null : namesAfterKey.value;
	}

	public String getSuffixToKeyValue()
	{
		return (suffixToKey == null) ? null : suffixToKey.value;
	}

	public String getLettersAfterNamesValue()
	{
		return (lettersAfterNames == null) ? null : lettersAfterNames.value;
	}

	public String getTitlesAfterNamesValue()
	{
		return (titlesAfterNames == null) ? null : titlesAfterNames.value;
	}

	public JonixPersonNameIdentifier findPersonNameIdentifier(PersonNameIdentifierTypes personNameIDType)
	{
		if (personNameIdentifiers != null)
		{
			for (PersonNameIdentifier x : personNameIdentifiers)
			{
				if (x.getPersonNameIDTypeValue() == personNameIDType)
					return x.asJonixPersonNameIdentifier();
			}
		}
		return null;
	}

	public List<JonixPersonNameIdentifier> findPersonNameIdentifiers(
			java.util.Set<PersonNameIdentifierTypes> personNameIDTypes)
	{
		if (personNameIdentifiers != null)
		{
			List<JonixPersonNameIdentifier> matches = new ArrayList<>();
			for (PersonNameIdentifier x : personNameIdentifiers)
			{
				if (personNameIDTypes == null || personNameIDTypes.contains(x.getPersonNameIDTypeValue()))
					matches.add(x.asJonixPersonNameIdentifier());
			}
			return matches;
		}
		return null;
	}
}


text:
<?php

session_start();
 include("header.php");
session_destroy();
?>

Student Information System.

Logged Out Successfully...

You will be redirecting to Login page...

<?php
header( "refresh:3;url=admin.php" );

?>

<?php include("footer.php"); ?>


text:
<?xml version="1.0" encoding="utf-8"?>
<sync-adapter
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:contentAuthority="media"
    android:accountType="org.savemypics.android.account"
    android:userVisible="true"
    android:supportsUploading="true"/>


text:
package com.hwh.test;

import static org.junit.Assert.*;

import java.util.List;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.hwh.dao.BookDAO;
import com.hwh.dao.ManagerDAO;
import com.hwh.dao.impl.ManagerDAOImpl;
import com.hwh.model.Bookinfo;
import com.hwh.model.Manager;
import com.hwh.model.Purview;

public class MangerDAOImplTest {

	@Test
	public void test() {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				"applicationContext.xml");
		//ManagerDAO mngDAO = context.getBean("managerDAOImpl", ManagerDAO.class);
		BookDAO bookDAO = context.getBean("bookDAOImpl", BookDAO.class);
		List<Bookinfo> bookinfos=bookDAO.bookQuery();
		System.out.println(bookinfos.get(0).getBookcase().getColumn());

/*		Manager manager=new Manager();
		manager.setName("adcd");
		manager.setPassword("111");
		mngDAO.managerAdd(manager);
		*/
		//mngDAO.managerDel(id);
/*		Manager mng=mngDAO.getManager(manager);
		//Purview purview=mngDAO.getPurview(mng);
		System.out.println(mng.getPurview().getId());
		System.out.println(mng.getPurview().getBookset());
		System.out.println(mng);

		mngDAO.managerDel(6);
		int sz=mngDAO.managerQuery().size();
		System.out.println("size= "+sz);
		*/
	}

}


text:
require 'spec_helper'

describe Batchbook::Client do
  subject { Batchbook::Client.new }
  let(:user) { 'https://ramon.batchbook.com'}
  let(:token) { '12345abcde'}
  let(:client) { Batchbook::Client.new(user, token)}
  let(:bad_token) { '12345abcd'}
  let(:bad_client) { Batchbook::Client.new(user,bad_token)}

  describe '#initialize' do
    it 'stores the user and token' do
      expect(client.user).to eq(user)
      expect(client.token).to eq(token)
    end
  end

  describe '#ping' do
    context 'good token' do
      it 'returns true' do
        response = client.ping
        expect(response).to be_truthy
      end
    end

    context 'bad_token' do
      it 'returns false' do
        response = bad_client.ping
        expect(response).to be_falsey
      end
    end
  end

  describe '#people' do
    it 'returns the collection of people' do
      response = client.people
      expect(response['page']).to eq(1)
      expect(response['people'].size).to eq(30)
    end

    context 'wrong token' do
      it "returns an error message" do
        response = bad_client.people
        expect(response['error']).to eq('Invalid authentication token.')
      end
    end
  end

  describe '#users' do
    it 'return the collection of users' do
      response = client.users
      expect(response.has_key?('users')).to be_truthy
    end

    context 'wrong token' do
      it "returns an error message" do
        response = bad_client.users
        expect(response['error']).to eq('Invalid authentication token.')
      end
    end
  end

  describe '#custom_field_sets' do
    it 'returns the collection of custom fields' do
      response = client.custom_field_sets
      expect(response.has_key?('custom_field_sets')).to be_truthy
    end

    context 'wrong token' do
      it "returns an error message" do
        response = bad_client.custom_field_sets
        expect(response['error']).to eq('Invalid authentication token.')
      end
    end
  end
end


text:
package com.google.javascript.jscomp;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.javascript.jscomp.CompilerTestCase.lines;
import static com.google.javascript.jscomp.parsing.Config.JsDocParsing.INCLUDE_DESCRIPTIONS_NO_WHITESPACE;
import static com.google.javascript.rhino.testing.NodeSubject.assertNode;
import static com.google.javascript.rhino.testing.TypeSubject.assertType;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Ordering;
import com.google.common.testing.EqualsTester;
import com.google.javascript.jscomp.CompilerOptions.LanguageMode;
import com.google.javascript.jscomp.SymbolTable.Reference;
import com.google.javascript.jscomp.SymbolTable.Symbol;
import com.google.javascript.jscomp.SymbolTable.SymbolScope;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.JSDocInfo.Visibility;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import com.google.javascript.rhino.jstype.FunctionType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * An integration test for symbol table creation
 *
 * @author nicksantos@google.com (Nick Santos)
 */

@RunWith(JUnit4.class)
public final class SymbolTableTest {

  private static final String EXTERNS =
      CompilerTypeTestCase.DEFAULT_EXTERNS
          + "var Number;"
          + "\nfunction customExternFn(customExternArg) {}";

  private CompilerOptions options;

  @Before
  public void setUp() throws Exception {

    options = new CompilerOptions();
    options.setLanguageIn(LanguageMode.ECMASCRIPT_2017);
    options.setLanguageOut(LanguageMode.ECMASCRIPT5);
    options.setCodingConvention(new ClosureCodingConvention());
    CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(options);
    WarningLevel.VERBOSE.setOptionsForWarningLevel(options);
    options.setChecksOnly(true);
    options.setPreserveDetailedSourceInfo(true);
    options.setContinueAfterErrors(true);
    options.setAllowHotswapReplaceScript(true);
    options.setParseJsDocDocumentation(INCLUDE_DESCRIPTIONS_NO_WHITESPACE);
  }

  /**
   * Make sure rewrite of super() call containing a function literal doesn't cause the SymbolTable
   * to crash.
   */
  @Test
  public void testFunctionInCall() {
    createSymbolTable(
        lines(
            "class Y { constructor(fn) {} }",
            "class X extends Y {",
            "  constructor() {",
            "    super(function() {});",
            "  }",
            "}"));
  }

  @Test
  public void testGlobalVar() {
    SymbolTable table = createSymbolTable("/** @type {number} */ var x = 5;");
    assertThat(getGlobalVar(table, "y")).isNull();
    assertThat(getGlobalVar(table, "x")).isNotNull();
    assertThat(getGlobalVar(table, "x").getType().toString()).isEqualTo("number");

    // 2 == sizeof({x, *global*})
    assertThat(getVars(table)).hasSize(2);
  }

  @Test
  public void testGlobalThisReferences() {
    SymbolTable table =
        createSymbolTable(
            "var x = this; function f() { return this + this + this; }", /* externsCode= */ "");

    Symbol global = getGlobalVar(table, "*global*");
    assertThat(global).isNotNull();

    List<Reference> refs = table.getReferenceList(global);
    assertThat(refs).hasSize(1);
  }

  @Test
  public void testGlobalThisReferences2() {
    // Make sure the global this is declared, even if it isn't referenced.
    SymbolTable table = createSymbolTable("", /* externsCode= */ "");

    Symbol global = getGlobalVar(table, "*global*");
    assertThat(global).isNotNull();

    List<Reference> refs = table.getReferenceList(global);
    assertThat(refs).isEmpty();
  }

  @Test
  public void testGlobalThisReferences3() {
    SymbolTable table =
        createSymbolTable("this.foo = {}; this.foo.bar = {};", /* externsCode= */ "");

    Symbol global = getGlobalVar(table, "*global*");
    assertThat(global).isNotNull();

    List<Reference> refs = table.getReferenceList(global);
    assertThat(refs).hasSize(2);
  }

  @Test
  public void testGlobalThisPropertyReferences() {
    SymbolTable table = createSymbolTable("/** @constructor */ function Foo() {} this.Foo;");

    Symbol foo = getGlobalVar(table, "Foo");
    assertThat(foo).isNotNull();

    List<Reference> refs = table.getReferenceList(foo);
    assertThat(refs).hasSize(2);
  }

  @Test
  public void testGlobalVarReferences() {
    SymbolTable table = createSymbolTable("/** @type {number} */ var x = 5; x = 6;");
    Symbol x = getGlobalVar(table, "x");
    List<Reference> refs = table.getReferenceList(x);

    assertThat(refs).hasSize(2);
    assertThat(refs.get(0)).isEqualTo(x.getDeclaration());
    assertThat(refs.get(0).getNode().getParent().getToken()).isEqualTo(Token.VAR);
    assertThat(refs.get(1).getNode().getParent().getToken()).isEqualTo(Token.ASSIGN);
  }

  @Test
  public void testLocalVarReferences() {
    SymbolTable table = createSymbolTable("function f(x) { return x; }");
    Symbol x = getLocalVar(table, "x");
    List<Reference> refs = table.getReferenceList(x);

    assertThat(refs).hasSize(2);
    assertThat(refs.get(0)).isEqualTo(x.getDeclaration());
    assertThat(refs.get(0).getNode().getParent().getToken()).isEqualTo(Token.PARAM_LIST);
    assertThat(refs.get(1).getNode().getParent().getToken()).isEqualTo(Token.RETURN);
  }

  @Test
  public void testLocalThisReferences() {
    SymbolTable table =
        createSymbolTable("/** @constructor */ function F() { this.foo = 3; this.bar = 5; }");

    Symbol f = getGlobalVar(table, "F");
    assertThat(f).isNotNull();

    Symbol t = table.getParameterInFunction(f, "this");
    assertThat(t).isNotNull();

    List<Reference> refs = table.getReferenceList(t);
    assertThat(refs).hasSize(2);
  }

  @Test
  public void testLocalThisReferences2() {
    SymbolTable table =
        createSymbolTable(
            lines(
                "/** @constructor */ function F() {}",
                "F.prototype.baz = function() { this.foo = 3; this.bar = 5; };"));

    Symbol baz = getGlobalVar(table, "F.prototype.baz");
    assertThat(baz).isNotNull();

    Symbol t = table.getParameterInFunction(baz, "this");
    assertThat(t).isNotNull();

    List<Reference> refs = table.getReferenceList(t);
    assertThat(refs).hasSize(2);
  }

  // No 'this' reference is created for empty functions.
  @Test
  public void testLocalThisReferences3() {
    SymbolTable table = createSymbolTable("/** @constructor */ function F() {}");

    Symbol baz = getGlobalVar(table, "F");
    assertThat(baz).isNotNull();

    Symbol t = table.getParameterInFunction(baz, "this");
    assertThat(t).isNull();
  }

  @Test
  public void testObjectLiteral() {
    SymbolTable table = createSymbolTable("var obj = {foo: 0};");

    Symbol foo = getGlobalVar(table, "obj.foo");
    assertThat(foo.getName()).isEqualTo("foo");
  }

  @Test
  public void testObjectLiteralQuoted() {
    SymbolTable table = createSymbolTable("var obj = {'foo': 0};");

    // Quoted keys are not symbols.
    assertThat(getGlobalVar(table, "obj.foo")).isNull();
    // Only obj and *global* are symbols.
    assertThat(getVars(table)).hasSize(2);
  }

  @Test
  public void testObjectLiteralWithMemberFunction() {
    String input = lines("var obj = { fn() {} }; obj.fn();");
    SymbolTable table = createSymbolTable(input);

    Symbol objFn = getGlobalVar(table, "obj.fn");
    assertThat(objFn).isNotNull();
    List<Reference> references = table.getReferenceList(objFn);
    assertThat(references).hasSize(2);

    // The declaration node corresponds to "fn", not "fn() {}", in the source info.
    Node declaration = objFn.getDeclarationNode();
    assertThat(declaration.getCharno()).isEqualTo(12);
    assertThat(declaration.getLength()).isEqualTo(2);
  }

  @Test
  public void testNamespacedReferences() {
    // Because the type of goog is anonymous, we build its properties into
    // the global scope.
    SymbolTable table =
        createSymbolTable(
            lines("var goog = {};", "goog.dom = {};", "goog.dom.DomHelper = function(){};"));

    Symbol goog = getGlobalVar(table, "goog");
    assertThat(goog).isNotNull();
    assertThat(table.getReferences(goog)).hasSize(3);

    Symbol googDom = getGlobalVar(table, "goog.dom");
    assertThat(googDom).isNotNull();
    assertThat(table.getReferences(googDom)).hasSize(2);

    Symbol googDomHelper = getGlobalVar(table, "goog.dom.DomHelper");
    assertThat(googDomHelper).isNotNull();
    assertThat(table.getReferences(googDomHelper)).hasSize(1);
  }

  @Test
  public void testIncompleteNamespacedReferences() {
    SymbolTable table =
        createSymbolTable(
            lines(
                "/** @constructor */",
                "goog.dom.DomHelper = function(){};",
                "var y = goog.dom.DomHelper;"));
    Symbol goog = getGlobalVar(table, "goog");
    assertThat(goog).isNotNull();
    assertThat(table.getReferenceList(goog)).hasSize(2);

    Symbol googDom = getGlobalVar(table, "goog.dom");
    assertThat(googDom).isNotNull();
    assertThat(table.getReferenceList(googDom)).hasSize(2);

    Symbol googDomHelper = getGlobalVar(table, "goog.dom.DomHelper");
    assertThat(googDomHelper).isNotNull();
    assertThat(table.getReferences(googDomHelper)).hasSize(2);
  }

  @Test
  public void testGlobalRichObjectReference() {
    SymbolTable table =
        createSymbolTable(
            lines(
                "/** @constructor */",
                "function A(){};",
                "/** @type {?A} */ A.prototype.b;",
                "/** @type {A} */ var a = new A();",
                "function g() {",
                "  return a.b ? 'x' : 'y';",
                "}",
                "(function() {",
                "  var x; if (x) { x = a.b.b; } else { x = a.b.c; }",
                "  return x;",
                "})();"));

    Symbol ab = getGlobalVar(table, "a.b");
    assertThat(ab).isNull();

    Symbol propB = getGlobalVar(table, "A.prototype.b");
    assertThat(propB).isNotNull();
    assertThat(table.getReferenceList(propB)).hasSize(5);
  }

  @Test
  public void testRemovalOfNamespacedReferencesOfProperties() {
    SymbolTable table =
        createSymbolTable(
            lines(
                "/** @constructor */ var DomHelper = function(){};",
                "/** method */ DomHelper.method = function() {};"));

    Symbol domHelper = getGlobalVar(table, "DomHelper");
    assertThat(domHelper).isNotNull();

    Symbol domHelperNamespacedMethod = getGlobalVar(table, "DomHelper.method");
    assertThat(domHelperNamespacedMethod.getName()).isEqualTo("method");

    Symbol domHelperMethod = domHelper.getPropertyScope().getSlot("method");
    assertThat(domHelperMethod).isNotNull();
  }

  @Test
  public void testGoogScopeReferences() {
    SymbolTable table =
        createSymbolTable(
            lines("var goog = {};", "goog.scope = function() {};", "goog.scope(function() {});"));

    Symbol googScope = getGlobalVar(table, "goog.scope");
    assertThat(googScope).isNotNull();
    assertThat(table.getReferences(googScope)).hasSize(2);
  }

  @Test
  public void testGoogRequireReferences() {
    SymbolTable table =
        createSymbolTable(
            lines(
                "var goog = {};",
                "goog.provide = function() {};",
                "goog.require = function() {};",
                "goog.provide('goog.dom');",
                "goog.require('goog.dom');"));
    Symbol goog = getGlobalVar(table, "goog");
    assertThat(goog).isNotNull();

    // 8 references:
    // 5 in code
    // 2 in strings
    // 1 created by ProcessClosurePrimitives when it processes the provide.
    //
    // NOTE(nicksantos): In the future, we may de-dupe references such
    // that the one in the goog.provide string and the one created by
    // ProcessClosurePrimitives count as the same reference.
    assertThat(table.getReferences(goog)).hasSize(8);
  }

  @Test
  public void testGoogRequireReferences2() {
    options.setBrokenClosureRequiresLevel(CheckLevel.OFF);
    SymbolTable table =
        createSymbolTable(
            lines("foo.bar = function(){};  // definition", "goog.require('foo.bar')"));
    Symbol fooBar = getGlobalVar(table, "foo.bar");
    assertThat(fooBar).isNotNull();
    assertThat(table.getReferences(fooBar)).hasSize(2);
  }

  @Test
  public void testGlobalVarInExterns() {
    SymbolTable table = createSymbolTable("customExternFn(1);");
    Symbol fn = getGlobalVar(table, "customExternFn");
    List<Reference> refs = table.getReferenceList(fn);
    assertThat(refs).hasSize(3);

    SymbolScope scope = table.getEnclosingScope(refs.get(0).getNode());
    assertThat(scope.isGlobalScope()).isTrue();
    assertThat(table.getSymbolForScope(scope).getName()).isEqualTo(SymbolTable.GLOBAL_THIS);
  }

  @Test
  public void testLocalVarInExterns() {
    SymbolTable table = createSymbolTable("");
    Symbol arg = getLocalVar(table, "customExternArg");
    List<Reference> refs = table.getReferenceList(arg);
    assertThat(refs).hasSize(1);

    Symbol fn = getGlobalVar(table, "customExternFn");
    SymbolScope scope = table.getEnclosingScope(refs.get(0).getNode());
    assertThat(scope.isGlobalScope()).isFalse();
    assertThat(table.getSymbolForScope(scope)).isEqualTo(fn);
  }

  @Test
  public void testSymbolsForType() {
    SymbolTable table =
        createSymbolTable(
            lines(
                "function random() { return 1; }",
                "/** @constructor */ function Foo() {}",
                "/** @constructor */ function Bar() {}",
                "var x = random() ? new Foo() : new Bar();"));

    Symbol x = getGlobalVar(table, "x");
    Symbol foo = getGlobalVar(table, "Foo");
    Symbol bar = getGlobalVar(table, "Bar");
    Symbol fooPrototype = getGlobalVar(table, "Foo.prototype");
    Symbol fn = getGlobalVar(table, "Function");
    assertThat(table.getAllSymbolsForTypeOf(x)).containsExactly(foo, bar);
    assertThat(table.getAllSymbolsForTypeOf(foo)).containsExactly(fn);
    assertThat(table.getAllSymbolsForTypeOf(fooPrototype)).containsExactly(foo);
    assertThat(table.getSymbolDeclaredBy(foo.getType().toMaybeFunctionType())).isEqualTo(foo);
  }

  @Test
  public void testStaticMethodReferences() {
    SymbolTable table =
        createSymbolTable(
            lines(
                "/** @constructor */ var DomHelper = function(){};",
                "/** method */ DomHelper.method = function() {};",
                "function f() { var x = DomHelper; x.method() + x.method(); }"));

    Symbol method = getGlobalVar(table, "DomHelper").getPropertyScope().getSlot("method");
    assertThat(table.getReferences(method)).hasSize(3);
  }

  @Test
  public void testMethodReferences() {
    SymbolTable table =
        createSymbolTable(
            lines(
                "/** @constructor */ var DomHelper = function(){};",
                "/** method */ DomHelper.prototype.method = function() {};",
                "function f() { ",
                "  (new DomHelper()).method(); (new DomHelper()).method(); };"));

    Symbol method = getGlobalVar(table, "DomHelper.prototype.method");
    assertThat(table.getReferences(method)).hasSize(3);
  }

  @Test
  public void testSuperClassMethodReferences() {
    SymbolTable table =
        createSymbolTable(
            lines(
                "var goog = {};",
                "goog.inherits = function(a, b) {};",
                "/** @constructor */ var A = function(){};",
                "/** method */ A.prototype.method = function() {};",
                "/**",
                " * @constructor",
                " * @extends {A}",
                " */",
                "var B = function(){};",
                "goog.inherits(B, A);",
                "/** method */ B.prototype.method = function() {",
                "  B.superClass_.method();",
                "};"));

    Symbol methodA = getGlobalVar(table, "A.prototype.method");
    assertThat(table.getReferences(methodA)).hasSize(2);
  }

  @Test
  public void testMethodReferencesMissingTypeInfo() {
    SymbolTable table =
        createSymbolTable(
            lines(
                "/**",
                " * @constructor",
                " * @extends {Missing}",
                " */ var DomHelper = function(){};",
                "/** method */ DomHelper.prototype.method = function() {",
                "  this.method();",
                "};",
                "function f() { ",
                "  (new DomHelper()).method();",
                "};"));

    Symbol method = getGlobalVar(table, "DomHelper.prototype.method");
    assertThat(table.getReferences(method)).hasSize(3);
  }

  @Test
  public void testFieldReferencesMissingTypeInfo() {
    SymbolTable table =
        createSymbolTable(
            lines(
                "/**",
                " * @constructor",
                " * @extends {Missing}",
                " */ var DomHelper = function(){ this.prop = 1; };",
                "/** @type {number} */ DomHelper.prototype.prop = 2;",
                "function f() {",
                "  return (new DomHelper()).prop;",
                "};"));

    Symbol prop = getGlobalVar(table, "DomHelper.prototype.prop");
    assertThat(table.getReferenceList(prop)).hasSize(3);

    assertThat(getLocalVar(table, "this.prop")).isNull();
  }

  @Test
  public void testFieldReferences() {
    SymbolTable table =
        createSymbolTable(
            lines(
                "/** @constructor */ var DomHelper = function(){",
                "  /** @type {number} */ this.field = 3;",
                "};",
                "function f() { ",
                "  return (new DomHelper()).field + (new DomHelper()).field; };"));

    Symbol field = getGlobalVar(table, "DomHelper.prototype.field");
    assertThat(table.getReferences(field)).hasSize(3);
  }

  @Test
  public void testUndeclaredFieldReferences() {
    // We do not currently create symbol table entries for undeclared fields,
    // but this may change in the future.
    SymbolTable table =
        createSymbolTable(
            lines(
                "/** @constructor */ var DomHelper = function(){};",
                "DomHelper.prototype.method = function() { ",
                "  this.field = 3;",
                "  return x.field;",
                "}"));

    Symbol field = getGlobalVar(table, "DomHelper.prototype.field");
    assertThat(field).isNull();
  }

  @Test
  public void testPrototypeReferences() {
    SymbolTable table =
        createSymbolTable(
            lines(
                "/** @constructor */ function DomHelper() {}",
                "DomHelper.prototype.method = function() {};"));
    Symbol prototype = getGlobalVar(table, "DomHelper.prototype");
    assertThat(prototype).isNotNull();

    List<Reference> refs = table.getReferenceList(prototype);

    // One of the refs is implicit in the declaration of the function.
    assertWithMessage(refs.toString()).that(refs.size()).isEqualTo(2);
  }

  @Test
  public void testPrototypeReferences2() {
    SymbolTable table =
        createSymbolTable(
            "/** @constructor */" + "function Snork() {}" + "Snork.prototype.baz = 3;");
    Symbol prototype = getGlobalVar(table, "Snork.prototype");
    assertThat(prototype).isNotNull();

    List<Reference> refs = table.getReferenceList(prototype);
    assertThat(refs).hasSize(2);
  }

  @Test
  public void testPrototypeReferences3() {
    SymbolTable table = createSymbolTable("/** @constructor */ function Foo() {}");
    Symbol fooPrototype = getGlobalVar(table, "Foo.prototype");
    assertThat(fooPrototype).isNotNull();

    List<Reference> refs = table.getReferenceList(fooPrototype);
    assertThat(refs).hasSize(1);
    assertThat(refs.get(0).getNode().getToken()).isEqualTo(Token.NAME);

    // Make sure that the ctor and its prototype are declared at the
    // same node.
    assertThat(table.getReferenceList(getGlobalVar(table, "Foo")).get(0).getNode())
        .isEqualTo(refs.get(0).getNode());
  }

  @Test
  public void testPrototypeReferences4() {
    SymbolTable table =
        createSymbolTable(
            lines("/** @constructor */ function Foo() {}", "Foo.prototype = {bar: 3}"));
    Symbol fooPrototype = getGlobalVar(table, "Foo.prototype");
    assertThat(fooPrototype).isNotNull();

    List<Reference> refs = ImmutableList.copyOf(table.getReferences(fooPrototype));
    assertThat(refs).hasSize(1);
    assertThat(refs.get(0).getNode().getToken()).isEqualTo(Token.GETPROP);
    assertThat(refs.get(0).getNode().getQualifiedName()).isEqualTo("Foo.prototype");
  }

  @Test
  public void testPrototypeReferences5() {
    SymbolTable table =
        createSymbolTable("var goog = {}; /** @constructor */ goog.Foo = function() {};");
    Symbol fooPrototype = getGlobalVar(table, "goog.Foo.prototype");
    assertThat(fooPrototype).isNotNull();

    List<Reference> refs = table.getReferenceList(fooPrototype);
    assertThat(refs).hasSize(1);
    assertThat(refs.get(0).getNode().getToken()).isEqualTo(Token.GETPROP);

    // Make sure that the ctor and its prototype are declared at the
    // same node.
    assertThat(table.getReferenceList(getGlobalVar(table, "goog.Foo")).get(0).getNode())
        .isEqualTo(refs.get(0).getNode());
  }

  @Test
  public void testReferencesInJSDocType() {
    SymbolTable table =
        createSymbolTable(
            lines(
                "/** @constructor */ function Foo() {}",
                "/** @type {Foo} */ var x;",
                "/** @param {Foo} x */ function f(x) {}",
                "/** @return {function(): Foo} */ function g() {}",
                "/**",
                " * @constructor",
                " * @extends {Foo}",
                " */ function Sub() {}"));
    Symbol foo = getGlobalVar(table, "Foo");
    assertThat(foo).isNotNull();

    List<Reference> refs = table.getReferenceList(foo);
    assertThat(refs).hasSize(5);

    assertThat(refs.get(0).getNode().getLineno()).isEqualTo(1);
    assertThat(refs.get(0).getNode().getCharno()).isEqualTo(29);
    assertThat(refs.get(0).getNode().getLength()).isEqualTo(3);

    assertThat(refs.get(1).getNode().getLineno()).isEqualTo(2);
    assertThat(refs.get(1).getNode().getCharno()).isEqualTo(11);

    assertThat(refs.get(2).getNode().getLineno()).isEqualTo(3);
    assertThat(refs.get(2).getNode().getCharno()).isEqualTo(12);

    assertThat(refs.get(3).getNode().getLineno()).isEqualTo(4);
    assertThat(refs.get(3).getNode().getCharno()).isEqualTo(25);

    assertThat(refs.get(4).getNode().getLineno()).isEqualTo(7);
    assertThat(refs.get(4).getNode().getCharno()).isEqualTo(13);
  }

  @Test
  public void testReferencesInJSDocType2() {
    SymbolTable table = createSymbolTable("/** @param {string} x */ function f(x) {}");
    Symbol str = getGlobalVar(table, "String");
    assertThat(str).isNotNull();

    List<Reference> refs = table.getReferenceList(str);

    // We're going to pick up a lot of references from the externs,
    // so it's not meaningful to check the number of references.
    // We really want to make sure that all the references are in the externs,
    // except the last one.
    assertThat(refs.size()).isGreaterThan(1);

    int last = refs.size() - 1;
    for (int i = 0; i < refs.size(); i++) {
      Reference ref = refs.get(i);
      assertThat(ref.getNode().isFromExterns()).isEqualTo(i != last);
      if (!ref.getNode().isFromExterns()) {
        assertThat(ref.getNode().getSourceFileName()).isEqualTo("in1");
      }
    }
  }

  @Test
  public void testDottedReferencesInJSDocType() {
    SymbolTable table =
        createSymbolTable(
            lines(
                "var goog = {};",
                "/** @constructor */ goog.Foo = function() {}",
                "/** @type {goog.Foo} */ var x;",
                "/** @param {goog.Foo} x */ function f(x) {}",
                "/** @return {function(): goog.Foo} */ function g() {}",
                "/**",
                " * @constructor",
                " * @extends {goog.Foo}",
                " */ function Sub() {}"));
    Symbol foo = getGlobalVar(table, "goog.Foo");
    assertThat(foo).isNotNull();

    List<Reference> refs = table.getReferenceList(foo);
    assertThat(refs).hasSize(5);

    assertThat(refs.get(0).getNode().getLineno()).isEqualTo(2);
    assertThat(refs.get(0).getNode().getCharno()).isEqualTo(20);
    assertThat(refs.get(0).getNode().getLength()).isEqualTo(8);

    assertThat(refs.get(1).getNode().getLineno()).isEqualTo(3);
    assertThat(refs.get(1).getNode().getCharno()).isEqualTo(16);

    assertThat(refs.get(2).getNode().getLineno()).isEqualTo(4);
    assertThat(refs.get(2).getNode().getCharno()).isEqualTo(17);

    assertThat(refs.get(3).getNode().getLineno()).isEqualTo(5);
    assertThat(refs.get(3).getNode().getCharno()).isEqualTo(30);

    assertThat(refs.get(4).getNode().getLineno()).isEqualTo(8);
    assertThat(refs.get(4).getNode().getCharno()).isEqualTo(18);
  }

  @Test
  public void testReferencesInJSDocName() {
    String code = "/** @param {Object} x */ function f(x) {}";
    SymbolTable table = createSymbolTable(code);
    Symbol x = getLocalVar(table, "x");
    assertThat(x).isNotNull();

    List<Reference> refs = table.getReferenceList(x);
    assertThat(refs).hasSize(2);

    assertThat(refs.get(0).getNode().getCharno()).isEqualTo(code.indexOf("x) {"));
    assertThat(refs.get(1).getNode().getCharno()).isEqualTo(code.indexOf("x */"));
    assertThat(refs.get(0).getNode().getSourceFileName()).isEqualTo("in1");
  }

  @Test
  public void testLocalQualifiedNamesInLocalScopes() {
    SymbolTable table = createSymbolTable("function f() { var x = {}; x.number = 3; }");
    Symbol xNumber = getLocalVar(table, "x.number");
    assertThat(xNumber).isNotNull();
    assertThat(table.getScope(xNumber).isGlobalScope()).isFalse();

    assertThat(xNumber.getType().toString()).isEqualTo("number");
  }

  @Test
  public void testNaturalSymbolOrdering() {
    SymbolTable table =
        createSymbolTable(
            lines(
                "/** @const */ var a = {};",
                "/** @const */ a.b = {};",
                "/** @param {number} x */ function f(x) {}"));
    Symbol a = getGlobalVar(table, "a");
    Symbol ab = getGlobalVar(table, "a.b");
    Symbol f = getGlobalVar(table, "f");
    Symbol x = getLocalVar(table, "x");
    Ordering<Symbol> ordering = table.getNaturalSymbolOrdering();
    assertSymmetricOrdering(ordering, a, ab);
    assertSymmetricOrdering(ordering, a, f);
    assertSymmetricOrdering(ordering, f, ab);
    assertSymmetricOrdering(ordering, f, x);
  }

  @Test
  public void testDeclarationDisagreement() {
    SymbolTable table =
        createSymbolTable(
            lines(
                "/** @const */ var goog = goog || {};",
                "/** @param {!Function} x */",
                "goog.addSingletonGetter2 = function(x) {};",
                "/** Wakka wakka wakka */",
                "goog.addSingletonGetter = goog.addSingletonGetter2;",
                "/** @param {!Function} x */",
                "goog.addSingletonGetter = function(x) {};"));

    Symbol method = getGlobalVar(table, "goog.addSingletonGetter");
    List<Reference> refs = table.getReferenceList(method);
    assertThat(refs).hasSize(2);

    // Note that the declaration should show up second.
    assertThat(method.getDeclaration().getNode().getLineno()).isEqualTo(7);
    assertThat(refs.get(1).getNode().getLineno()).isEqualTo(5);
  }

  @Test
  public void testMultipleExtends() {
    SymbolTable table =
        createSymbolTable(
            lines(
                "/** @const */ var goog = goog || {};",
                "goog.inherits = function(x, y) {};",
                "/** @constructor */",
                "goog.A = function() { this.fieldA = this.constructor; };",
                "/** @constructor */ goog.A.FooA = function() {};",
                "/** @return {void} */ goog.A.prototype.methodA = function() {};",
                "/**",
                " * @constructor",
                " * @extends {goog.A}",
                " */",
                "goog.B = function() { this.fieldB = this.constructor; };",
                "goog.inherits(goog.B, goog.A);",
                "/** @return {void} */ goog.B.prototype.methodB = function() {};",
                "/**",
                " * @constructor",
                " * @extends {goog.A}",
                " */",
                "goog.B2 = function() { this.fieldB = this.constructor; };",
                "goog.inherits(goog.B2, goog.A);",
                "/** @constructor */ goog.B2.FooB = function() {};",
                "/** @return {void} */ goog.B2.prototype.methodB = function() {};",
                "/**",
                " * @constructor",
                " * @extends {goog.B}",
                " */",
                "goog.C = function() { this.fieldC = this.constructor; };",
                "goog.inherits(goog.C, goog.B);",
                "/** @constructor */ goog.C.FooC = function() {};",
                "/** @return {void} */ goog.C.prototype.methodC = function() {};"));

    Symbol bCtor = getGlobalVar(table, "goog.B.prototype.constructor");
    assertThat(bCtor).isNotNull();

    List<Reference> bRefs = table.getReferenceList(bCtor);
    assertThat(bRefs).hasSize(2);
    assertThat(bCtor.getDeclaration().getNode().getLineno()).isEqualTo(11);

    Symbol cCtor = getGlobalVar(table, "goog.C.prototype.constructor");
    assertThat(cCtor).isNotNull();

    List<Reference> cRefs = table.getReferenceList(cCtor);
    assertThat(cRefs).hasSize(2);
    assertThat(cCtor.getDeclaration().getNode().getLineno()).isEqualTo(26);
  }

  @Test
  public void testJSDocAssociationWithBadNamespace() {
    SymbolTable table =
        createSymbolTable(
            // Notice that the declaration for "goog" is missing.
            // We want to recover anyway and print out what we know
            // about goog.Foo.
            "/** @constructor */ goog.Foo = function(){};");

    Symbol foo = getGlobalVar(table, "goog.Foo");
    assertThat(foo).isNotNull();

    JSDocInfo info = foo.getJSDocInfo();
    assertThat(info).isNotNull();
    assertThat(info.isConstructor()).isTrue();
  }

  @Test
  public void testMissingConstructorTag() {
    SymbolTable table =
        createSymbolTable(
            lines(
                "function F() {",
                "  this.field1 = 3;",
                "}",
                "F.prototype.method1 = function() {",
                "  this.field1 = 5;",
                "};",
                "(new F()).method1();"));

    // Because the constructor tag is missing, this is going
    // to be missing a lot of inference.
    assertThat(getGlobalVar(table, "F.prototype.field1")).isNull();

    Symbol sym = getGlobalVar(table, "F.prototype.method1");
    assertThat(table.getReferenceList(sym)).hasSize(1);
  }

  @Test
  public void testTypeCheckingOff() {
    options = new CompilerOptions();

    // Turning type-checking off is even worse than not annotating anything.
    SymbolTable table =
        createSymbolTable(
            lines(
                "/** @contstructor */",
                "function F() {",
                "  this.field1 = 3;",
                "}",
                "F.prototype.method1 = function() {",
                "  this.field1 = 5;",
                "};",
                "(new F()).method1();"));
    assertThat(getGlobalVar(table, "F.prototype.field1")).isNull();
    assertThat(getGlobalVar(table, "F.prototype.method1")).isNull();

    Symbol sym = getGlobalVar(table, "F");
    assertThat(table.getReferenceList(sym)).hasSize(3);
  }

  @Test
  public void testSuperClassReference() {
    SymbolTable table =
        createSymbolTable(
            "  var a = {b: {}};"
                + "/** @constructor */"
                + "a.b.BaseClass = function() {};"
                + "a.b.BaseClass.prototype.doSomething = function() {"
                + "  alert('hi');"
                + "};"
                + "/**"
                + " * @constructor"
                + " * @extends {a.b.BaseClass}"
                + " */"
                + "a.b.DerivedClass = function() {};"
                + "goog.inherits(a.b.DerivedClass, a.b.BaseClass);"
                + "/** @override */"
                + "a.b.DerivedClass.prototype.doSomething = function() {"
                + "  a.b.DerivedClass.superClass_.doSomething();"
                + "};");

    Symbol bad = getGlobalVar(table, "a.b.DerivedClass.superClass_.doSomething");
    assertThat(bad).isNull();

    Symbol good = getGlobalVar(table, "a.b.BaseClass.prototype.doSomething");
    assertThat(good).isNotNull();

    List<Reference> refs = table.getReferenceList(good);
    assertThat(refs).hasSize(2);
    assertThat(refs.get(1).getNode().getQualifiedName())
        .isEqualTo("a.b.DerivedClass.superClass_.doSomething");
  }

  @Test
  public void testInnerEnum() {
    SymbolTable table =
        createSymbolTable(
            "var goog = {}; goog.ui = {};"
                + "  /** @constructor */"
                + "goog.ui.Zippy = function() {};"
                + "/** @enum {string} */"
                + "goog.ui.Zippy.EventType = { TOGGLE: 'toggle' };");

    Symbol eventType = getGlobalVar(table, "goog.ui.Zippy.EventType");
    assertThat(eventType).isNotNull();
    assertThat(eventType.getType().isEnumType()).isTrue();

    Symbol toggle = getGlobalVar(table, "goog.ui.Zippy.EventType.TOGGLE");
    assertThat(toggle).isNotNull();
  }

  @Test
  public void testMethodInAnonObject1() {
    SymbolTable table = createSymbolTable("var a = {}; a.b = {}; a.b.c = function() {};");
    Symbol a = getGlobalVar(table, "a");
    Symbol ab = getGlobalVar(table, "a.b");
    Symbol abc = getGlobalVar(table, "a.b.c");

    assertThat(abc).isNotNull();
    assertThat(table.getReferenceList(abc)).hasSize(1);

    assertThat(a.getType().toString()).isEqualTo("{b: {c: function(): undefined}}");
    assertThat(ab.getType().toString()).isEqualTo("{c: function(): undefined}");
    assertThat(abc.getType().toString()).isEqualTo("function(): undefined");
  }

  @Test
  public void testMethodInAnonObject2() {
    SymbolTable table = createSymbolTable("var a = {b: {c: function() {}}};");
    Symbol a = getGlobalVar(table, "a");
    Symbol ab = getGlobalVar(table, "a.b");
    Symbol abc = getGlobalVar(table, "a.b.c");

    assertThat(abc).isNotNull();
    assertThat(table.getReferenceList(abc)).hasSize(1);

    assertThat(a.getType().toString()).isEqualTo("{b: {c: function(): undefined}}");
    assertThat(ab.getType().toString()).isEqualTo("{c: function(): undefined}");
    assertThat(abc.getType().toString()).isEqualTo("function(): undefined");
  }

  @Test
  public void testJSDocOnlySymbol() {
    SymbolTable table =
        createSymbolTable(lines("/**", " * @param {number} x", " * @param y", " */", "var a;"));
    Symbol x = getDocVar(table, "x");
    assertThat(x).isNotNull();
    assertThat(x.getType().toString()).isEqualTo("number");
    assertThat(table.getReferenceList(x)).hasSize(1);

    Symbol y = getDocVar(table, "y");
    assertThat(x).isNotNull();
    assertThat(y.getType()).isNull();
    assertThat(table.getReferenceList(y)).hasSize(1);
  }

  @Test
  public void testNamespaceDefinitionOrder() {
    // Sometimes, weird things can happen where the files appear in
    // a strange order. We need to make sure we're robust against this.
    SymbolTable table =
        createSymbolTable(
            lines(
                "/** @const */ var goog = {};",
                "/** @constructor */ goog.dom.Foo = function() {};",
                "/** @const */ goog.dom = {};"));

    Symbol goog = getGlobalVar(table, "goog");
    Symbol dom = getGlobalVar(table, "goog.dom");
    Symbol Foo = getGlobalVar(table, "goog.dom.Foo");

    assertThat(goog).isNotNull();
    assertThat(dom).isNotNull();
    assertThat(Foo).isNotNull();

    assertThat(goog.getPropertyScope().getSlot("dom")).isEqualTo(dom);
    assertThat(dom.getPropertyScope().getSlot("Foo")).isEqualTo(Foo);
  }

  @Test
  public void testConstructorAlias() {
    SymbolTable table =
        createSymbolTable(
            lines(
                "/** @constructor */ var Foo = function() {};",
                "/** desc */ Foo.prototype.bar = function() {};",
                "/** @constructor */ var FooAlias = Foo;",
                "/** desc */ FooAlias.prototype.baz = function() {};"));

    Symbol foo = getGlobalVar(table, "Foo");
    Symbol fooAlias = getGlobalVar(table, "FooAlias");
    Symbol bar = getGlobalVar(table, "Foo.prototype.bar");
    Symbol baz = getGlobalVar(table, "Foo.prototype.baz");
    Symbol bazAlias = getGlobalVar(table, "FooAlias.prototype.baz");

    assertThat(foo).isNotNull();
    assertThat(fooAlias).isNotNull();
    assertThat(bar).isNotNull();
    assertThat(baz).isNotNull();
    assertThat(bazAlias).isNull();

    Symbol barScope = table.getSymbolForScope(table.getScope(bar));
    assertThat(barScope).isNotNull();

    Symbol bazScope = table.getSymbolForScope(table.getScope(baz));
    assertThat(bazScope).isNotNull();

    Symbol fooPrototype = foo.getPropertyScope().getSlot("prototype");
    assertThat(fooPrototype).isNotNull();

    assertThat(barScope).isEqualTo(fooPrototype);
    assertThat(bazScope).isEqualTo(fooPrototype);
  }

  @Test
  public void testSymbolForScopeOfNatives() {
    SymbolTable table = createSymbolTable("");

    // From the externs.
    Symbol sliceArg = getLocalVar(table, "sliceArg");
    assertThat(sliceArg).isNotNull();

    Symbol scope = table.getSymbolForScope(table.getScope(sliceArg));
    assertThat(scope).isNotNull();
    assertThat(getGlobalVar(table, "String.prototype.slice")).isEqualTo(scope);

    Symbol proto = getGlobalVar(table, "String.prototype");
    assertThat(proto.getDeclaration().getNode().getSourceFileName()).isEqualTo("externs1");
  }

  @Test
  public void testJSDocNameVisibility() {
    SymbolTable table =
        createSymbolTable(
            lines(
                "/** @public */ var foo;",
                "/** @protected */ var bar;",
                "/** @package */ var baz;",
                "/** @private */ var quux;",
                "var xyzzy;"));

    assertThat(getGlobalVar(table, "foo").getVisibility()).isEqualTo(Visibility.PUBLIC);
    assertThat(getGlobalVar(table, "bar").getVisibility()).isEqualTo(Visibility.PROTECTED);
    assertThat(getGlobalVar(table, "baz").getVisibility()).isEqualTo(Visibility.PACKAGE);
    assertThat(getGlobalVar(table, "quux").getVisibility()).isEqualTo(Visibility.PRIVATE);
    assertThat(getGlobalVar(table, "xyzzy").getVisibility()).isEqualTo(Visibility.INHERITED);
    assertThat(getGlobalVar(table, "xyzzy").getJSDocInfo()).isNull();
  }

  @Test
  public void testJSDocNameVisibilityWithFileOverviewVisibility() {
    SymbolTable table =
        createSymbolTable(
            lines(
                "/** @fileoverview\n @package */",
                "/** @public */ var foo;",
                "/** @protected */ var bar;",
                "/** @package */ var baz;",
                "/** @private */ var quux;",
                "var xyzzy;"));
    assertThat(getGlobalVar(table, "foo").getVisibility()).isEqualTo(Visibility.PUBLIC);
    assertThat(getGlobalVar(table, "bar").getVisibility()).isEqualTo(Visibility.PROTECTED);
    assertThat(getGlobalVar(table, "baz").getVisibility()).isEqualTo(Visibility.PACKAGE);
    assertThat(getGlobalVar(table, "quux").getVisibility()).isEqualTo(Visibility.PRIVATE);
    assertThat(getGlobalVar(table, "xyzzy").getVisibility()).isEqualTo(Visibility.PACKAGE);
    assertThat(getGlobalVar(table, "xyzzy").getJSDocInfo()).isNull();
  }

  @Test
  public void testJSDocPropertyVisibility() {
    SymbolTable table =
        createSymbolTable(
            lines(
                "/** @constructor */ var Foo = function() {};",
                "/** @public */ Foo.prototype.bar;",
                "/** @protected */ Foo.prototype.baz;",
                "/** @package */ Foo.prototype.quux;",
                "/** @private */ Foo.prototype.xyzzy;",
                "Foo.prototype.plugh;",
                "/** @constructor @extends {Foo} */ var SubFoo = function() {};",
                "/** @override */ SubFoo.prototype.bar = function() {};",
                "/** @override */ SubFoo.prototype.baz = function() {};",
                "/** @override */ SubFoo.prototype.quux = function() {};",
                "/** @override */ SubFoo.prototype.xyzzy = function() {};",
                "/** @override */ SubFoo.prototype.plugh = function() {};"));

    assertThat(getGlobalVar(table, "Foo.prototype.bar").getVisibility())
        .isEqualTo(Visibility.PUBLIC);
    assertThat(getGlobalVar(table, "Foo.prototype.baz").getVisibility())
        .isEqualTo(Visibility.PROTECTED);
    assertThat(getGlobalVar(table, "Foo.prototype.quux").getVisibility())
        .isEqualTo(Visibility.PACKAGE);
    assertThat(getGlobalVar(table, "Foo.prototype.xyzzy").getVisibility())
        .isEqualTo(Visibility.PRIVATE);
    assertThat(getGlobalVar(table, "Foo.prototype.plugh").getVisibility())
        .isEqualTo(Visibility.INHERITED);
    assertThat(getGlobalVar(table, "Foo.prototype.plugh").getJSDocInfo()).isNull();

    assertThat(getGlobalVar(table, "SubFoo.prototype.bar").getVisibility())
        .isEqualTo(Visibility.INHERITED);
    assertThat(getGlobalVar(table, "SubFoo.prototype.baz").getVisibility())
        .isEqualTo(Visibility.INHERITED);
    assertThat(getGlobalVar(table, "SubFoo.prototype.quux").getVisibility())
        .isEqualTo(Visibility.INHERITED);
    assertThat(getGlobalVar(table, "SubFoo.prototype.xyzzy").getVisibility())
        .isEqualTo(Visibility.INHERITED);
    assertThat(getGlobalVar(table, "SubFoo.prototype.plugh").getVisibility())
        .isEqualTo(Visibility.INHERITED);
  }

  @Test
  public void testJSDocPropertyVisibilityWithFileOverviewVisibility() {
    SymbolTable table =
        createSymbolTable(
            lines(
                "/** @fileoverview\n @package */",
                "/** @constructor */ var Foo = function() {};",
                "/** @public */ Foo.prototype.bar;",
                "/** @protected */ Foo.prototype.baz;",
                "/** @package */ Foo.prototype.quux;",
                "/** @private */ Foo.prototype.xyzzy;",
                "Foo.prototype.plugh;",
                "/** @constructor @extends {Foo} */ var SubFoo = function() {};",
                "/** @override @public */ SubFoo.prototype.bar = function() {};",
                "/** @override @protected */ SubFoo.prototype.baz = function() {};",
                "/** @override @package */ SubFoo.prototype.quux = function() {};",
                "/** @override @private */ SubFoo.prototype.xyzzy = function() {};",
                "/** @override */ SubFoo.prototype.plugh = function() {};"));

    assertThat(getGlobalVar(table, "Foo.prototype.bar").getVisibility())
        .isEqualTo(Visibility.PUBLIC);
    assertThat(getGlobalVar(table, "Foo.prototype.baz").getVisibility())
        .isEqualTo(Visibility.PROTECTED);
    assertThat(getGlobalVar(table, "Foo.prototype.quux").getVisibility())
        .isEqualTo(Visibility.PACKAGE);
    assertThat(getGlobalVar(table, "Foo.prototype.xyzzy").getVisibility())
        .isEqualTo(Visibility.PRIVATE);
    assertThat(getGlobalVar(table, "Foo.prototype.plugh").getVisibility())
        .isEqualTo(Visibility.PACKAGE);
    assertThat(getGlobalVar(table, "Foo.prototype.plugh").getJSDocInfo()).isNull();

    assertThat(getGlobalVar(table, "SubFoo.prototype.bar").getVisibility())
        .isEqualTo(Visibility.INHERITED);
    assertThat(getGlobalVar(table, "SubFoo.prototype.baz").getVisibility())
        .isEqualTo(Visibility.INHERITED);
    assertThat(getGlobalVar(table, "SubFoo.prototype.quux").getVisibility())
        .isEqualTo(Visibility.INHERITED);
    assertThat(getGlobalVar(table, "SubFoo.prototype.xyzzy").getVisibility())
        .isEqualTo(Visibility.INHERITED);
    assertThat(getGlobalVar(table, "SubFoo.prototype.plugh").getVisibility())
        .isEqualTo(Visibility.INHERITED);
  }

  @Test
  public void testPrototypeSymbolEqualityForTwoPathsToSamePrototype() {
    String input =
        lines(
            "/**",
            "* An employer.",
            "*",
            "* @param {String} name name of employer.",
            "* @param {String} address address of employer.",
            "* @constructor",
            "*/",
            "function Employer(name, address) {",
            "this.name = name;",
            "this.address = address;",
            "}",
            "",
            "/**",
            "* @return {String} information about an employer.",
            "*/",
            "Employer.prototype.getInfo = function() {",
            "return this.name + '.' + this.address;",
            "};");
    SymbolTable table = createSymbolTable(input);
    Symbol employer = getGlobalVar(table, "Employer");
    assertThat(employer).isNotNull();
    SymbolScope propertyScope = employer.getPropertyScope();
    assertThat(propertyScope).isNotNull();
    Symbol prototypeOfEmployer = propertyScope.getQualifiedSlot("prototype");
    assertThat(prototypeOfEmployer).isNotNull();

    Symbol employerPrototype = getGlobalVar(table, "Employer.prototype");
    assertThat(employerPrototype).isNotNull();

    new EqualsTester().addEqualityGroup(employerPrototype, prototypeOfEmployer).testEquals();
  }

  @Test
  public void testRestParameter() {
    String input = "function f(...x) {} f(1, 2, 3);";

    SymbolTable table = createSymbolTable(input);

    Symbol f = getGlobalVar(table, "f");
    assertThat(f).isNotNull();

    Symbol x = table.getParameterInFunction(f, "x");
    assertThat(x).isNotNull();
  }

  @Test
  public void testGetEnclosingScope_Global() {
    SymbolTable table = createSymbolTable("const baz = 1;");

    Symbol baz = getLocalVar(table, "baz");
    SymbolScope bazScope = table.getEnclosingScope(baz.getDeclarationNode());

    assertThat(bazScope).isNotNull();
    assertThat(bazScope.isGlobalScope()).isTrue();
  }

  @Test
  public void testGetEnclosingScope_GlobalNested() {
    SymbolTable table = createSymbolTable("{ const baz = 1; }");

    Symbol baz = getLocalVar(table, "baz");
    SymbolScope bazScope = table.getEnclosingScope(baz.getDeclarationNode());

    assertThat(bazScope).isNotNull();
    assertThat(bazScope.isBlockScope()).isTrue();
    assertThat(bazScope.getParentScope().isGlobalScope()).isTrue();
  }

  @Test
  public void testGetEnclosingScope_FunctionNested() {
    SymbolTable table = createSymbolTable("function foo() { { const baz = 1; } }");

    Symbol baz = getLocalVar(table, "baz");
    SymbolScope bazScope = table.getEnclosingScope(baz.getDeclarationNode());

    assertThat(bazScope).isNotNull();
    assertThat(bazScope.isBlockScope()).isTrue();
    assertThat(bazScope.getParentScope().isBlockScope()).isTrue();
    Node foo = getGlobalVar(table, "foo").getDeclarationNode().getParent();
    assertThat(bazScope.getParentScope().getParentScope().getRootNode()).isEqualTo(foo);
  }

  @Test
  public void testGetEnclosingFunctionScope_GlobalScopeNoNesting() {
    SymbolTable table = createSymbolTable("const baz = 1;");

    Symbol baz = getLocalVar(table, "baz");
    SymbolScope bazFunctionScope = table.getEnclosingFunctionScope(baz.getDeclarationNode());

    assertThat(bazFunctionScope).isNotNull();
    assertThat(bazFunctionScope.isGlobalScope()).isTrue();
  }

  @Test
  public void testGetEnclosingFunctionScope_GlobalScopeNested() {
    SymbolTable table = createSymbolTable("{ const baz = 1; }");

    Symbol baz = getLocalVar(table, "baz");
    SymbolScope bazFunctionScope = table.getEnclosingFunctionScope(baz.getDeclarationNode());

    assertThat(bazFunctionScope).isNotNull();
    assertThat(bazFunctionScope.isGlobalScope()).isTrue();
  }

  @Test
  public void testGetEnclosingFunctionScope_FunctionNoNestedScopes() {
    SymbolTable table = createSymbolTable("function foo() { const baz = 1; }");

    Symbol baz = getLocalVar(table, "baz");
    SymbolScope bazFunctionScope = table.getEnclosingFunctionScope(baz.getDeclarationNode());

    assertThat(bazFunctionScope).isNotNull();
    Node foo = getGlobalVar(table, "foo").getDeclarationNode().getParent();
    assertThat(bazFunctionScope.getRootNode()).isEqualTo(foo);
  }

  @Test
  public void testGetEnclosingFunctionScope_FunctionNested() {
    SymbolTable table = createSymbolTable("function foo() { { { const baz = 1; } } }");

    Symbol baz = getLocalVar(table, "baz");
    SymbolScope bazFunctionScope = table.getEnclosingFunctionScope(baz.getDeclarationNode());

    assertThat(bazFunctionScope).isNotNull();
    Node foo = getGlobalVar(table, "foo").getDeclarationNode().getParent();
    assertThat(bazFunctionScope.getRootNode()).isEqualTo(foo);
  }

  @Test
  public void testGetEnclosingFunctionScope_FunctionInsideFunction() {
    SymbolTable table = createSymbolTable("function foo() { function baz() {} }");

    Symbol baz = getLocalVar(table, "baz");
    SymbolScope bazFunctionScope = table.getEnclosingFunctionScope(baz.getDeclarationNode());

    assertThat(bazFunctionScope).isNotNull();
    Node foo = getGlobalVar(table, "foo").getDeclarationNode().getParent();
    assertThat(bazFunctionScope.getRootNode()).isEqualTo(foo);
  }

  @Test
  public void testSymbolSuperclassStaticInheritance() {
    // set this option so that typechecking sees untranspiled classes.
    // TODO(b/76025401): remove this option after class transpilation is always post-typechecking
    options.setLanguageOut(LanguageMode.ECMASCRIPT_2015);
    options.setSkipUnsupportedPasses(false);

    SymbolTable table =
        createSymbolTable(
            lines(
                "class Bar { static staticMethod() {} }",
                "class Foo extends Bar {",
                "  act() { Foo.staticMethod(); }",
                "}"));

    Symbol foo = getGlobalVar(table, "Foo");
    Symbol bar = getGlobalVar(table, "Bar");

    FunctionType barType = checkNotNull(bar.getType().toMaybeFunctionType());
    FunctionType fooType = checkNotNull(foo.getType().toMaybeFunctionType());

    FunctionType superclassCtorType = fooType.getSuperClassConstructor();

    assertType(superclassCtorType).isEqualTo(barType);
    Symbol superSymbol = table.getSymbolDeclaredBy(superclassCtorType);
    assertThat(superSymbol).isEqualTo(bar);

    Symbol barStaticMethod = getGlobalVar(table, "Bar.staticMethod");
    ImmutableList<Reference> barStaticMethodRefs = table.getReferenceList(barStaticMethod);
    assertThat(barStaticMethodRefs).hasSize(2);
    assertThat(barStaticMethodRefs.get(0)).isEqualTo(barStaticMethod.getDeclaration());
    // We recognize that the call to Foo.staticMethod() is actually a call to Bar.staticMethod().
    assertNode(barStaticMethodRefs.get(1).getNode()).matchesQualifiedName("Foo.staticMethod");
  }

  @Test
  public void testTypedefInNodeJsModule() {
    options.setProcessCommonJSModules(true);
    SymbolTable table =
        createSymbolTableFromTwoSources(
            lines("/** @typedef {number} */", "exports.MyTypedef;"),
            lines(
                "const file1 = require('./file1.js');",
                "/** @const {!file1.MyTypedef} */",
                "const one = 1;"));

    Symbol typedefSymbol = getGlobalVar(table, "module$file1.default.MyTypedef");
    assertThat(typedefSymbol).isNotNull();
    assertThat(table.getReferenceList(typedefSymbol)).hasSize(2);
  }

  @Test
  public void testSuperKeywords() {
    SymbolTable table =
        createSymbolTable(
            lines(
                "class Parent { doFoo() {} }",
                "class Child extends Parent {",
                "  constructor() { super(); }",
                "  doFoo() { super.doFoo(); }",
                "}"));

    Symbol parentClass = getGlobalVar(table, "Parent");
    long numberOfSuperReferences =
        table.getReferenceList(parentClass).stream()
            .filter((Reference ref) -> ref.getNode().isSuper())
            .count();
    // TODO(b/112359882): change number of refs to 2 once Es6ConvertSuper pass is moved after type
    // checks.
    assertThat(numberOfSuperReferences).isEqualTo(1);
  }

  @Test
  public void testDuplicatedWindowExternsMerged() {
    // Add window so that it triggers logic that defines all global externs on window.
    // See DeclaredGlobalExternsOnWindow.java pass.
    String externs = lines("/** @externs */", "var window", "/** @type {number} */ var foo;");
    String mainCode = lines("foo = 2;", "window.foo = 1;");
    SymbolTable table = createSymbolTable(mainCode, externs);

    Map<String, Integer> refsPerFile = new HashMap<>();
    for (Reference reference : table.getReferenceList(getGlobalVar(table, "foo"))) {
      String file = reference.getSourceFile().getName();
      refsPerFile.put(file, refsPerFile.getOrDefault(file, 0) + 1);
    }
    assertThat(refsPerFile).containsExactly("in1", 2, "externs1", 1);
  }

  @Test
  public void testDuplicatedWindowExternsMergedWithWindowPrototype() {
    // Add window so that it triggers logic that defines all global externs on window.
    // See DeclaredGlobalExternsOnWindow.java pass.
    // Also add Window class as it affects symbols (e.g. window.foo is set on Window.prototype.foo
    // instead).
    String externs =
        lines(
            "/** @externs */",
            "/** @constructor */ function Window() {}",
            "/** @type {!Window} */ var window;",
            "/** @type {number} */ var foo;");
    String mainCode = lines("foo = 2;", "window.foo = 1;");
    SymbolTable table = createSymbolTable(mainCode, externs);

    Map<String, Integer> refsPerFile = new HashMap<>();
    for (Reference reference : table.getReferenceList(getGlobalVar(table, "foo"))) {
      String file = reference.getSourceFile().getName();
      refsPerFile.put(file, refsPerFile.getOrDefault(file, 0) + 1);
    }
    assertThat(refsPerFile).containsExactly("in1", 2, "externs1", 1);
  }

  private void assertSymmetricOrdering(Ordering<Symbol> ordering, Symbol first, Symbol second) {
    assertThat(ordering.compare(first, first)).isEqualTo(0);
    assertThat(ordering.compare(second, second)).isEqualTo(0);
    assertThat(ordering.compare(first, second)).isLessThan(0);
    assertThat(ordering.compare(second, first)).isGreaterThan(0);
  }

  private Symbol getGlobalVar(SymbolTable table, String name) {
    return table.getGlobalScope().getQualifiedSlot(name);
  }

  private Symbol getDocVar(SymbolTable table, String name) {
    for (Symbol sym : table.getAllSymbols()) {
      if (sym.isDocOnlyParameter() && sym.getName().equals(name)) {
        return sym;
      }
    }
    return null;
  }

  private Symbol getLocalVar(SymbolTable table, String name) {
    for (SymbolScope scope : table.getAllScopes()) {
      if (!scope.isGlobalScope()
          && scope.isLexicalScope()
          && scope.getQualifiedSlot(name) != null) {
        return scope.getQualifiedSlot(name);
      }
    }
    return null;
  }

  /** Returns all non-extern vars. */
  private List<Symbol> getVars(SymbolTable table) {
    List<Symbol> result = new ArrayList<>();
    for (Symbol symbol : table.getAllSymbols()) {
      if (symbol.getDeclaration() != null && !symbol.getDeclaration().getNode().isFromExterns()) {
        result.add(symbol);
      }
    }
    return result;
  }

  private SymbolTable createSymbolTable(String input) {
    return createSymbolTable(input, EXTERNS);
  }

  private SymbolTable createSymbolTable(String input, String externsCode) {
    List<SourceFile> inputs = ImmutableList.of(SourceFile.fromCode("in1", input));
    List<SourceFile> externs = ImmutableList.of(SourceFile.fromCode("externs1", externsCode));

    Compiler compiler = new Compiler(new BlackHoleErrorManager());
    compiler.compile(externs, inputs, options);
    return assertSymbolTableValid(compiler.buildKnownSymbolTable());
  }

  private SymbolTable createSymbolTableFromTwoSources(String input1, String input2) {
    List<SourceFile> inputs =
        ImmutableList.of(
            SourceFile.fromCode("file1.js", input1), SourceFile.fromCode("file2.js", input2));
    List<SourceFile> externs = ImmutableList.of();

    Compiler compiler = new Compiler(new BlackHoleErrorManager());
    compiler.compile(externs, inputs, options);
    return assertSymbolTableValid(compiler.buildKnownSymbolTable());
  }

  /**
   * Asserts that the symbol table meets some invariants. Returns the same table for easy chaining.
   */
  private SymbolTable assertSymbolTableValid(SymbolTable table) {
    Set<Symbol> allSymbols = new HashSet<>();
    allSymbols.addAll(table.getAllSymbols());
    for (Symbol sym : table.getAllSymbols()) {
      // Make sure that grabbing the symbol's scope and looking it up
      // again produces the same symbol.
      assertThat(table.getScope(sym).getQualifiedSlot(sym.getName())).isEqualTo(sym);

      for (Reference ref : table.getReferences(sym)) {
        // Make sure that the symbol and reference are mutually linked.
        assertThat(ref.getSymbol()).isEqualTo(sym);
      }

      Symbol symbolForScope = table.getSymbolForScope(table.getScope(sym));
      if (symbolForScope != null) {
        assertWithMessage("The %s has a scope that shouldn't exist; a zombie scope.", sym)
            .that(allSymbols)
            .contains(symbolForScope);
      }
    }

    // Make sure that the global "this" is declared at the first input root.
    Symbol global = getGlobalVar(table, SymbolTable.GLOBAL_THIS);
    assertThat(global).isNotNull();
    assertThat(global.getDeclaration()).isNotNull();
    assertThat(global.getDeclaration().getNode().getToken()).isEqualTo(Token.SCRIPT);

    List<Reference> globalRefs = table.getReferenceList(global);

    // The main reference list should never contain the synthetic declaration
    // for the global root.
    assertThat(globalRefs).doesNotContain(global.getDeclaration());

    return table;
  }
}


text:
import abc
import urllib
import urlparse

from django import forms
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response
from django.template import RequestContext, TemplateDoesNotExist
from django.template.loader import get_template
from django.utils.decorators import classonlymethod
from django_conneg.decorators import renderer
from django_conneg.http import HttpResponseSeeOther
from django_conneg.views import HTMLView

from humfrey.linkeddata.views import MappingView
from humfrey.results.views.standard import RDFView
from humfrey.results.views.json import JSONRDFView
from humfrey.sparql.views import StoreView

class FeedForm(forms.Form):
    def __init__(self, *args, **kwargs):
        kwargs.pop('endpoint')

        conneg = kwargs.pop('conneg')
        format_choices = [(renderer.format, renderer.name) for renderer in conneg.renderers]
        format_choices.insert(0, ('', '-'*20))
        self.base_fields['format'].choices = format_choices

        orderings = kwargs.pop('orderings')
        order_by_choices = [(k, v[0]) for k,v in orderings.iteritems()]
        order_by_choices.insert(0, ('', '-'*20))
        self.base_fields['order_by'].choices = order_by_choices

        super(FeedForm, self).__init__(*args, **kwargs)

    format = forms.ChoiceField(required=False)
    order_by = forms.ChoiceField(required=False)
    css = forms.CharField(label="Additional CSS URL",
                          help_text="Used for HTML-based formats; a link tag will be added.",
                          required=False)

class FeedView(StoreView, MappingView, JSONRDFView, RDFView, HTMLView):
    __metaclass__ = abc.ABCMeta

    template_name = 'feeds/view'
    snippet_template = 'feeds/snippet'
    item_template = 'feeds/item'

    slug = None
    meta = None

    @abc.abstractproperty
    def form_class(self): pass

    @abc.abstractproperty
    def name(self): pass

    @abc.abstractproperty
    def plural_name(self): pass

    @abc.abstractproperty
    def description(self): pass

    @classonlymethod
    def as_view(self, **initkwargs):
        view = super(FeedView, self).as_view(**initkwargs)
        for n in ('orderings', 'form_class', 'name', 'description', 'plural_name'):
            setattr(view, n, getattr(self, n))
        view.meta, view.slug = initkwargs['meta'], initkwargs['slug']
        return view

    def get(self, request):
        self.form = self.form_class(request.GET,
                                    conneg=self.conneg,
                                    endpoint=self.endpoint,
                                    orderings=self.orderings)

        qs = request.META['QUERY_STRING']
        qs = urlparse.parse_qs(qs, keep_blank_values=1)
        qs.pop('format', None)
        qs = urllib.urlencode(qs, True)
        config_url = reverse('feeds:feed-config', args=[self.slug]) + '?' + qs

        self.context.update({'feed': self.meta,
                             'config_url': config_url,
                             'templates': {'snippet': self._template_name_joiner(self.snippet_template),
                                           'item': self._template_name_joiner(self.item_template),
                                           }})

        if self.form.is_valid():
            query_context = self.form.cleaned_data.copy()
            query_context.update({'url': request.build_absolute_uri()})
            results = self.endpoint.query(self.get_query(query_context), defer=True)
            self.context.update({'results': results,
                                 'cleaned_data': self.form.cleaned_data})
            return self.render()
        else:
            return HttpResponseSeeOther(self.context['config_url'])

    def get_query(self, query_context):
        t = get_template(self.query_template)
        c = RequestContext(self.request, query_context)
        return t.render(c)

    def sort_subjects(self, subjects):
        order_by = self.form.cleaned_data.get('order_by')
        if order_by:
            subjects.sort(key=self.orderings[order_by][1])
        else:
            super(FeedView, self).sort_subjects(subjects)

    def _template_name_joiner(self, template_name):
        class Joiner(object):
            def __init__(self, join_template_name, template_name):
                self.join_template_name = join_template_name
                self.template_name = template_name
            def __getattr__(self2, name):
                return self.join_template_name(template_name, name)
        return Joiner(self.join_template_name, template_name)

    @renderer(format='iframe', mimetypes=(), name='IFrame')
    def render_iframe(self, request, context, template_name):
        self.undefer()
        template_name = self.join_template_name(template_name, 'iframe')
        if template_name is None:
            return NotImplemented
        try:
            return render_to_response(template_name,
                                      context, context_instance=RequestContext(request),
                                      mimetype='text/html')
        except TemplateDoesNotExist:
            raise
            return NotImplemented


text:
MacStartupProfiler* MacStartupProfiler::GetInstance() {
  return base::Singleton<MacStartupProfiler>::get();
}

MacStartupProfiler::MacStartupProfiler() : recorded_metrics_(false) {
}

MacStartupProfiler::~MacStartupProfiler() {
}

void MacStartupProfiler::Profile(Location location) {
  profiled_ticks_[location] = base::TimeTicks::Now();
}

void MacStartupProfiler::RecordMetrics() {
  const base::TimeTicks main_entry_ticks =
      startup_metric_utils::MainEntryPointTicks();
  DCHECK(!main_entry_ticks.is_null());
  DCHECK(!recorded_metrics_);

  recorded_metrics_ = true;

  for (const std::pair<Location, base::TimeTicks>& entry : profiled_ticks_)
    RecordHistogram(entry.first, entry.second - main_entry_ticks);
}

const std::string MacStartupProfiler::HistogramName(Location location) {
  std::string prefix("Startup.OSX.");
  switch (location) {
    case PRE_MAIN_MESSAGE_LOOP_START:
      return prefix + "PreMainMessageLoopStart";
    case AWAKE_FROM_NIB:
      return prefix + "AwakeFromNib";
    case POST_MAIN_MESSAGE_LOOP_START:
      return prefix + "PostMainMessageLoopStart";
    case PRE_PROFILE_INIT:
      return prefix + "PreProfileInit";
    case POST_PROFILE_INIT:
      return prefix + "PostProfileInit";
    case WILL_FINISH_LAUNCHING:
      return prefix + "WillFinishLaunching";
    case DID_FINISH_LAUNCHING:
      return prefix + "DockIconWillFinishBouncing";
  }
}

void MacStartupProfiler::RecordHistogram(Location location,
                                         const base::TimeDelta& delta) {
  const std::string name(HistogramName(location));
  base::TimeDelta min = base::TimeDelta::FromMilliseconds(10);
  base::TimeDelta max = base::TimeDelta::FromMinutes(1);
  int bucket_count = 100;

  // No need to cache the histogram pointers, since each invocation of this
  // method will be the first and only usage of a histogram with that given
  // name.
  base::HistogramBase* histogram = base::Histogram::FactoryTimeGet(
      name,
      min,
      max,
      bucket_count,
      base::HistogramBase::kUmaTargetedHistogramFlag);
  histogram->AddTime(delta);
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.01.30 at 01:53:29 PM CET
//

package ExternalPackages.org.hupo.psi.ms.traml;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 * List of transitions
 *

 *
Java class for TransitionListType complex type.
 *

 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <complexType name="TransitionListType">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="Transition" type="{http://psi.hupo.org/ms/traml}TransitionType" maxOccurs="unbounded"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TransitionListType", propOrder = {
        "transition"
})
public class TransitionListType {

    @XmlElement(name = "Transition", required = true)
    protected List<TransitionType> transition;

    /**
     * Gets the value of the transition property.
     *

     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the transition property.
     *

     *

     * For example, to add a new item, do as follows:
     *

     *    getTransition().add(newItem);
     *

     *

     *

     *

     * Objects of the following type(s) are allowed in the list
     * {@link TransitionType }
     */
    public List<TransitionType> getTransition() {
        if (transition == null) {
            transition = new ArrayList<TransitionType>();
        }
        return this.transition;
    }

}


text:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="Koklu_MasterData" setup_version="1.0.0">
        <sequence>
            <module name="Magento_Catalog"/>
            <module name="Koklu_Event"/>
            <module name="Koklu_Recommender"/>
        </sequence>
    </module>
</config>


text:
title: "Data Visualization and Power of Evidence-Based Policymaking in Countries in Transition"
collection: talks
type: "Panelist"
# permalink: /talks/2016-08-02-jsm
venue: "Joint Statistical Meetings"
date: 2016-08-02
location: "Chicago, IL"
---
In this talk, I discussed the power of evidence-based approaches in addressing public policy issues in countries in transition. I presented case studies in public health, economics, and education in developing countries.


text:
<?php

namespace Ivoba\ImageExtractor\Filter;

use Ivoba\ImageExtractor\FilterInterface;

class StrPosFilter implements FilterInterface
{

    private $needles;

    function __construct(array $needles)
    {
        $this->needles = $needles;
    }

    /**
     * @inheritdoc
     */
    public function filter(array $images)
    {
        foreach ($images as $index => $img) {
            if ($this->findNeedle($img->getSrc())) {
                unset($images[$index]);
            }
        }
        return $images;
    }

    private function findNeedle($string)
    {
        foreach ($this->needles as $needle) {
            if (strpos($string, $needle) !== false) {
                return true;
            }
        }
        return false;
    }
}


text:
// $Id: ChildAxisExpr.java 96 2005-02-28 21:07:29Z blindsey $

package com.blnz.xsl.expr;

import com.blnz.xsl.om.*;

/**
 *
 */
class ChildAxisExpr extends AxisExpr
{
    public NodeIterator eval(Node node, ExprContext context)
    {
        return node.getChildren();
    }

    int getOptimizeFlags()
    {
        return STAYS_IN_SUBTREE | SINGLE_LEVEL;
    }
}


text:
package org.apache.shardingsphere.test.sql.parser.parameterized.asserts.statement.dal.impl;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.shardingsphere.sql.parser.sql.dialect.statement.mysql.dal.MySQLShowCharacterSetStatement;
import org.apache.shardingsphere.test.sql.parser.parameterized.asserts.SQLCaseAssertContext;
import org.apache.shardingsphere.test.sql.parser.parameterized.asserts.segment.show.ShowFilterAssert;
import org.apache.shardingsphere.test.sql.parser.parameterized.jaxb.cases.domain.statement.dal.ShowCharacterSetStatementTestCase;

/**
 * Show character set statement assert.
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class ShowCharacterSetStatementAssert {

    /**
     * Assert show character set statement is correct with expected parser result.
     *
     * @param assertContext assert context
     * @param actual actual show character set statement
     * @param expected expected show character set statement test case
     */
    public static void assertIs(final SQLCaseAssertContext assertContext, final MySQLShowCharacterSetStatement actual, final ShowCharacterSetStatementTestCase expected) {
        if (actual.getFilter().isPresent()) {
            ShowFilterAssert.assertIs(assertContext, actual.getFilter().get(), expected.getFilter());
        }
    }
}