// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library unittest.breath_test;

import 'dart:async';

import 'package:unittest/unittest.dart';

void main() {
  // Test the sync test 'breath' feature of unittest.

  group('breath', () {
    var sentinel = 0;
    var start;

    test('initial', () {
      Timer.run(() {
        sentinel = 1;
      });
    });

    test('starve', () {
      start = new DateTime.now().millisecondsSinceEpoch;
      var now;
      do {
        expect(sentinel, 0);
        now = new DateTime.now().millisecondsSinceEpoch;
      } while (now - start <= BREATH_INTERVAL);
    });

    test('breathed', () {
      expect(sentinel, 1);
    });
  });
}

// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library unittest.breath_test;

import 'dart:async';

import 'package:unittest/unittest.dart';

void main() {
  // Test the sync test 'breath' feature of unittest.

  // We use the testStartStopwatch to determine if the 'starve'
  // test was executed within a small enough time interval from
  // the first test that we are guaranteed the second test is
  // running in a microtask. If the second test is running as a
  // microtask we are guaranteed the timer scheduled in the
  // first test has not been run yet.
  var testStartStopwatch = new Stopwatch()..start();

  group('breath', () {
    var sentinel = 0;

    test('initial', () {
      Timer.run(() {
        sentinel = 1;
      });
    });

    test('starve', () {
      // If less than BREATH_INTERVAL time has passed since before
      // we started the test group then the previous test's timer
      // has not been run (at least this is what we are testing).
      if (testStartStopwatch.elapsed.inMilliseconds <= BREATH_INTERVAL) {
        expect(sentinel, 0);
      }

      // Next we wait for at least BREATH_INTERVAL to guaranteed the
      // next (third) test is run using a timer which means it will
      // run after the timer scheduled in the first test and hence
      // the sentinel should have been set to 1.
      var sw = new Stopwatch()..start();
      while (sw.elapsed.inMilliseconds < BREATH_INTERVAL);
    });

    test('breathed', () {
      expect(sentinel, 1);
    });
  });
}

Make the unittest's breath test a bit more resilient against timing issue.

BUG=
R=kustermann@google.com, sgjesse@google.com

Review URL: https://codereview.chromium.org//734023002

git-svn-id: b889c0189f1adfea19efba192a3d7a5b889e4120@41774 260f80e4-7a28-3924-810f-c04153c831b5


library font_awesome_flutter;

import 'package:flutter/widgets.dart';

class IconDataBrands extends IconData {
  const IconDataBrands(int codePoint)
      : super(
          codePoint,
          fontFamily: 'FontAwesomeBrands',
          fontPackage: 'font_awesome_flutter',
        );
}

class IconDataSolid extends IconData {
  const IconDataSolid(int codePoint)
      : super(
          codePoint,
          fontFamily: 'FontAwesomeSolid',
          fontPackage: 'font_awesome_flutter',
        );
}

class IconDataRegular extends IconData {
  const IconDataRegular(int codePoint)
      : super(
          codePoint,
          fontFamily: 'FontAwesomeRegular',
          fontPackage: 'font_awesome_flutter',
        );
}

// Pro only
class IconDataLight extends IconData {
  const IconDataLight(int codePoint)
      : super(
          codePoint,
          fontFamily: 'FontAwesomeLight',
          fontPackage: 'font_awesome_flutter',
        );
}

library font_awesome_flutter;

import 'package:flutter/widgets.dart';

class IconDataBrands extends IconData {
  const IconDataBrands(int codePoint)
      : super(
          codePoint,
          fontFamily: 'FontAwesomeBrands',
          fontPackage: 'font_awesome_flutter',
        );
}

class IconDataSolid extends IconData {
  const IconDataSolid(int codePoint)
      : super(
          codePoint,
          fontFamily: 'FontAwesomeSolid',
          fontPackage: 'font_awesome_flutter',
        );
}

class IconDataRegular extends IconData {
  const IconDataRegular(int codePoint)
      : super(
          codePoint,
          fontFamily: 'FontAwesomeRegular',
          fontPackage: 'font_awesome_flutter',
        );
}

// Uncomment to be able to use (pro) light icons if installed
/*
class IconDataLight extends IconData {
  const IconDataLight(int codePoint)
      : super(
          codePoint,
          fontFamily: 'FontAwesomeLight',
          fontPackage: 'font_awesome_flutter',
        );
}
*/

Comment out pro-only light icons

Comment out pro-only light icons


import 'package:flutter/widgets.dart';

abstract class Scene {
  String get title;
  Future<void> setUp() async {}
  Widget build();
}

import 'package:flutter/widgets.dart';

abstract class Scene {
  /// This Scene's name in the [StagerApp]'s list of scenes.
  String get title;

  /// Used to configure this Scene's dependencies.
  ///
  /// Analogous to StatefulWidget's `initState`, this is called once at app
  /// launch.
  Future<void> setUp() async {}

  /// Creates the widget tree for this Scene.
  ///
  /// This is called on every rebuild, including by Hot Reload.
  Widget build();
}

Add doc comments to Scene

Add doc comments to Scene


// Copyright (c) 2015, Brian G. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.

/// The dartbase_server library.
part of dartbase_server;

final GameSupervisor _gameSuper = new GameSupervisor._singleton();

class GameSupervisor {
  List<Game> _games;

  GameSupervisor._singleton() {
    log("Constructing GameSupervisor");
    _games = [];
  }

  static int newGame(Map players){
    if(_gameSuper._games.length == 0){
      log("Creating new game with player data: " + players.toString());
      Game game = new Game();
      //TODO add players
      _gameSuper._games.add(game);
    }
    log("Returning gameid: 1");

    return 1;
  }
}

// Copyright (c) 2015, Brian G. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.

/// The dartbase_server library.
part of dartbase_server;

final GameSupervisor _gameSuper = new GameSupervisor._singleton();

class GameSupervisor {
  List<Game> _games;
  final int MAX_GAMES = 2;

  GameSupervisor._singleton() {
    log("Constructing GameSupervisor");
    _games = [];
  }

  static int newGame(Map players){
    if(_gameSuper._games.length == 0){
      log("Creating new game with player data: " + players.toString());
      Game game = new Game();
      //TODO add players
      _gameSuper._games.add(game);
    }
    log("Returning gameid: 1");

    return 1;
  }
}

class WebGame {
  int gameid;
  Game game;
  final DateTime created = new DateTime.now();
  DateTime modified = new DateTime.now();

  WebGame(this.gameid, this.game);

  Map getGameData(){
    Map gameDataMap = {};

    return gameDataMap;
  }
}

Add web server game class

Add web server game class


// Copyright (c) 2013, Google Inc. Please see the AUTHORS file for details.
// All rights reserved. Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

library spark_widgets.button;

import 'package:polymer/polymer.dart';

import '../common/spark_widget.dart';

// TODO(ussuri): Add comments.

@CustomTag('spark-button')
class SparkButton extends SparkWidget {
  // [raised] is the default.
  @published bool raised;
  // [flat] is just a negation of [raised], provided for convenience.
  // It's not used in the CSS.
  @published bool flat;
  @published bool round;
  @published bool primary;
  @published bool minPadding;
  @published bool noPadding;
  @published bool disabled;
  @published bool active;

  SparkButton.created() : super.created();

  @override
  void ready() {
    super.ready();

    // Make sure at most one of [raised] or [flat] is defined by the client.
    // TODO(ussuri): This is really clumsy. Find a better way to provide
    // mutually exclusive flags.
    assert(raised == null || flat == null);
    if (flat != null) {
      raised = !flat;
    } else {
      raised = true;
    }
    deliverChanges();
  }
}

// Copyright (c) 2013, Google Inc. Please see the AUTHORS file for details.
// All rights reserved. Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

library spark_widgets.button;

import 'package:polymer/polymer.dart';

import '../common/spark_widget.dart';

// TODO(ussuri): Add comments.

@CustomTag('spark-button')
class SparkButton extends SparkWidget {
  // [raised] is the default.
  @published bool raised;
  // [flat] is just a negation of [raised], provided for convenience.
  // It's not used in the CSS.
  @published bool flat;
  @published bool round;
  @published bool primary;
  @published bool minPadding;
  @published bool noPadding;
  @published bool disabled;
  @published bool active;

  SparkButton.created() : super.created();

  @override
  void enteredView() {
    super.enteredView();

    // Make sure at most one of [raised] or [flat] is defined by the client.
    // TODO(ussuri): This is really clumsy. Find a better way to provide
    // mutually exclusive flags.
    assert(raised == null || flat == null);
    if (flat != null) {
      raised = !flat;
    } else {
      raised = true;
    }
    deliverChanges();
  }
}

Switch to a more standard place to handle/set initial attribute values


import 'package:angular/angular.dart';

@MirrorsUsed(override: '*')
import 'dart:mirrors';

import '../lib/chronos.dart';

@NgController(
    selector: "[timesheet]",
    publishAs: 'ctrl'
)
class TimesheetController {
  Timesheet timesheet = new Timesheet();
  String hours = "1";
  String description = "";
  String client = "";

  TimesheetController() {
    clearNewEntry();
  }

  clearNewEntry() {
    hours = "1";
    description = "";
  }

  addEntry() {
    timesheet.entries.add(
        new Entry(new Duration(hours: int.parse(hours, radix: 10)), description, client));
    clearNewEntry();
  }
}

@NgFilter(name: 'duration')
class DurationFilter {
  call(Duration duration) {
    return "${duration.inHours}:${duration.inMinutes}";
  }
}

class ChronosModule extends Module {
  ChronosModule() {
    type(TimesheetController);
    type(DurationFilter);
  }
}

main() => ngBootstrap(module: new ChronosModule());

import 'package:angular/angular.dart';

@MirrorsUsed(override: '*')
import 'dart:mirrors';

import '../lib/chronos.dart';

@NgController(
    selector: "[timesheet]",
    publishAs: 'ctrl'
)
class TimesheetController {
  Timesheet timesheet = new Timesheet();
  String hours = "1";
  String description = "";
  String client = "";

  TimesheetController() {
    clearNewEntry();
  }

  clearNewEntry() {
    hours = "1";
    description = "";
  }

  addEntry() {
    timesheet.entries.add(
        new Entry(new Duration(hours: int.parse(hours, radix: 10)), description, client));
    clearNewEntry();
  }
}

@NgFilter(name: 'duration')
class DurationFilter {
  call(Duration duration) {
    return "${duration.inHours}:${duration.inMinutes - (duration.inHours * 60)}";
  }
}

class ChronosModule extends Module {
  ChronosModule() {
    type(TimesheetController);
    type(DurationFilter);
  }
}

main() => ngBootstrap(module: new ChronosModule());

Handle durations longer than one hour.

Handle durations longer than one hour.


// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:analyzer/src/error/codes.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';

import '../dart/resolution/context_collection_resolution.dart';

main() {
  defineReflectiveSuite(() {
    defineReflectiveTests(PartOfDifferentLibraryTest);
  });
}

@reflectiveTest
class PartOfDifferentLibraryTest extends PubPackageResolutionTest {
  test_name() async {
    newFile('$testPackageLibPath/part.dart', "part of lub;");
    await assertErrorsInCode('''
library lib;
part 'part.dart';
''', [
      error(CompileTimeErrorCode.PART_OF_DIFFERENT_LIBRARY, 18, 11),
    ]);
  }
}

// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:analyzer/src/error/codes.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';

import '../dart/resolution/context_collection_resolution.dart';

main() {
  defineReflectiveSuite(() {
    defineReflectiveTests(PartOfDifferentLibraryTest);
  });
}

@reflectiveTest
class PartOfDifferentLibraryTest extends PubPackageResolutionTest {
  test_doesNotExist() async {
    await assertErrorsInCode('''
part 'part.dart';
''', [
      error(CompileTimeErrorCode.URI_DOES_NOT_EXIST, 5, 11),
    ]);
  }

  test_doesNotExist_generated() async {
    await assertErrorsInCode('''
part 'part.g.dart';
''', [
      error(CompileTimeErrorCode.URI_HAS_NOT_BEEN_GENERATED, 5, 13),
    ]);
  }

  test_partOfName() async {
    newFile('$testPackageLibPath/part.dart', '''
part of bar;
''');

    await assertErrorsInCode('''
library foo;
part 'part.dart';
''', [
      error(CompileTimeErrorCode.PART_OF_DIFFERENT_LIBRARY, 18, 11),
    ]);
  }

  test_partOfUri() async {
    newFile('$testPackageLibPath/part.dart', '''
part of 'other.dart';
''');

    await assertErrorsInCode('''
part 'part.dart';
''', [
      error(CompileTimeErrorCode.PART_OF_DIFFERENT_LIBRARY, 5, 11),
    ]);
  }
}

Add a few more tests for PART_OF_DIFFERENT_LIBRARY.

Change-Id: I685874502d49e4a6b4164bb25cf449423659514a
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/265180
Reviewed-by: Brian Wilkerson <1f7641b6b14c52b9163524ab8d9aabff80176f21@google.com>
Commit-Queue: Konstantin Shcheglov <09e4d7516628963212bf4aace2f97603d2b706e4@google.com>


// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// or details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

/**
 * Test date formatting and parsing using locale data read via an http request
 * to a server.
 */

library date_time_format_http_request_test;

import 'dart:async';
import 'package:intl/intl.dart';
import 'package:intl/date_symbol_data_http_request.dart';
import 'date_time_format_test_core.dart';
import 'dart:html';
import 'package:unittest/unittest.dart';
import 'package:unittest/html_config.dart';

var url = '';

main() {
  useHtmlConfiguration();
  url = "http://localhost:${window.location.port}/pkg/intl/lib/src/data/dates/";
  // Initialize one locale just so we know what the list is.
  test('Run everything', () {
    initializeDateFormatting("en_US", url).then(expectAsync1(runEverything));});
}

void runEverything(_) {
  // Initialize all locales and wait for them to finish before running tests.
  var futures = DateFormat.allLocalesWithSymbols()
      .map((locale) => initializeDateFormatting(locale, url))
      .toList();
  Future.wait(futures).then(expectAsync1((_) {
      runDateTests(smallSetOfLocales());
    }));
}

// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// or details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

/**
 * Test date formatting and parsing using locale data read via an http request
 * to a server.
 */

library date_time_format_http_request_test;

import 'dart:async';
import 'package:intl/intl.dart';
import 'package:intl/date_symbol_data_http_request.dart';
import 'date_time_format_test_core.dart';
import 'dart:html';
import 'package:unittest/unittest.dart';
import 'package:unittest/html_config.dart';

var url = '';

main() {
  useHtmlConfiguration();
  url = "http://localhost:${window.location.port}/root_dart/pkg/intl/lib/src/data/dates/";
  // Initialize one locale just so we know what the list is.
  test('Run everything', () {
    initializeDateFormatting("en_US", url).then(expectAsync1(runEverything));});
}

void runEverything(_) {
  // Initialize all locales and wait for them to finish before running tests.
  var futures = DateFormat.allLocalesWithSymbols()
      .map((locale) => initializeDateFormatting(locale, url))
      .toList();
  Future.wait(futures).then(expectAsync1((_) {
      runDateTests(smallSetOfLocales());
    }));
}

Create generated tests inside the build directory

Patch Set 1 is a revert of r18295.

Review URL: https://codereview.chromium.org//12223074

git-svn-id: a8f079e7cfc3a289d8496d7b88aabbd5c45a3053@18802 260f80e4-7a28-3924-810f-c04153c831b5


part of irc;

class WhoisBuilder {
  static final List<String> FIELDS = [
    "nickname",
    "realname",
    "hostname",
    "username",
    "away_message",
    "away",
    "channels",
    "op_in",
    "voice_in",
    "server_name",
    "server_info",
    "idle",
    "idle_time",
    "server_operator"
  ];

  final String nickname;
  String username;
  String realname;
  String hostname;
  String away_message;
  List<String> channels = [];
  List<String> voice_in = [];
  List<String> op_in = [];
  String server_name;
  String server_info;
  bool idle;
  int idle_time;
  bool server_operator;
  bool away = false;

  WhoisBuilder(this.nickname);

  @override
  String toString() {
    var sb = new StringBuffer("WHOIS(");
    for (String field in FIELDS) {
      var last = FIELDS.last == field;
      var obj = reflect(this).getField(MirrorSystem.getSymbol(field)).reflectee;
      sb
        ..write(field)
        ..write(": ")
        ..write("${obj}");
      if (!last)
        sb.write(", ");
    }
    sb.write(")");
    return sb.toString();
  }
}

part of irc;

class WhoisBuilder {
  final String nickname;
  String username;
  String realname;
  String hostname;
  String away_message;
  List<String> channels = [];
  List<String> voice_in = [];
  List<String> op_in = [];
  String server_name;
  String server_info;
  bool idle;
  int idle_time;
  bool server_operator;
  bool away = false;

  WhoisBuilder(this.nickname);

  @override
  String toString() {
    var instance = reflect(this);
    var sb = new StringBuffer("WHOIS(");
    var fields = instance.type.declarations.values.where((f) => f is VariableMirror && !f.isPrivate);
    var names = fields.map((f) => MirrorSystem.getName(f.simpleName));
    for (String field in names) {
      var last = names.last == field;
      var obj = instance.getField(MirrorSystem.getSymbol(field)).reflectee;
      sb
        ..write(field)
        ..write(": ")
        ..write("${obj}");
      if (!last)
        sb.write(", ");
    }
    sb.write(")");
    return sb.toString();
  }
}

WhoisBuilder: Remove field names storage and use introspection instead.


import '../core/parser.dart';

/// Returns a lazy iterable over all parsers reachable from a [root].
///
/// For example, the following code prints the two parsers of the
/// defined grammar:
///
///     final parser = range('0', '9').star();
///     allParser(parser).forEach((each) {
///       print(each);
///     });
///
Iterable<Parser> allParser(Parser root) sync* {
  final todo = [root];
  final seen = {root};
  while (todo.isNotEmpty) {
    final current = todo.removeLast();
    yield current;
    for (final parser in current.children) {
      if (seen.add(parser)) {
        todo.add(parser);
      }
    }
  }
}

import '../core/parser.dart';

/// Returns a lazy iterable over all parsers reachable from a [root].
///
/// For example, the following code prints the two parsers of the
/// defined grammar:
///
///     final parser = range('0', '9').star();
///     allParser(parser).forEach((each) {
///       print(each);
///     });
///
Iterable<Parser> allParser(Parser root) => _ParserIterable(root);

class _ParserIterable extends Iterable<Parser> {
  final Parser root;

  _ParserIterable(this.root);

  @override
  Iterator<Parser> get iterator => _ParserIterator(root);
}

class _ParserIterator extends Iterator<Parser> {
  final List<Parser> todo;
  final Set<Parser> seen;

  @override
  late Parser current;

  _ParserIterator(Parser root)
      : todo = [root],
        seen = {root};

  bool moveNext() {
    if (todo.isEmpty) {
      return false;
    }
    current = todo.removeLast();
    for (final parser in current.children) {
      if (seen.add(parser)) {
        todo.add(parser);
      }
    }
    return true;
  }
}

Optimize the iteration over parser graphs by creating a native iterator.


// GENERATED CODE - DO NOT MODIFY BY HAND
// 2015-03-17T09:43:06.033Z

part of uix.example.hello.main;

// **************************************************************************
// Generator: UixGenerator
// Target: class Main
// **************************************************************************

Main createMain([String data]) {
  final r = new Main()..data = data;
  return r;
}
VNode vMain({String data, Object key, String type, Map<String, String> attrs,
    Map<String, String> style, List<String> classes,
    List<VNode> children}) => new VNode.component(createMain,
    flags: VNode.componentFlag | VNode.dirtyCheckFlag,
    key: key,
    data: data,
    type: type,
    attrs: attrs,
    style: style,
    classes: classes,
    children: children);

// GENERATED CODE - DO NOT MODIFY BY HAND
// 2015-03-17T12:16:22.111Z

part of uix.example.hello.main;

// **************************************************************************
// Generator: UixGenerator
// Target: class Main
// **************************************************************************

Main createMain([String data]) {
  final r = new Main()..data = data;
  return r;
}
VNode vMain({String data, Object key, String type, Map<String, String> attrs,
    Map<String, String> style, List<String> classes,
    List<VNode> children}) => new VNode.component(createMain,
    flags: VNode.componentFlag | VNode.dirtyCheckFlag,
    key: key,
    data: data,
    type: type,
    attrs: attrs,
    style: style,
    classes: classes,
    children: children);

Add link to "Snake Game" example

Add link to "Snake Game" example


// Copyright (c) 2014, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import "dart:_internal";

patch class UserTag {
  /* patch */ factory UserTag(String label) {
    return new _UserTag(label);
  }
  /* patch */ static UserTag get defaultTag => _getDefaultTag();
}

class _UserTag implements UserTag {
  factory _UserTag(String label) native "UserTag_new";
  String get label native "UserTag_label";
  void makeCurrent() native "UserTag_makeCurrent";
}

patch UserTag getCurrentTag() => _getCurrentTag();
UserTag _getCurrentTag() native "Profiler_getCurrentTag";

UserTag _getDefaultTag() native "UserTag_defaultTag";

// Copyright (c) 2014, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import "dart:_internal";

patch class UserTag {
  /* patch */ factory UserTag(String label) {
    return new _UserTag(label);
  }
  /* patch */ static UserTag get defaultTag => _getDefaultTag();
}

class _UserTag implements UserTag {
  factory _UserTag(String label) native "UserTag_new";
  String get label native "UserTag_label";
  UserTag makeCurrent() native "UserTag_makeCurrent";
}

patch UserTag getCurrentTag() => _getCurrentTag();
UserTag _getCurrentTag() native "Profiler_getCurrentTag";

UserTag _getDefaultTag() native "UserTag_defaultTag";

Fix return value for makeCurrent

Fix return value for makeCurrent

BUG=

Review URL: https://codereview.chromium.org//279913002

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@35979 260f80e4-7a28-3924-810f-c04153c831b5


import 'dart:io';

/// Runs all test files individually.
///
/// For some reason, coverage collection times out when running them all at once
/// with null safety enabled, so this is what we have to do now.
Future<void> main() async {
  final directory = Directory('test');
  var hadFailures = false;

  await for (final entity in directory.list(recursive: true)) {
    if (entity is! File || !entity.path.endsWith('_test.dart')) continue;

    final process = await Process.start(
        '/home/simon/bin/dart-sdk/beta/bin/dart', [
      '--no-sound-null-safety',
      'run',
      'test',
      '--coverage=coverage',
      entity.path
    ]);
    await Future.wait(
        [stdout.addStream(process.stdout), stderr.addStream(process.stderr)]);

    final exitCode = await process.exitCode;
    if (exitCode != 0) {
      hadFailures = true;
    }
  }

  exit(hadFailures ? 1 : 0);
}

import 'dart:io';

/// Runs all test files individually.
///
/// For some reason, coverage collection times out when running them all at once
/// with null safety enabled, so this is what we have to do now.
Future<void> main() async {
  final directory = Directory('test');
  var hadFailures = false;

  await for (final entity in directory.list(recursive: true)) {
    if (entity is! File || !entity.path.endsWith('_test.dart')) continue;

    final process = await Process.start('dart', [
      '--no-sound-null-safety',
      'run',
      'test',
      '--coverage=coverage',
      entity.path
    ]);
    await Future.wait(
        [stdout.addStream(process.stdout), stderr.addStream(process.stderr)]);

    final exitCode = await process.exitCode;
    if (exitCode != 0) {
      hadFailures = true;
    }
  }

  exit(hadFailures ? 1 : 0);
}

Use right Dart binary for tests, ugh

Use right Dart binary for tests, ugh


part of stocksapp;

class Stocklist extends FixedHeightScrollable {
  String query;
  List<Stock> stocks;

  Stocklist({
    Object key,
    this.stocks,
    this.query
  }) : super(key: key, scrollCurve: new BoundedScrollCurve(minOffset: 0.0));

  List<Node> buildItems(int start, int count) {
    return stocks
      .skip(start)
      .where((stock) => query == null || stock.symbol.contains(
          new RegExp(query, caseSensitive: false)))
      .take(count)
      .map((stock) => new StockRow(stock: stock))
      .toList(growable: false);
  }
}

part of stocksapp;

class Stocklist extends FixedHeightScrollable {
  String query;
  List<Stock> stocks;

  Stocklist({
    Object key,
    this.stocks,
    this.query
  }) : super(key: key, scrollCurve: new OverscrollCurve());

  List<Node> buildItems(int start, int count) {
    return stocks
      .skip(start)
      .where((stock) => query == null || stock.symbol.contains(
          new RegExp(query, caseSensitive: false)))
      .take(count)
      .map((stock) => new StockRow(stock: stock))
      .toList(growable: false);
  }
}

Implement an OverscrollCurve for Scrollable

When using OverscrollCurve, we continue to scroll beyond the top of the
scrollable area but the scroll delta is reduced by 2x. A future CL will add an
animation at gesturescrollend to relax back to scroll position 0.0.

R=eseidel@chromium.org

Review URL: https://codereview.chromium.org/1002953003


part of bridge.view;

ViewResponse view(String templateName, {String withScript, List<String> withScripts}) {
  var scripts = <String>[];
  if (withScript != null) scripts.add(withScript);
  if (withScripts != null) scripts.addAll(withScripts);
  return new ViewResponse(templateName, scripts);
}

part of bridge.view;

ViewResponse template(String templateName, {String withScript, List<String> withScripts}) {
  var scripts = <String>[];
  if (withScript != null) scripts.add(withScript);
  if (withScripts != null) scripts.addAll(withScripts);
  return new ViewResponse(templateName, scripts);
}

Change view helper to template

Change view helper to template


import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:code_builder/code_builder.dart';

ReferenceBuilder toBuilder(DartType type, List<ImportElement> imports) =>
    reference(type.name, _importFrom(type, imports))
        .toTyped(_coerceTypeArgs(type, imports));

String _importFrom(DartType dartType, List<ImportElement> imports) {
  var definingLibrary = dartType.element.library;
  for (final import in imports) {
    if (_definesLibrary(import.importedLibrary, definingLibrary) &&
        // We might have some collection of show/hide that hides this symbol.
        // Easier to avoid then do this wrong, for now (b/35879283).
        import.combinators.isEmpty) {
      return import.uri;
    }
  }
  return null;
}

bool _definesLibrary(LibraryElement importedLibrary, LibraryElement library) =>
    importedLibrary == library ||
    importedLibrary.exportedLibraries
        .any((exportedLibrary) => _definesLibrary(exportedLibrary, library));

Iterable<TypeBuilder> _coerceTypeArgs(
    DartType type, List<ImportElement> imports) {
  if (type is! ParameterizedType) return const [];
  var typeArgs = (type as ParameterizedType).typeArguments;
  if (typeArgs.every((t) => t.isDynamic)) return const [];
  return typeArgs.map((type) => toBuilder(type, imports));
}

import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:code_builder/code_builder.dart';

ReferenceBuilder toBuilder(DartType type, List<ImportElement> imports) =>
    reference(type.name, _importFrom(type, imports))
        .toTyped(_coerceTypeArgs(type, imports));

String _importFrom(DartType dartType, List<ImportElement> imports) {
  for (final import in imports) {
    final exportedElement =
        import.importedLibrary.exportNamespace?.get(dartType.element.name);
    if (exportedElement == dartType.element) {
      return import.uri;
    }
  }
  return null;
}

Iterable<TypeBuilder> _coerceTypeArgs(
    DartType type, List<ImportElement> imports) {
  if (type is! ParameterizedType) return const [];
  var typeArgs = (type as ParameterizedType).typeArguments;
  if (typeArgs.every((t) => t.isDynamic)) return const [];
  return typeArgs.map((type) => toBuilder(type, imports));
}

SourceGen: Replace manual searching through imports/exports with LibraryElement.exportNamespace.

The analyzer already determines which elements are visible from a library, and exposes that information via the namespace, so we don't need to do a recursive search ourselves.

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=152160527


// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:newton/newton.dart';
import 'package:sky/animation/direction.dart';

// Base class for creating Simulations for the animation Timeline.
abstract class Force {
  Simulation release(double position, double velocity, Direction direction);
}

class SpringForce extends Force {
  SpringForce(this.spring, {this.left: 0.0, this.right: 1.0});

  final SpringDescription spring;
  // Where to put the spring's resting point when releasing left or right,
  // respectively.
  final double left, right;

  Simulation release(double position, double velocity, Direction direction) {
    // Target just past the endpoint, because the animation will stop once the
    // Spring gets within the epsilon, and we want to stop at the endpoint.
    double target = direction == Direction.reverse ?
        this.left - _kEpsilon : this.right + _kEpsilon;
    return new SpringSimulation(spring, position, target, velocity);
  }
}

final SpringDescription _kDefaultSpringDesc =
    new SpringDescription.withDampingRatio(mass: 1.0, springConstant: 500.0, ratio: 1.0);
final SpringForce kDefaultSpringForce = new SpringForce(_kDefaultSpringDesc);

const double _kEpsilon = 0.001;

// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:newton/newton.dart';
import 'package:sky/animation/direction.dart';

// Base class for creating Simulations for the animation Timeline.
abstract class Force {
  Simulation release(double position, double velocity, Direction direction);
}

class SpringForce extends Force {
  SpringForce(this.spring, {this.left: 0.0, this.right: 1.0});

  // We overshoot the target by this distance, but stop the simulation when
  // the spring gets within this distance (regardless of how fast it's moving).
  // This causes the spring to settle a bit faster than it otherwise would.
  static final Tolerance tolerance =
      new Tolerance(velocity: double.INFINITY, distance: 0.01);

  final SpringDescription spring;
  // Where to put the spring's resting point when releasing left or right,
  // respectively.
  final double left, right;

  Simulation release(double position, double velocity, Direction direction) {
    double target = direction == Direction.reverse ?
        this.left - tolerance.distance : this.right + tolerance.distance;
    return new SpringSimulation(spring, position, target, velocity)
      ..tolerance = tolerance;
  }
}

final SpringDescription _kDefaultSpringDesc =
    new SpringDescription.withDampingRatio(mass: 1.0, springConstant: 500.0, ratio: 1.0);
final SpringForce kDefaultSpringForce = new SpringForce(_kDefaultSpringDesc);

Adjust the SpringForce tolerance, used by Drawer and Dismissable.

They settle much faster after you fling them now.


// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:sky/widgets/basic.dart';
import 'package:sky/widgets/navigator.dart';
import 'package:sky/widgets/widget.dart';

import 'stock_home.dart';
import 'stock_settings.dart';

class StocksApp extends App {
  Widget build() {
    return new Navigator(
      routes: [
        new Route(
          name: '/',
          builder: (navigator) => new StockHome(navigator)
        ),
        new Route(
          name: '/settings',
          builder: (navigator) => new StockSettings(navigator)
        ),
      ]
    );
  }
}

void main() {
  print("starting stocks app!");
  App app = new StocksApp();
  WidgetAppView.appView.onFrame = () {
    // uncomment this for debugging:
    // WidgetAppView.appView.debugDumpRenderTree();
  };
}

// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:sky/rendering/box.dart';
import 'package:sky/widgets/basic.dart';
import 'package:sky/widgets/navigator.dart';
import 'package:sky/widgets/widget.dart';

import 'stock_home.dart';
import 'stock_settings.dart';

class StocksApp extends App {

  StocksApp({ RenderView renderViewOverride }) : super(renderViewOverride: renderViewOverride);

  Widget build() {
    return new Navigator(
      routes: [
        new Route(
          name: '/',
          builder: (navigator) => new StockHome(navigator)
        ),
        new Route(
          name: '/settings',
          builder: (navigator) => new StockSettings(navigator)
        ),
      ]
    );
  }
}

void main() {
  print("starting stocks app!");
  App app = new StocksApp();
  WidgetAppView.appView.onFrame = () {
    // uncomment this for debugging:
    // WidgetAppView.appView.debugDumpRenderTree();
  };
}

Enable render view override for stocks app to enable testing

This fixes the test

TBR=abarth

Review URL: https://codereview.chromium.org/1192533002.


// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#import("dart:io");

main() {
  Expect.isTrue(Platform.numberOfProcessors > 0);
  var os = Platform.operatingSystem;
  Expect.isTrue(os == "linux" || os == "macos" || os == "windows");
  var sep = Platform.pathSeparator;
  Expect.isTrue(sep == '/' || (os == 'windows' && sep == '\\'));
  var hostname = Platform.localHostname;
  Expect.isTrue(hostname is String && hostname != "");
  var environment = Platform.environment;
  Expect.isTrue(environment is Map<String, String>);
}

// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#import("dart:io");

main() {
  Expect.isTrue(Platform.numberOfProcessors > 0);
  var os = Platform.operatingSystem;
  Expect.isTrue(os == "android" || os == "linux" || os == "macos" ||
      os == "windows");
  var sep = Platform.pathSeparator;
  Expect.isTrue(sep == '/' || (os == 'windows' && sep == '\\'));
  var hostname = Platform.localHostname;
  Expect.isTrue(hostname is String && hostname != "");
  var environment = Platform.environment;
  Expect.isTrue(environment is Map<String, String>);
}

Add "android" as an expected OS target.

Add "android" as an expected OS target.

Enables this test to pass when run on Android.

BUG=

Review URL: https://chromiumcodereview.appspot.com//10828231

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@10590 260f80e4-7a28-3924-810f-c04153c831b5


// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Test comparison of this and a constant.

class Foo {
  static final C1 = const Foo('C1');
  static final C2 = const Foo('C2');
  static final C3 = const Foo('C3');

  var name;
  const Foo(this.name);

  foo() {
    switch (this) {
      case C1: return C1;
      case C2: return C2;
      default: return null;
    }
  }
}

main() {
  Expect.equals(Foo.C1, Foo.C1.foo());
  Expect.equals(Foo.C2, Foo.C2.foo());
  Expect.equals(null, Foo.C3.foo());
}

// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Test comparison of this and a constant.

class Foo {
  static final C1 = const Foo('C1');
  static final C2 = const Foo('C2');
  static final C3 = const Foo('C3');

  final name;
  const Foo(this.name);

  foo() {
    switch (this) {
      case C1: return C1;
      case C2: return C2;
      default: return null;
    }
  }
}

main() {
  Expect.equals(Foo.C1, Foo.C1.foo());
  Expect.equals(Foo.C2, Foo.C2.foo());
  Expect.equals(null, Foo.C3.foo());
}

Make field final in const class.

Make field final in const class.

TBR=ager@google.com

Review URL: https://chromiumcodereview.appspot.com//10446011

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@7947 260f80e4-7a28-3924-810f-c04153c831b5


part of kafka.common;

/// Represents single node in a Kafka cluster.
class Broker {
  /// Unique ID of this broker within cluster.
  final int id;

  /// Host name or IP address of this broker.
  final String host;

  /// Port number of this broker.
  final int port;

  static final Map<String, Broker> _instances = new Map();

  /// Creates new instance of Kafka broker.
  factory Broker(int id, String host, int port) {
    var key = '${host}:${port}';
    if (!_instances.containsKey(key)) {
      _instances[key] = new Broker._(id, host, port);
    } else {
      if (_instances[key].id != id) throw new StateError('Broker ID mismatch.');
    }

    return _instances[key];
  }

  Broker._(this.id, this.host, this.port);
}

class TopicPartition {
  final String topicName;
  final int partitionId;

  static final Map<String, TopicPartition> _cache = new Map();

  TopicPartition._(this.topicName, this.partitionId);

  factory TopicPartition(String topicName, int partitionId) {
    var key = topicName + partitionId.toString();
    if (!_cache.containsKey(key)) {
      _cache[key] = new TopicPartition._(topicName, partitionId);
    }

    return _cache[key];
  }

  @override
  bool operator ==(TopicPartition other) {
    return (other.topicName == topicName && other.partitionId == partitionId);
  }

  @override
  int hashCode() {
    return (topicName + partitionId.toString()).hashCode;
  }
}

part of kafka.common;

/// Represents single node in a Kafka cluster.
class Broker {
  /// Unique ID of this broker within cluster.
  final int id;

  /// Host name or IP address of this broker.
  final String host;

  /// Port number of this broker.
  final int port;

  static final Map<String, Broker> _instances = new Map();

  /// Creates new instance of Kafka broker.
  factory Broker(int id, String host, int port) {
    var key = '${host}:${port}';
    if (!_instances.containsKey(key)) {
      _instances[key] = new Broker._(id, host, port);
    } else {
      if (_instances[key].id != id) throw new StateError('Broker ID mismatch.');
    }

    return _instances[key];
  }

  Broker._(this.id, this.host, this.port);
}

class TopicPartition {
  final String topicName;
  final int partitionId;

  static final Map<String, TopicPartition> _cache = new Map();

  TopicPartition._(this.topicName, this.partitionId);

  factory TopicPartition(String topicName, int partitionId) {
    var key = topicName + partitionId.toString();
    if (!_cache.containsKey(key)) {
      _cache[key] = new TopicPartition._(topicName, partitionId);
    }

    return _cache[key];
  }

  @override
  bool operator ==(TopicPartition other) {
    return (other.topicName == topicName && other.partitionId == partitionId);
  }

  @override
  int get hashCode => (topicName + partitionId.toString()).hashCode;
}

Fix for hasCode to be a getter instead of regular method in TopicPartition


// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:html';

import 'package:angular/angular.dart';
import 'package:angular_components/material_button/material_button_base.dart';
import 'package:angular_components/material_ripple/material_ripple.dart';
import 'package:angular_components/material_tab/tab_mixin.dart';

/// A specialized button component used only by the tab strip.
@Component(
  selector: 'tab-button',
  template: r'''
          <div class="content">
            {{label}}
          </div>
          <material-ripple></material-ripple>
        ''',
  styleUrls: ['tab_button.scss.css'],
  directives: [MaterialRippleComponent],
)
class TabButtonComponent extends MaterialButtonBase with TabMixin {
  final Element _nativeElement;

  TabButtonComponent(this._nativeElement) : super(_nativeElement, 'tab');

  @override
  Element get nativeElement => _nativeElement;

  /// Whether the tab represented by this button is currently active.
  @Input('active')
  bool isActive = false;

  @HostBinding('class.focus')
  bool get hostClassFocus => visualFocus;

  @HostBinding('class.active')
  bool get hostClassActive => isActive || isMouseDown;

  @HostBinding('attr.disabled')
  String get hostDisabled => disabled ? "" : null;
}

// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:html';

import 'package:angular/angular.dart';
import 'package:angular_components/material_button/material_button_base.dart';
import 'package:angular_components/material_ripple/material_ripple.dart';
import 'package:angular_components/material_tab/tab_mixin.dart';

/// A specialized button component used only by the tab strip.
@Component(
  selector: 'tab-button',
  template: r'''
          <div class="content">
            {{label}}
          </div>
          <material-ripple></material-ripple>
        ''',
  styleUrls: ['tab_button.scss.css'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  directives: [MaterialRippleComponent],
)
class TabButtonComponent extends MaterialButtonBase with TabMixin {
  final Element _nativeElement;

  TabButtonComponent(this._nativeElement) : super(_nativeElement, 'tab');

  @override
  Element get nativeElement => _nativeElement;

  /// Whether the tab represented by this button is currently active.
  @Input('active')
  bool isActive = false;

  @HostBinding('class.focus')
  bool get hostClassFocus => visualFocus;

  @HostBinding('class.active')
  bool get hostClassActive => isActive || isMouseDown;

  @HostBinding('attr.disabled')
  String get hostDisabled => disabled ? "" : null;
}

Change TabButton to be OnPush as it is used in an OnPush context, and there is no reason why it can't be OnPush.

PiperOrigin-RevId: 242756270


/// Creates a symlink to the reflectable package next to this package.
import "dart:io";

void main(List<String> args) {
  String projectRoot = args[0];
  // If projectRoot is relative we want to make it absolute, so the link
  // will be to an absolute location.
  Uri currentPathUri = new Uri.file(Directory.current.path +
                                    Platform.pathSeparator);
  Uri projectRootUri = currentPathUri.resolve(projectRoot);
  Uri reflectableLocation = projectRootUri.resolve(
      "../../../../../dart/third_party/pkg/reflectable/reflectable");
  Uri destination = projectRootUri.resolve("../reflectable/reflectable");
  print("Making a link to ${reflectableLocation.toFilePath()} "
        "at ${destination.toFilePath()}");
  new Link.fromUri(destination).create(reflectableLocation.toFilePath());
}

/// Creates a symlink to the reflectable package next to this package.
import "dart:io";

void main(List<String> args) {
  String projectRoot = args[0];
  // If projectRoot is relative we want to make it absolute, so the link
  // will be to an absolute location.
  Uri currentPathUri = new Uri.file(Directory.current.path +
                                    Platform.pathSeparator);
  Uri projectRootUri = currentPathUri.resolve(projectRoot);
  Uri reflectableLocation = projectRootUri.resolve(
      "../../../../../dart/third_party/pkg/reflectable/reflectable");
  Uri destination = projectRootUri.resolve("../reflectable/reflectable");
  print("Making a link to ${reflectableLocation.toFilePath()} "
        "at ${destination.toFilePath()}");
  bool exists = new Directory(reflectableLocation.toFilePath()).existsSync();
  print("Target exists: $exists");
  new Link.fromUri(destination).create(reflectableLocation.toFilePath());
}

Add diagnostic to see if the target of the created link exists.

BUG=
R=eernst@google.com

Review URL: https://codereview.chromium.org/1216213002.


import 'package:ddays/task.dart';
import "package:test/test.dart";

void main() {
  test('task gets initialised correctly', () {
    var t1 = new Task('task1',null);
    expect(t1.summary, 'task1');
    var t2 = new Task('task2', new DateTime(2015,1,1));
    expect(t2.scheduled.month, 1);
  });
  test('addNote should add notes to tasknotes list.', () {
    var t1 = new Task('task1', null);
    t1.addNote('first note');
    expect(t1.tasknotes[0], 'first note');
  });

}

import 'package:ddays/task.dart';
import "package:test/test.dart";

void main() {
  test('task gets initialised correctly', () {
    var t1 = new Task('task1',null);
    expect(t1.summary, 'task1');
    var t2 = new Task('task2', new DateTime(2015,1,1));
    expect(t2.scheduled.month, 1);
  });
  test('addNote should add notes to tasknotes list.', () {
    var t1 = new Task('task1', null);
       var n1 = new TaskNote('first note');
       t1.addNote(n1);
       expect(t1.tasknotes[0].notebody, 'first note');
  });

}

Refactor test for addNote function.

Refactor test for addNote function.


// Copyright (c) 2014, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
//
// Test write barrier verification mode.
// VMOptions=--verified_mem --verify_before_gc --verify_after_gc

var a = [];

void main() {
  for (int i = 0; i < 123; ++i) {
    a.add(new List(12345));
  }
  for (int i = 0; i < 12345; ++i) {
    a[0] = new List(100000);
  }
}

// Copyright (c) 2014, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
//
// Test write barrier verification mode.
// VMOptions=--verified_mem --verify_before_gc --verify_after_gc

var a = [];

void main() {
  for (int i = 0; i < 123; ++i) {
    a.add(new List(12345));
  }
  for (int i = 0; i < 1234; ++i) {
    a[0] = new List(100000);
  }
}

Decrease size of test of write barrier verification.

It was close to timing out on Linux, and failing on Windows, likely due to OOM.

TBR=iposva@google.com

Review URL: https://codereview.chromium.org//723893002

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@41702 260f80e4-7a28-3924-810f-c04153c831b5


part of hop_runner;

Map<String, dynamic> config;

Directory get tool_dir => new File.fromUri(Platform.script).parent.absolute;
Directory get root_dir => tool_dir.parent;

Map<String, dynamic> load_config() => loadYaml(new File("${tool_dir.path}/build.yaml").readAsStringSync());

Map<String, dynamic> variables = {
  "tool_dir": tool_dir.path,
  "root_dir": root_dir.path
};

String parse_config_value(String input) {
  var out = input;
  for (var variable in variables.keys) {
    out = out.replaceAll("{${variable}}", variables[variable]);
  }
  return out;
}

dynamic getvar(String path, [dynamic defaultValue = false]) {
  var current = config;

  if (current.containsKey(path)) {
    return current[path];
  }

  var parts = path.split(r"\.");
  for (var part in parts) {
    if (current == null) {
      return null;
    }
    current = current[part];
  }
  if (current is String) {
    current = parse_config_value(current);
  }
  return current;
}

void init() {
  Directory.current = root_dir;
  config = load_config();
}

part of hop_runner;

Map<String, dynamic> config;

Directory get tool_dir => new File.fromUri(Platform.script).parent.absolute;
Directory get root_dir => tool_dir.parent;

Map<String, dynamic> load_config() {
  var it = loadYaml(new File("${tool_dir.path}/build.yaml").readAsStringSync());
  if (it.containsKey("variables")) {
    variables.addAll(it["variables"]);
  }
  return it;
}

Map<String, dynamic> variables = {
  "tool_dir": tool_dir.path,
  "root_dir": root_dir.path
};

String parse_config_value(String input) {
  var out = input;
  for (var variable in variables.keys) {
    out = out.replaceAll("{${variable}}", variables[variable]);
  }
  return out;
}

dynamic getvar(String path, [dynamic defaultValue = false]) {
  var current = config;

  if (current.containsKey(path)) {
    return current[path];
  }

  var parts = path.split(r"\.");
  for (var part in parts) {
    if (current == null) {
      return null;
    }
    current = current[part];
  }
  if (current is String) {
    current = parse_config_value(current);
  }
  return current;
}

void init() {
  Directory.current = root_dir;
  config = load_config();
}

Add Variables Support in Configuration

Build: Add Variables Support in Configuration


part of darwin;

class Generation<T extends Phenotype> {
  List<T> members = new List<T>();

  /**
   * Filters the generation to phenotypes that are similar to [ph] as defined
   * by their Hamming distance being less than [radius].
   *
   * This _includes_ the original [ph] (Because [ph]'s Hamming distance to
   * itself is [:0:].)
   */
  Iterable<T> getSimilarPhenotypes(T ph, num radius) {
    return members
        .where((T candidate) => ph.computeHammingDistance(candidate) < radius);
  }

  num cummulativeFitness;
  num get averageFitness {
    if (cummulativeFitness == null) return null;
    return cummulativeFitness / members.length;
  }
  num bestFitness;

  /**
   * Computes [cummulativeFitness] and [bestFitness], assuming all members of
   * the population are scored.
   */
  void computeSummary() {
    cummulativeFitness = 0;
    bestFitness = double.INFINITY;
    members.forEach((T ph) {
      cummulativeFitness += ph.result;
      if (ph.result < bestFitness) bestFitness = ph.result;
    });
  }
}

part of darwin;

class Generation<T extends Phenotype> {
  List<T> members = new List<T>();

  /**
   * Filters the generation to phenotypes that are similar to [ph] as defined
   * by their Hamming distance being less than [radius].
   *
   * This _includes_ the original [ph] (Because [ph]'s Hamming distance to
   * itself is [:0:].)
   */
  Iterable<T> getSimilarPhenotypes(T ph, num radius) {
    return members
        .where((T candidate) => ph.computeHammingDistance(candidate) < radius);
  }

  num cummulativeFitness;
  num get averageFitness {
    if (cummulativeFitness == null) return null;
    return cummulativeFitness / members.length;
  }
  num bestFitness;

  /**
   * Computes [cummulativeFitness] and [bestFitness], assuming all members of
   * the population are scored.
   */
  void computeSummary() {
    cummulativeFitness = 0;
    bestFitness = double.INFINITY;
    members.forEach((T ph) {
      cummulativeFitness += ph.result;
      if (ph.result < bestFitness) {
        bestFitness = ph.result;
        best = ph;
      }
    });
  }

  T best;
}

Add best phenotype to Generation as a field


// Copyright (c) 2019, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

part of dart.ffi;

/// This class is extended to define structs.
///
/// Fields in a struct, annotated with a subtype of [NativeType], are
/// automatically transformed into wrappers to access the fields of the struct
/// in native memory.
///
/// All fields in a struct must either have a type which extends [NativeType] or
/// else have an annotation indicating the corresponding native type (e.g.
/// "@Int32()" for "int").
///
/// Instances of a subclass of [Struct] have reference semantics and are backed
/// by native memory. The may allocated via allocation or loaded from a
/// [Pointer], but not by a generative constructor.
abstract class Struct extends NativeType {
  final Pointer<Struct> _addressOf;

  /// Construct a reference to the [nullptr].
  ///
  /// Use [StructPointer]'s `.ref` to gain references to native memory backed
  /// structs.
  Struct() : _addressOf = nullptr;

  Struct._fromPointer(this._addressOf);
}

/// Extension on [Struct] specialized for it's subtypes.
extension StructAddressOf<T extends Struct> on T {
  /// Returns the address backing the reference.
  Pointer<T> get addressOf => _addressOf as Pointer<T>;
}

// Copyright (c) 2019, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

part of dart.ffi;

/// This class is extended to define structs.
///
/// Fields in a struct, annotated with a subtype of [NativeType], are
/// automatically transformed into wrappers to access the fields of the struct
/// in native memory.
///
/// All fields in a struct must either have a type which extends [NativeType] or
/// else have an annotation indicating the corresponding native type (e.g.
/// "@Int32()" for "int").
///
/// Instances of a subclass of [Struct] have reference semantics and are backed
/// by native memory. The may allocated via allocation or loaded from a
/// [Pointer], but not by a generative constructor.
abstract class Struct extends NativeType {
  final Pointer<Struct> _addressOf;

  /// Construct a reference to the [nullptr].
  ///
  /// Use [StructPointer]'s `.ref` to gain references to native memory backed
  /// structs.
  Struct() : _addressOf = nullptr;

  Struct._fromPointer(this._addressOf);
}

/// Extension on [Struct] specialized for its subtypes.
extension StructAddressOf<T extends Struct> on T {
  /// Returns the address backing the reference.
  Pointer<T> get addressOf => _addressOf as Pointer<T>;
}

Fix spelling in ffi documentation

[vm/ffi] Fix spelling in ffi documentation

Fix spelling nit (it's -> its).

Closes https://github.com/dart-lang/sdk/pull/43483
https://github.com/dart-lang/sdk/pull/43483

GitOrigin-RevId: 5bc63e70f3846b131ea25dcdb81c6a66929f995b
Change-Id: I13d3a42896412d1111e9b9882911ade8bb7623a1
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/163362
Reviewed-by: Daco Harkes <930cbae0ca77f1954c53e32620d89cfcca318f00@google.com>
Commit-Queue: Daco Harkes <930cbae0ca77f1954c53e32620d89cfcca318f00@google.com>


// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

enum IconThemeColor { white, black }

class IconThemeData {
  const IconThemeData({ this.color });
  final IconThemeColor color;

  bool operator ==(dynamic other) {
    if (other is! IconThemeData)
      return false;
    final IconThemeData typedOther = other;
    return color == typedOther;
  }

  int get hashCode => color.hashCode;

  String toString() => '$color';
}

// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

enum IconThemeColor { white, black }

class IconThemeData {
  const IconThemeData({ this.color });
  final IconThemeColor color;

  bool operator ==(dynamic other) {
    if (other is! IconThemeData)
      return false;
    final IconThemeData typedOther = other;
    return color == typedOther.color;
  }

  int get hashCode => color.hashCode;

  String toString() => '$color';
}

Fix a type mismatch in IconThemeData.operator==


import 'dart:html';
import 'package:angular2/core.dart';
import 'package:intl/intl.dart';

@Component(
  selector: 'datepicker',
  templateUrl: 'datepicker_component.html',
  styleUrls: const['datepicker_component.css']
)

class DatepickerComponent implements OnInit{

  @Input() String componentId;

  String datepickerId;
  String initialDate;
  DateFormat dateFormat = new DateFormat("yyyy-MM-dd");
  bool hidden = true;

  @override
  void ngOnInit() {
    datepickerId = componentId+"-datepicker";
    var now = new DateTime.now();
    initialDate = dateFormat.format(now);
  }

  void toggleDatepicker() {
    if (hidden) {
      showDatepicker();
    } else {
      hideDatepicker();
    }
  }

  void showDatepicker() {
    document.getElementById(datepickerId).classes.remove("hide");
    hidden = false;
    document.getElementById(componentId).querySelector("input").focus();
  }

  void hideDatepicker() {
    document.getElementById(datepickerId).classes.add("hide");
    hidden = true;
  }

}

import 'dart:html';
import 'package:angular2/core.dart';
import 'package:intl/intl.dart';
import 'day_component.dart';

@Component(
  selector: 'datepicker',
  templateUrl: 'datepicker_component.html',
  styleUrls: const['datepicker_component.css'],
  directives: const[DayComponent]
)

class DatepickerComponent implements OnInit, AfterContentInit, AfterViewInit{

  @Input() String componentId;

  String datepickerId;
  String initialDate;
  DateFormat dateFormat = new DateFormat("yyyy-MM-dd");
  bool hidden = true;
  InputElement inputDate;

  ElementRef _elementRef;
  Element hostElement;

  @ViewChildren(DayComponent) List<DayComponent> dayList;

  DatepickerComponent(this._elementRef);

  @override
  void ngOnInit() {
    datepickerId = componentId+"-datepicker";
    var now = new DateTime.now();
    initialDate = dateFormat.format(now);
  }

  @override
  void ngAfterContentInit() {
    hostElement = _elementRef.nativeElement;
    inputDate = hostElement.querySelector('input') as InputElement;
  }

  @override
  void ngAfterViewInit() {
    for (var day in dayList) {
      day.hostElement.onClick.listen((event) => dateClickListener(day, event));
    }
  }

  void dateClickListener(DayComponent currentDay, Event event) {
    for (var day in dayList) {
      if (day.isSelected) {
        day.deselect();
        break;
      }
    }
    currentDay.select();
    inputDate.value = dateFormat.format(currentDay.date);
  }

  void toggleDatepicker() {
    if (hidden) {
      showDatepicker();
    } else {
      hideDatepicker();
    }
  }

  void showDatepicker() {
    hostElement.querySelector("#$datepickerId").classes.remove("hide");
    hidden = false;
    inputDate.focus();
  }

  void hideDatepicker() {
    hostElement.querySelector("#$datepickerId").classes.add("hide");
    hidden = true;
  }

}

Add click listener to day module.

Add click listener to day module.


import '../enums/attribute_type.dart';
import '../utils/token.dart';

/// Immutable external ID .
class DtdExternalId {
  DtdExternalId.public(String this.publicId, XmlAttributeType this.publicIdType,
      this.systemId, this.systemIdType);

  DtdExternalId.system(this.systemId, this.systemIdType)
      : publicId = null,
        publicIdType = null;

  /// The public identifier for the external subset of the document type
  /// definition. This is a string, or `null`.
  final String? publicId;

  final XmlAttributeType? publicIdType;

  /// The system identifier for the external subset of the document type
  /// definition. This is a URI as a string, or `null`.
  final String systemId;

  final XmlAttributeType systemIdType;

  @override
  String toString() {
    final buffer = StringBuffer();
    if (publicId != null) {
      buffer.write(XmlToken.doctypePublicId);
      buffer.write(XmlToken.whitespace);
      buffer.write(publicIdType!.token);
      buffer.write(publicId);
      buffer.write(publicIdType!.token);
    } else {
      buffer.write(XmlToken.doctypeSystemId);
    }
    buffer.write(XmlToken.whitespace);
    buffer.write(systemIdType.token);
    buffer.write(systemId);
    buffer.write(systemIdType.token);
    return buffer.toString();
  }

  @override
  int get hashCode => Object.hash(systemId, publicId);

  @override
  bool operator ==(Object other) =>
      other is DtdExternalId &&
      other.publicId == other.publicId &&
      other.systemId == other.systemId;
}

import '../enums/attribute_type.dart';
import '../utils/token.dart';

/// Immutable external ID.
class DtdExternalId {
  DtdExternalId.public(String this.publicId, XmlAttributeType this.publicIdType,
      this.systemId, this.systemIdType);

  DtdExternalId.system(this.systemId, this.systemIdType)
      : publicId = null,
        publicIdType = null;

  /// The public identifier for the external subset of the document type
  /// definition. This is a string, or `null`.
  final String? publicId;

  final XmlAttributeType? publicIdType;

  /// The system identifier for the external subset of the document type
  /// definition. This is a URI as a string, or `null`.
  final String systemId;

  final XmlAttributeType systemIdType;

  @override
  String toString() {
    final buffer = StringBuffer();
    if (publicId != null) {
      buffer.write(XmlToken.doctypePublicId);
      buffer.write(XmlToken.whitespace);
      buffer.write(publicIdType!.token);
      buffer.write(publicId);
      buffer.write(publicIdType!.token);
    } else {
      buffer.write(XmlToken.doctypeSystemId);
    }
    buffer.write(XmlToken.whitespace);
    buffer.write(systemIdType.token);
    buffer.write(systemId);
    buffer.write(systemIdType.token);
    return buffer.toString();
  }

  @override
  int get hashCode => Object.hash(systemId, publicId);

  @override
  bool operator ==(Object other) =>
      other is DtdExternalId &&
      other.publicId == other.publicId &&
      other.systemId == other.systemId;
}

Fix comment of External ID.

Fix comment of External ID.


import 'dart:async';

import 'dart_doc_syncer.dart' as syncer;

final examplesToSync = <List<String>>[
  <String>[
    'public/docs/_examples/template-syntax/dart',
    'git@github.com:angular-examples/template-syntax.git'
  ]
];

/// Syncs all angular.io example applications.
Future main(List<String> args) async {
  for (List<String> example in examplesToSync) {
    await syncer.main(example..addAll(args));
  }
}

import 'dart:async';

import 'package:dart_doc_syncer/documentation_updater.dart';

/// Syncs all angular.io example applications.
Future main() async {
  for (List<String> example in _examplesToSync) {
    try {
      final documentation = new DocumentationUpdater();
      await documentation.updateRepository(example[0], example[1]);
    } catch (e, stacktrace) {
      print('Error: $e, \nCause: $stacktrace');
    }
  }
}

final _examplesToSync = <List<String>>[
  <String>[
    'public/docs/_examples/template-syntax/dart',
    'git@github.com:angular-examples/template-syntax.git'
  ],
  <String>[
    'public/docs/_examples/pipes/dart',
    'git@github.com:angular-examples/pipes.git'
  ],
  <String>[
    'public/docs/_examples/server-communication/dart',
    'git@github.com:angular-examples/server-communication.git'
  ],
  <String>[
    'public/docs/_examples/quickstart/dart',
    'git@github.com:angular-examples/quickstart.git'
  ],
  <String>[
    'public/docs/_examples/displaying-data/dart',
    'git@github.com:angular-examples/displaying-data.git'
  ],
  <String>[
    'public/docs/_examples/forms/dart',
    'git@github.com:angular-examples/forms.git'
  ],
  <String>[
    'public/docs/_examples/hierarchical-dependency-injection/dart',
    'git@github.com:angular-examples/hierarchical-dependency-injection.git'
  ],
  <String>[
    'public/docs/_examples/dependency-injection/dart',
    'git@github.com:angular-examples/dependency-injection.git'
  ],
  <String>[
    'public/docs/_examples/attribute-directives/dart',
    'git@github.com:angular-examples/attribute-directives.git'
  ],
  <String>[
    'public/docs/_examples/architecture/dart',
    'git@github.com:angular-examples/architecture.git'
  ],
];

Add more repositories to sync.

Add more repositories to sync.


part of stream_transformers;

Stream _bindStream({Stream like, StreamSubscription onListen(EventSink sink), onCancel()}) {
  StreamSubscription subscription;
  StreamController controller;

  controller = _createControllerLikeStream(
      stream: like,
      onListen: () => subscription = onListen(controller),
      onPause: () => subscription.pause(),
      onResume: () => subscription.resume(),
      onCancel: () {
        var futures = [onCancel, subscription.cancel]
            .where((function) => function != null)
            .map((function) => function())
            .where((future) => future != null);
        return Future.wait(futures);
      });

  return controller.stream;
}

StreamController _createControllerLikeStream({Stream stream, void onListen(), void onCancel(), void onPause(), void onResume()}) {
  if (stream == null || !stream.isBroadcast) {
    return new StreamController(onListen: onListen, onCancel: onCancel, onPause: onPause, onResume: onResume);
  } else {
    return new StreamController.broadcast(onListen: onListen, onCancel: onCancel);
  }
}

Future _cancelSubscriptions(Iterable<StreamSubscription> subscriptions) {
  var futures = subscriptions
      .map((subscription) => subscription.cancel())
      .where((future) => future != null);
  return Future.wait(futures);
}

part of stream_transformers;

Stream _bindStream({Stream like, StreamSubscription onListen(EventSink sink), onCancel(), bool sync: false}) {
  StreamSubscription subscription;
  StreamController controller;

  controller = _createControllerLikeStream(
      stream: like,
      sync: sync,
      onListen: () => subscription = onListen(controller),
      onPause: () => subscription.pause(),
      onResume: () => subscription.resume(),
      onCancel: () {
        var futures = [onCancel, subscription.cancel]
            .where((function) => function != null)
            .map((function) => function())
            .where((future) => future != null);
        return Future.wait(futures);
      });

  return controller.stream;
}

StreamController _createControllerLikeStream({Stream stream, void onListen(), void onCancel(), void onPause(), void onResume(), bool sync: false}) {
  if (stream == null || !stream.isBroadcast) {
    return new StreamController(onListen: onListen, onCancel: onCancel, onPause: onPause, onResume: onResume, sync: sync);
  } else {
    return new StreamController.broadcast(onListen: onListen, onCancel: onCancel, sync: sync);
  }
}

Future _cancelSubscriptions(Iterable<StreamSubscription> subscriptions) {
  var futures = subscriptions
      .map((subscription) => subscription.cancel())
      .where((future) => future != null);
  return Future.wait(futures);
}

Allow creation of sync streams from internal stream factories


// Copyright (c) 2015, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:io';
import 'dart:mirrors';
import 'package:lookup_map/lookup_map.dart'; // accessed via mirrors;
import 'package:test/test.dart';
import 'package:yaml/yaml.dart';

/// This dartdoc helps remove a warning for the unused import on [LookupMap].
main() {
  test('validate version number matches', () {
    var pubspecPath = Platform.script.resolve('../pubspec.yaml').path;
    var yaml = loadYaml(new File(pubspecPath).readAsStringSync());
    var version1 = yaml['version'];
    var library = currentMirrorSystem().findLibrary(#lookup_map);
    var version2 = library.getField(new Symbol('_version')).reflectee;
    expect(version1, version2);
  });
}

// Copyright (c) 2015, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:io';
import 'dart:mirrors';
import 'package:lookup_map/lookup_map.dart'; // accessed via mirrors;
import 'package:test/test.dart';
import 'package:yaml/yaml.dart';

/// This dartdoc helps remove a warning for the unused import on [LookupMap].
main() {
  test('validate version number matches', () {
    var pubspec = Platform.script.resolve('../pubspec.yaml');
    var yaml = loadYaml(new File.fromUri(pubspec).readAsStringSync());
    var version1 = yaml['version'];
    var library = currentMirrorSystem().findLibrary(#lookup_map);
    var version2 = library.getField(new Symbol('_version')).reflectee;
    expect(version1, version2);
  });
}

Fix conversion from Uri to File in test, to use File.fromUri().

BUG=
R=wibling@google.com

Review URL: https://codereview.chromium.org//1333313002 .


// Copyright (c) 2014, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
//
// Test write barrier verification mode.
// VMOptions=--verified_mem --verify_before_gc --verify_after_gc

var a = [];

void main() {
  for (int i = 0; i < 123; ++i) {
    a.add(new List(12345));
  }
  for (int i = 0; i < 1234; ++i) {
    a[0] = new List(100000);
  }
}

// Copyright (c) 2014, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
//
// Test write barrier verification mode.
// VMOptions=--verified_mem --verify_before_gc --verify_after_gc

var a = [];

void main() {
  for (int i = 0; i < 12; ++i) {
    a.add(new List(12345));
  }
  for (int i = 0; i < 1234; ++i) {
    a[0] = new List(100000);
  }
}

Reduce live size of test of write barrier verification.

TBR=iposva@google.com

Review URL: https://codereview.chromium.org//726453002

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@41703 260f80e4-7a28-3924-810f-c04153c831b5


library generated_getter_setter_spec;

import '../../_specs.dart';
import 'parser_spec.dart' as parser_spec;
import 'generated_getter_setter.dart';

main() {
  describe('hybrid getter-setter', () {
    beforeEach(module((Module module) {
      module.type(Parser, implementedBy: DynamicParser);
      module.type(ClosureMap, implementedBy: StaticClosureMap);
    }));
    //parser_spec.main();
  });
}

library generated_getter_setter_spec;

import '../../_specs.dart';
import 'parser_spec.dart' as parser_spec;
import 'generated_getter_setter.dart';

main() {
  describe('hybrid getter-setter', () {
    beforeEach(module((Module module) {
      module.type(Parser, implementedBy: DynamicParser);
      module.type(ClosureMap, implementedBy: StaticClosureMap);
    }));
    parser_spec.main();
  });
}

chore(parser): Enable parser tests using the generated hybrid parser.


// Copyright (c) 2015, <your name>. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.

/// The dartbase_console_client library.
library dartbase_console_client;

import 'package:console/console.dart';
import 'package:dartbase_server/gamelogic.dart';

class LocalConsoleClient {
  final int numPlayers;
  Game _game;
  LocalConsoleClient(this.numPlayers){
    _game = new Game();
    for (var i = 1; i <= numPlayers; i++) {
      _game.addPlayer("Player${i}");
    }
    _game.startGame();

  }

}

void printBoard(Board board, BoardLoc viewLoc){
  var canvas = new Canvas(120, 48);

  if(board.contains(viewLoc)){
    _drawLoc(canvas, board[viewLoc], 60, 25);
  }

  print(canvas.frame());
}

void _drawLoc(Canvas canvas, PlayedCard pc, int viewX, int viewY){
  canvas.set(viewX, viewY);
}

// Copyright (c) 2015, <your name>. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.

/// The dartbase_console_client library.
library dartbase_console_client;

import 'package:console/console.dart';
import 'package:dartbase_server/gamelogic.dart';

part 'print.dart';

class LocalConsoleClient {
  final int numPlayers;
  Game _game;
  LocalConsoleClient(this.numPlayers){
    _game = new Game();
    for (var i = 1; i <= numPlayers; i++) {
      _game.addPlayer("Player${i}");
    }
    _game.startGame();

  }

}

Add print part, remove print methods

Add print part, remove print methods


part of '../../pay.dart';

typedef PayGestureTapCallback = void Function(Pay client);

class GooglePayButtonWidget extends StatelessWidget {
  final Pay _googlePayClient;
  final GooglePayButton _googlePayButton;

  final Widget _childOnError;
  final Widget _loadingIndicator;

  GooglePayButtonWidget._(
    Key key,
    this._googlePayClient,
    this._googlePayButton,
    this._childOnError,
    this._loadingIndicator,
  ) : super(key: key);

  factory GooglePayButtonWidget({
    Key key,
    @required paymentConfigurationAsset,
    @required PayGestureTapCallback onPressed,
    type,
    color,
    childOnError,
    loadingIndicator,
  }) {
    Pay googlePayClient = Pay.fromAsset(paymentConfigurationAsset);
    GooglePayButton googlePayButton = GooglePayButton(
      onPressed: () => onPressed(googlePayClient),
      type: type,
      color: color,
    );

    return GooglePayButtonWidget._(
      key,
      googlePayClient,
      googlePayButton,
      childOnError,
      loadingIndicator,
    );
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<bool>(
      future: _googlePayClient.userCanPay(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          if (snapshot.data == true) {
            return SizedBox(
              width: double.infinity,
              child: _googlePayButton,
            );
          } else if (snapshot.hasError) {
            return _childOnError ?? SizedBox.shrink();
          }
        }

        return _loadingIndicator ?? SizedBox.shrink();
      },
    );
  }
}

part of '../../pay.dart';

typedef PayGestureTapCallback = void Function(Pay client);

class GooglePayButtonWidget extends StatelessWidget {
  final Pay _googlePayClient;
  final GooglePayButton _googlePayButton;

  final Widget _childOnError;
  final Widget _loadingIndicator;

  GooglePayButtonWidget._(
    Key key,
    this._googlePayClient,
    this._googlePayButton,
    this._childOnError,
    this._loadingIndicator,
  ) : super(key: key);

  factory GooglePayButtonWidget({
    Key key,
    @required paymentConfigurationAsset,
    @required PayGestureTapCallback onPressed,
    type,
    color,
    childOnError,
    loadingIndicator,
  }) {
    Pay googlePayClient = Pay.fromAsset(paymentConfigurationAsset);
    GooglePayButton googlePayButton = GooglePayButton(
      onPressed: () => onPressed(googlePayClient),
      type: type,
      color: color,
    );

    return GooglePayButtonWidget._(
      key,
      googlePayClient,
      googlePayButton,
      childOnError,
      loadingIndicator,
    );
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<bool>(
      future: _googlePayClient.userCanPay(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          if (snapshot.data == true) {
            return _googlePayButton;
          } else if (snapshot.hasError) {
            return _childOnError ?? SizedBox.shrink();
          }
        }

        return _loadingIndicator ?? SizedBox.shrink();
      },
    );
  }
}

Remove sizing opinion on the widget

Remove sizing opinion on the widget


// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'box.dart';
import 'object.dart';

class StatisticsBox extends RenderBox {

  StatisticsBox({int optionsMask: 0, int rasterizerThreshold: 0})
    : _optionsMask = optionsMask,
      _rasterizerThreshold = rasterizerThreshold;

  int _optionsMask;
  int get optionsMask => _optionsMask;
  void set optionsMask (int mask) {
    if (mask == _optionsMask) {
      return;
    }
    _optionsMask = mask;
    markNeedsPaint();
  }

  int _rasterizerThreshold;
  int get rasterizerThreshold => _rasterizerThreshold;
  void set rasterizerThreshold (int threshold) {
    if  (threshold == _rasterizerThreshold) {
      return;
    }
    _rasterizerThreshold = threshold;
    markNeedsPaint();
  }

  bool get sizedByParent => true;

  double getMinIntrinsicWidth(BoxConstraints constraints) {
    return constraints.minWidth;
  }

  double getMaxIntrinsicWidth(BoxConstraints constraints) {
    return constraints.maxWidth;
  }

  double getMinIntrinsicHeight(BoxConstraints constraints) {
    return constraints.minHeight;
  }

  double getMaxIntrinsicHeight(BoxConstraints constraints) {
    return constraints.maxHeight;
  }

  void performResize() {
    size = constraints.constrain(Size.infinite);
  }

  void paint(PaintingContext context, Offset offset) {
    context.paintStatistics(optionsMask, rasterizerThreshold, offset, size);
  }
}

// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'box.dart';
import 'object.dart';

class StatisticsBox extends RenderBox {

  StatisticsBox({int optionsMask: 0, int rasterizerThreshold: 0})
    : _optionsMask = optionsMask,
      _rasterizerThreshold = rasterizerThreshold;

  int _optionsMask;
  int get optionsMask => _optionsMask;
  void set optionsMask (int mask) {
    if (mask == _optionsMask) {
      return;
    }
    _optionsMask = mask;
    markNeedsPaint();
  }

  int _rasterizerThreshold;
  int get rasterizerThreshold => _rasterizerThreshold;
  void set rasterizerThreshold (int threshold) {
    if  (threshold == _rasterizerThreshold) {
      return;
    }
    _rasterizerThreshold = threshold;
    markNeedsPaint();
  }

  bool get sizedByParent => true;

  double getMinIntrinsicWidth(BoxConstraints constraints) {
    return constraints.minWidth;
  }

  double getMaxIntrinsicWidth(BoxConstraints constraints) {
    return constraints.maxWidth;
  }

  double getMinIntrinsicHeight(BoxConstraints constraints) {
    return constraints.minHeight;
  }

  double getMaxIntrinsicHeight(BoxConstraints constraints) {
    return constraints.maxHeight;
  }

  void performResize() {
    size = constraints.biggest;
  }

  void paint(PaintingContext context, Offset offset) {
    context.paintStatistics(optionsMask, rasterizerThreshold, offset, size);
  }
}

Remove an infinity in layout code.

Remove an infinity in layout code.


// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import "package:expect/expect.dart";
import "dart:async";
import "dart:io";
import "dart:isolate";

void testPauseList() {
  var keepAlive = new ReceivePort();
  new Directory("").createTemp().then((d) {
    // Linux reads 2K at a time.
    int total = 2 * 1024 + 1;
    for (int i = 0; i < total; i++) {
      new File("${d.path}/$i").createSync();
    }
    bool first = true;
    var subscription;
    int count = 0;
    subscription = d.list().listen((file) {
      if (first) {
        first = false;
        subscription.pause();
        Timer.run(() {
          for (int i = 0; i < total; i++) {
            new File("${d.path}/$i").deleteSync();
          }
          subscription.resume();
        });
      }
      count++;
    }, onDone: () {
      Expect.isTrue(count < total);
      keepAlive.close();
      d.delete().then((ignore) => keepAlive.close());
    });
  });
}

void main() {
  testPauseList();
}

// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import "package:expect/expect.dart";
import "dart:async";
import "dart:io";
import "dart:isolate";

void testPauseList() {
  var keepAlive = new ReceivePort();
  new Directory("").createTemp().then((d) {
    // Linux reads 2K at a time, so be sure to be >>.
    int total = 4 * 1024 + 1;
    for (int i = 0; i < total; i++) {
      new File("${d.path}/$i").createSync();
    }
    bool first = true;
    var subscription;
    int count = 0;
    subscription = d.list().listen((file) {
      if (first) {
        first = false;
        subscription.pause();
        Timer.run(() {
          for (int i = 0; i < total; i++) {
            new File("${d.path}/$i").deleteSync();
          }
          subscription.resume();
        });
      }
      count++;
    }, onDone: () {
      Expect.notEquals(total, count);
      keepAlive.close();
      d.delete().then((ignore) => keepAlive.close());
    });
  });
}

void main() {
  testPauseList();
}

Increase number of files created, to avoid flakyness on linux.

BUG=

Review URL: https://codereview.chromium.org//17232003

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@24084 260f80e4-7a28-3924-810f-c04153c831b5


// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library barback.test.package_graph.transform_test;

import 'package:barback/src/utils.dart';
import 'package:scheduled_test/scheduled_test.dart';

import '../utils.dart';

main() {
  initConfig();

  test("handles many parallel transformers", () {
    var files = new List.generate(100, (i) => "app|$i.txt");
    var rewrite = new RewriteTransformer("txt", "out");
    initGraph(files, {"app": [[rewrite]]});

    // Pause and resume apply to simulate parallel long-running transformers.
    rewrite.pauseApply();
    updateSources(files);
    schedule(pumpEventQueue);
    rewrite.resumeApply();

    for (var i = 0; i < 100; i++) {
      expectAsset("app|$i.out", "$i.out");
    }
    buildShouldSucceed();

    expect(rewrite.maxParallelRuns, completion(equals(10)));
  });
}

// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library barback.test.package_graph.transform_test;

import 'package:barback/src/utils.dart';
import 'package:scheduled_test/scheduled_test.dart';

import '../utils.dart';

main() {
  initConfig();

  test("handles many parallel transformers", () {
    currentSchedule.timeout *= 3;
    var files = new List.generate(100, (i) => "app|$i.txt");
    var rewrite = new RewriteTransformer("txt", "out");
    initGraph(files, {"app": [[rewrite]]});

    // Pause and resume apply to simulate parallel long-running transformers.
    rewrite.pauseApply();
    updateSources(files);
    schedule(pumpEventQueue);
    rewrite.resumeApply();

    for (var i = 0; i < 100; i++) {
      expectAsset("app|$i.out", "$i.out");
    }
    buildShouldSucceed();

    expect(rewrite.maxParallelRuns, completion(equals(10)));
  });
}

Increase barback scheduled_test timeout for many_parallel_transformers test.

BUG=dartbug.com/15483

Review URL: https://codereview.chromium.org//102433007

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@30978 260f80e4-7a28-3924-810f-c04153c831b5


// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS d.file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library pub_tests;

import 'package:scheduled_test/scheduled_stream.dart';
import 'package:scheduled_test/scheduled_test.dart';

import '../descriptor.dart' as d;
import '../test_pub.dart';
import '../serve/utils.dart';

main() {
  initConfig();

  // A syntax error will cause the analyzer to fail to parse the transformer
  // when attempting to rewrite its imports.
  integration("fails to load a transform with a syntax error", () {
    d.dir(appPath, [
      d.pubspec({
        "name": "myapp",
        "transformers": ["myapp/src/transformer"]
      }),
      d.dir("lib", [d.dir("src", [
        d.file("transformer.dart", "syntax error")
      ])])
    ]).create();

    createLockFile('myapp', pkg: ['barback']);

    var pub = startPubServe();
    pub.stderr.expect(startsWith('Error on line'));
    pub.shouldExit(1);
    pub.stderr.expect(never(contains('This is an unexpected error')));
  });
}

// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS d.file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library pub_tests;

import 'package:scheduled_test/scheduled_stream.dart';
import 'package:scheduled_test/scheduled_test.dart';

import '../descriptor.dart' as d;
import '../test_pub.dart';
import '../serve/utils.dart';

main() {
  initConfig();

  // A syntax error will cause the analyzer to fail to parse the transformer
  // when attempting to rewrite its imports.
  integration("fails to load a transform with a syntax error", () {
    d.dir(appPath, [
      d.pubspec({
        "name": "myapp",
        "transformers": ["myapp/src/transformer"]
      }),
      d.dir("lib", [d.dir("src", [
        d.file("transformer.dart", "syntax error")
      ])])
    ]).create();

    createLockFile('myapp', pkg: ['barback']);

    var pub = startPubServe();
    pub.stderr.expect(startsWith('Error in'));
    pub.shouldExit(1);
    pub.stderr.expect(never(contains('This is an unexpected error')));
  });
}

Fix test for analyzer error message.

Fix test for analyzer error message.

BUG=
R=nweiz@google.com

Review URL: https://codereview.chromium.org//192753005

git-svn-id: a962b240025cf0577aa172e20f49ccb159ba6be1@33507 260f80e4-7a28-3924-810f-c04153c831b5


/*
 * Copyright (c) 2015, the Dart project authors.  Please see the AUTHORS file
 * for details. All rights reserved. Use of this source code is governed by a
 * BSD-style license that can be found in the LICENSE file.
 */
/**
 * @assertion Evaluation of a property extraction i of the form new T#
 * proceeds as follows:
 * ...
 * If T does not denote a class, a dynamic error occurs.
 * @description Check that it is a dynamic error if T denotes enum
 * @author sgrekhov@unipro.ru
 */
import '../../../../Utils/dynamic_check.dart';

enum E {a, b, c, m}

main() {
  checkDynamicError(() {
    var x = new E#;
  });
}

/*
 * Copyright (c) 2015, the Dart project authors.  Please see the AUTHORS file
 * for details. All rights reserved. Use of this source code is governed by a
 * BSD-style license that can be found in the LICENSE file.
 */
/**
 * @assertion Evaluation of a property extraction i of the form new T#
 * proceeds as follows:
 * ...
 * If T does not denote a class, a dynamic error occurs.
 * @description Check that it is a dynamic error if T denotes not existing class
 * @author sgrekhov@unipro.ru
 */
import '../../../../Utils/dynamic_check.dart';

main() {
  checkDynamicError(() {
    var x = new C#;
  });
}

Test fixed. Don't try instantiate enum

Test fixed. Don't try instantiate enum


// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:html';

import 'package:angular/angular.dart';

/// Utility class to allow opening a URL in a new window.
@Injectable()
class NewWindowOpener {
  void open(String url) => openInNewWindow(url);
}

/// Opens the given url in a new window.
///
/// Gives a hint to Chrome that it should open the given link in a separate
/// process.
void openInNewWindow(String url) {
  var anchorElement = AnchorElement(href: url)
    ..rel = 'noreferrer'
    ..target = '_blank';
  document.body.append(anchorElement);
  anchorElement.click();
  anchorElement.remove();
}

// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:html';

import 'package:angular/angular.dart';

/// Utility class to allow opening a URL in a new window.
@Injectable()
class NewWindowOpener {
  void open(String url) => openInNewWindow(url);
}

/// Opens the given url in a new window.
///
/// Gives a hint to Chrome that it should open the given link in a separate
/// process.
void openInNewWindow(String url) {
  var anchorElement = AnchorElement(href: url)
    ..rel = 'noopener noreferrer'
    ..target = '_blank';
  document.body.append(anchorElement);
  anchorElement.click();
  anchorElement.remove();
}

Update all components to use ref="noopener noreferrer" for target="_blank" links.

https://www.owasp.org/index.php/Reverse_Tabnabbing

PiperOrigin-RevId: 249578192


import 'interval.dart';

extension LengthIntervalNumExtension on Interval<num> {
  /// Returns the length an [Interval] as [int].
  ///
  /// Returns `0` if the interval is empty or `1` if the interval contains a
  /// single value. Throws an [ArgumentError] if one of  the bounds is unbound
  /// (infinite).
  int toIntLength() {
    if (isEmpty) {
      return 0;
    } else if (isSingle) {
      return 1;
    } else if (lower.isUnbounded || upper.isUnbounded) {
      throw ArgumentError.value(this, 'interval', 'Interval is unbounded');
    } else {
      var lowerEndpoint = lower.endpoint!.ceil();
      if (lower.isOpen && lowerEndpoint == lower.endpoint) lowerEndpoint++;
      var upperEndpoint = upper.endpoint!.truncate();
      if (upper.isOpen && upperEndpoint == upper.endpoint) upperEndpoint--;
      return lowerEndpoint < upperEndpoint ? upperEndpoint - lowerEndpoint : 0;
    }
  }

  /// Returns the length an [Interval] as [double].
  ///
  /// Returns `0.0` if the interval is empty or `double.infinity` if one of
  /// the bounds is unbound (infinite).
  double toDoubleLength() => isEmpty
      ? 0.0
      : lower.isUnbounded || upper.isUnbounded
          ? double.infinity
          : upper.endpoint!.toDouble() - lower.endpoint!.toDouble();
}

import 'interval.dart';

extension LengthIntervalNumExtension on Interval<num> {
  /// Returns the length an [Interval] as [int].
  ///
  /// Returns `0` if the interval is empty or `1` if the interval contains a
  /// single value. Throws an [ArgumentError] if one of  the bounds is unbounded
  /// (infinite).
  int toIntLength() {
    if (isEmpty) {
      return 0;
    } else if (isSingle) {
      return 1;
    } else if (lower.isUnbounded || upper.isUnbounded) {
      throw ArgumentError.value(this, 'interval', 'Interval is unbounded');
    } else {
      var lowerEndpoint = lower.endpoint!.ceil();
      if (lower.isOpen && lowerEndpoint == lower.endpoint) lowerEndpoint++;
      var upperEndpoint = upper.endpoint!.truncate();
      if (upper.isOpen && upperEndpoint == upper.endpoint) upperEndpoint--;
      return lowerEndpoint < upperEndpoint ? upperEndpoint - lowerEndpoint : 0;
    }
  }

  /// Returns the length an [Interval] as [double].
  ///
  /// Returns `0.0` if the interval is empty or contains a single value. Returns
  /// `double.infinity` if one of the bounds is unbounded (infinite).
  double toDoubleLength() {
    if (isEmpty || isSingle) {
      return 0.0;
    } else if (lower.isUnbounded || upper.isUnbounded) {
      return double.infinity;
    } else {
      return upper.endpoint!.toDouble() - lower.endpoint!.toDouble();
    }
  }
}

Improve comments and code clarity for Interval.toDoubleLength() and Interval.toIntLength().


// Copyright (c) 2019, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// SharedOptions=--enable-experiment=control-flow-collections,spread-collections

// Test that a null stream expression procudes a runtime error.
import 'package:async_helper/async_helper.dart';

void main() {
  asyncTest(() async {
    // Null stream.
    Stream<int> nullStream = null;
    asyncExpectThrows<NoSuchMethodError>(
        () async => <int>[await for (var i in nullStream) 1]);
    asyncExpectThrows<NoSuchMethodError>(
        () async => <int, int>{await for (var i in nullStream) 1: 1});
    asyncExpectThrows<NoSuchMethodError>(
        () async => <int>{await for (var i in nullStream) 1});
  });
}

// Copyright (c) 2019, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// SharedOptions=--enable-experiment=control-flow-collections,spread-collections

// Test that a null stream expression procudes a runtime error.
import 'package:async_helper/async_helper.dart';

void main() {
  asyncTest(() async {
    // Null stream.
    Stream<int> nullStream = null;
    asyncExpectThrows<Error>(
        () async => <int>[await for (var i in nullStream) 1]);
    asyncExpectThrows<Error>(
        () async => <int, int>{await for (var i in nullStream) 1: 1});
    asyncExpectThrows<Error>(
        () async => <int>{await for (var i in nullStream) 1});
  });
}

[tests] Update expected error NoSuchMethodError --> Error

Most (all?) implementations now throw ArgumentError since the
StreamIterator constructor no longer accepts null but the actual
type is not specified.
https://dart-review.googlesource.com/c/sdk/+/98001.

Change-Id: I10a24a67aa7353552c56d435ef206a2bc4f842fa
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/100987
Commit-Queue: Nicholas Shahan <03847abd2d8aadfe859ecb98095a31f9f515dc47@google.com>
Reviewed-by: Bob Nystrom <afede3a9ebedb865bee78398feff6fbe97068f17@google.com>


// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

/** Handles the `list` pub command. */
void commandList(PubOptions options, List<String> args) {
  // TODO(rnystrom): Validate args. Right now, this just lists the packages in
  // your cache.
  final cache = new PackageCache(options.cacheDir);
  cache.listAll().then((packages) {
    for (final package in packages) {
      print(package.name);
    }
  });
}

// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

/** Handles the `list` pub command. */
void commandList(PubOptions options, List<String> args) {
  // TODO(rnystrom): Validate args. Right now, this just lists the packages in
  // your cache.
  final cache = new PackageCache(options.cacheDir);
  cache.listAll().then((packages) {
    packages.sort((a, b) => a.name.compareTo(b.name));
    for (final package in packages) {
      print(package.name);
    }
  });
}

Sort packages by name before listing them.

Review URL: https://chromiumcodereview.appspot.com//10191027

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@6978 260f80e4-7a28-3924-810f-c04153c831b5