import 'dart:async';
import 'dart:io';

import 'package:args/args.dart';
import 'package:lsp_server/src/analysis_server.dart';
import 'package:lsp_server/src/channel.dart';

const _optionCandyDirectory = 'candy-path';

Future<void> main(List<String> arguments) async {
  stderr.write('Starting LSP…');

  final parser = ArgParser()..addOption(_optionCandyDirectory);
  final results = parser.parse(arguments);

  final candyDirectory = Directory(results[_optionCandyDirectory]);
  if (!candyDirectory.existsSync()) {
    exit(HttpStatus.notFound);
  }

  final channel = LspByteStreamServerChannel(stdin, stdout);
  final analysisServer = AnalysisServer(channel, candyDirectory);
  stderr.write('Started LSP.');
  await channel.closed;

  // Only shutdown the server and exit if the server is not already
  // handling the shutdown.
  if (!analysisServer.willExit) {
    await analysisServer.shutdown();
    exit(0);
  }
}

Improve debuggability if core package is not found

import 'dart:async';
import 'dart:io';

import 'package:args/args.dart';
import 'package:lsp_server/src/analysis_server.dart';
import 'package:lsp_server/src/channel.dart';

const _optionCandyDirectory = 'candy-path';

Future<void> main(List<String> arguments) async {
  stderr.write('Starting LSP…');

  final parser = ArgParser()..addOption(_optionCandyDirectory);
  final results = parser.parse(arguments);

  final corePath = results[_optionCandyDirectory];
  final coreDirectory = Directory(corePath);
  if (!coreDirectory.existsSync()) {
    stderr.write('Core library not found at $corePath.');
    exit(HttpStatus.notFound);
  }

  final channel = LspByteStreamServerChannel(stdin, stdout);
  final analysisServer = AnalysisServer(channel, coreDirectory);
  stderr.write('Started LSP.');
  await channel.closed;

  // Only shutdown the server and exit if the server is not already
  // handling the shutdown.
  if (!analysisServer.willExit) {
    await analysisServer.shutdown();
    exit(0);
  }
}


import 'package:flutter/material.dart';
import 'package:flutter_linkify/flutter_linkify.dart';
import 'package:url_launcher/url_launcher.dart';

/*
Widget used to Linkify text and then ensure any invalid URLs are caught and
reported to user. This should be used in place of the Linkify widget.
 */

class LinkifyWithCatch extends StatelessWidget {
  final String text;
  final TextStyle style;
  final TextAlign textAlign;

  const LinkifyWithCatch(
      {Key key, @required this.text, this.style, this.textAlign})
      : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Linkify(
      onOpen: (link) async {
        try {
          if (await canLaunch(link.url)) {
            await launch(link.url);
          } else {
            throw 'Could not launch $link';
          }
        } catch (e) {
          Scaffold.of(context).showSnackBar(SnackBar(
            content: Text('Could not open.'),
          ));
        }
      },
      options: LinkifyOptions(humanize: false),
      text: text,
      textAlign: textAlign,
      style: style,
    );
  }
}

Add default value to textAlign property

import 'package:flutter/material.dart';
import 'package:flutter_linkify/flutter_linkify.dart';
import 'package:url_launcher/url_launcher.dart';

/*
Widget used to Linkify text and then ensure any invalid URLs are caught and
reported to user. This should be used in place of the Linkify widget.
 */

class LinkifyWithCatch extends StatelessWidget {
  final String text;
  final TextStyle style;
  final TextAlign textAlign;

  const LinkifyWithCatch(
      {Key key,
      @required this.text,
      this.style,
      this.textAlign = TextAlign.start})
      : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Linkify(
      onOpen: (link) async {
        try {
          if (await canLaunch(link.url)) {
            await launch(link.url);
          } else {
            throw 'Could not launch $link';
          }
        } catch (e) {
          Scaffold.of(context).showSnackBar(SnackBar(
            content: Text('Could not open.'),
          ));
        }
      },
      options: LinkifyOptions(humanize: false),
      text: text,
      textAlign: textAlign,
      style: style,
    );
  }
}


part of stream_transformers;

/// Similar to `FlatMap`, but instead of including events from all spawned
/// streams, only includes the ones from the latest stream. Think of this
/// as stream switching.
///
/// **Example:**
///
///     var controller = new StreamController();
///     var latest = controller.stream.transform(new FlatMapLatest((value) => new Stream.fromIterable([value + 1]));
///
///     latest.listen(print);
///
///     controller.add(1);
///     controller.add(2); // Prints: 3
class FlatMapLatest<S, T> implements StreamTransformer<S, T> {
  final Mapper<S, Stream<T>> _convert;

  FlatMapLatest(Mapper<S, Stream<T>> convert) : _convert = convert;

  Stream<T> bind(Stream<S> stream) {
    var input = stream.asBroadcastStream(onCancel: (subscription) => subscription.cancel());

    return _bindStream(like: stream, onListen: (EventSink<T> sink) {
      var done = input.handleError((e) => e);
      return input
          .transform(new FlatMap((value) => _convert(value).transform(new TakeUntil(done))))
          .listen((value) => sink.add(value), onError: sink.addError, onDone: () => sink.close());
    });
  }
}

Change how FlatMapLatest cancels previous subscriptions

part of stream_transformers;

/// Similar to `FlatMap`, but instead of including events from all spawned
/// streams, only includes the ones from the latest stream. Think of this
/// as stream switching.
///
/// **Example:**
///
///     var controller = new StreamController();
///     var latest = controller.stream.transform(new FlatMapLatest((value) => new Stream.fromIterable([value + 1]));
///
///     latest.listen(print);
///
///     controller.add(1);
///     controller.add(2); // Prints: 3
class FlatMapLatest<S, T> implements StreamTransformer<S, T> {
  final Mapper<S, Stream<T>> _convert;

  FlatMapLatest(Mapper<S, Stream<T>> convert) : _convert = convert;

  Stream<T> bind(Stream<S> stream) {
    var input = stream.asBroadcastStream(onCancel: (subscription) => subscription.cancel());
    StreamSubscription doneSubscription;

    StreamSubscription onListen(EventSink<T> sink) {
      var done = new StreamController.broadcast(sync: true);
      doneSubscription = input.listen((value) => done.add(true), onError: (_) {}, onDone: () => done.close());

      return input
          .transform(new FlatMap((value) => _convert(value).transform(new TakeUntil(done.stream))))
          .listen((value) => sink.add(value), onError: sink.addError, onDone: () => sink.close());
    }

    return _bindStream(like: stream, onListen: onListen, onCancel: () => doneSubscription.cancel());
  }
}


// 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:isolate';

main(List<String> args, SendPort sendPort) {
  ReceivePort receivePort = new ReceivePort();
  sendPort.send(receivePort.sendPort);

  receivePort.listen((msg) {
    sendPort.send(_handle(msg));
  });
}

_handle(String msg) {
  return "ECHO: $msg";
}

Replace compute target with a structure map function

// 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:convert';
import 'dart:isolate';

main(List<String> args, SendPort sendPort) {
  ReceivePort receivePort = new ReceivePort();
  sendPort.send(receivePort.sendPort);

  receivePort.listen((msg) {
    sendPort.send(_handle(msg));
  });
}

_handle(String msg) {
  // Unpack arguments

  var inArgs = JSON.decode(msg);

  String key = inArgs["key"];
  String value = inArgs["value"];

  return JSON.encode(map(key, value));
}

Map<String, List<String>> map(String k, String v) {
  return { k : [ v.length ] };
}


import 'safenames.dart';
import 'utils.dart';
import 'winrt_method.dart';

abstract class WinRTPropertyProjection extends WinRTMethodProjection {
  WinRTPropertyProjection(super.method, super.vtableOffset);

  /// Strip off all underscores, even if double underscores
  String get exposedMethodName =>
      method.name.startsWith('get__') || method.name.startsWith('put__')
          ? safeIdentifierForString(method.name.substring(5).toCamelCase())
          : safeIdentifierForString(method.name.substring(4).toCamelCase());

  // WinRT properties always return an HRESULT
  @override
  String get nativePrototype => 'HRESULT Function($nativeParams)';

  // WinRT properties always return an HRESULT
  @override
  String get dartPrototype => 'int Function($dartParams)';
}

Call .toCamelCase() after safeIdentifierForString for consistency

import 'safenames.dart';
import 'utils.dart';
import 'winrt_method.dart';

abstract class WinRTPropertyProjection extends WinRTMethodProjection {
  WinRTPropertyProjection(super.method, super.vtableOffset);

  /// Strip off all underscores, even if double underscores
  String get exposedMethodName =>
      method.name.startsWith('get__') || method.name.startsWith('put__')
          ? safeIdentifierForString(method.name.substring(5)).toCamelCase()
          : safeIdentifierForString(method.name.substring(4)).toCamelCase();

  // WinRT properties always return an HRESULT
  @override
  String get nativePrototype => 'HRESULT Function($nativeParams)';

  // WinRT properties always return an HRESULT
  @override
  String get dartPrototype => 'int Function($dartParams)';
}


// Copyright (c) 2011, 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("co19_test_config");

#import("../../tools/testing/dart/test_suite.dart");

class Co19TestSuite extends StandardTestSuite {
  RegExp _testRegExp = const RegExp(@"t[0-9]{2}.dart$");

  Co19TestSuite(Map configuration)
      : super(configuration,
              "co19",
              "tests/co19/src",
              ["tests/co19/co19-compiler.status",
               "tests/co19/co19-runtime.status",
               "tests/co19/co19-frog.status"]);

  bool isTestFile(String filename) => _testRegExp.hasMatch(filename);
  bool listRecursively() => true;
  bool complexStatusMatching() => true;
}

Allow test.dart to handle the co19 test suite if it is not checked out.

// Copyright (c) 2011, 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("co19_test_config");

#import("dart:io");
#import("../../tools/testing/dart/test_suite.dart");

class Co19TestSuite extends StandardTestSuite {
  RegExp _testRegExp = const RegExp(@"t[0-9]{2}.dart$");

  Co19TestSuite(Map configuration)
      : super(configuration,
              "co19",
              "tests/co19/src",
              ["tests/co19/co19-compiler.status",
               "tests/co19/co19-runtime.status",
               "tests/co19/co19-frog.status"]);

  // A Dart checkout may omit the check out of the co19 tests.
  void forEachTest(Function onTest, Map testCache, String globalTempDir(),
                   [Function onDone = null]) {
    Directory testDirectory =
        new Directory(TestUtils.dartDir() + '/tests/co19/src');
    if (testDirectory.existsSync()) {
      super.forEachTest(onTest, testCache, globalTempDir, onDone);
    } else {
      if (onDone != null) onDone();
    }
  }

  bool isTestFile(String filename) => _testRegExp.hasMatch(filename);
  bool listRecursively() => true;
  bool complexStatusMatching() => true;
}


import 'package:flutter/material.dart';
import 'package:sqflite_example/main.dart' as example;

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  example.main();
}

Use sqflite_common_ffi for web in example app

import 'main_ffi.dart' as main_ffi;

void main() {
  main_ffi.main();
}


// 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.menu_item;

import 'package:polymer/polymer.dart';

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

// Ported from Polymer Javascript to Dart code.

@CustomTag("spark-menu-item")
class SparkMenuItem extends SparkWidget {
  /// URL image for the icon associated with this menu item.
  @published String src = "";
  /// Size of the icon.
  @published String iconsize = "24";
  /// Specifies the label for the menu item.
  @published String label = "";

  @observable bool isHovered = false;

  SparkMenuItem.created(): super.created() {
    // BUG: Use mouse events instead of :hover because Chrome fails to remove
    // :hover from an element after it's clicked and programmatically moved from
    // under the mouse, as is the case with our auto-closing spark-menu.
    bindCssClass(this, 'highlighted', this, 'isHovered');
    onMouseOver.listen((_) => isHovered = true);
    onMouseOut.listen((_) => isHovered = false);
  }
}

Fix menu selection not working after dart2js

// 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.menu_item;

import 'package:polymer/polymer.dart';

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

// Ported from Polymer Javascript to Dart code.

@CustomTag("spark-menu-item")
class SparkMenuItem extends SparkWidget {
  /// URL image for the icon associated with this menu item.
  @published String src = "";
  /// Size of the icon.
  @published String iconsize = "24";
  /// Specifies the label for the menu item.
  @published String label = "";

  @observable bool isHovered = false;

  SparkMenuItem.created(): super.created() {
    // BUG: Use mouse events instead of :hover because Chrome fails to remove
    // :hover from an element after it's clicked and programmatically moved from
    // under the mouse, as is the case with our auto-closing spark-menu.
    if (IS_DART2JS) {
      // TODO: bindCssClass() doesn't work after dart2js. Keeping it only
      // because widgets are a Polymer testing ground - investigate/file bug.
      onMouseOver.listen((_) { classes.add('highlighted'); });
      onMouseOut.listen((_) { classes.remove('highlighted'); });
    } else {
      bindCssClass(this, 'highlighted', this, 'isHovered');
      onMouseOver.listen((_) => isHovered = true);
      onMouseOut.listen((_) => isHovered = false);
    }
  }
}


// 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;
  }
}

Create webgame wrappers and error response

// 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<WebGame> _games;
  final int MAX_GAMES = 2;
  int currentid = 0;

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

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

      return currentid;

    } else {
      log("Max simultaneous games already reached.");
      throw new app.ErrorResponse(400, {"error": "Max Games Reached"});
    }

  }
}

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;
  }
}


// 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.

library kernel.transformations.closure_conversion;

import '../ast.dart' show Class, Program, Library;

import '../core_types.dart' show CoreTypes;

import 'closure/converter.dart' show ClosureConverter;

import 'closure/info.dart' show ClosureInfo;

import 'closure/invalidate_closures.dart';

Program transformProgram(CoreTypes coreTypes, Program program) {
  var info = new ClosureInfo();
  info.visitProgram(program);

  var convert = new ClosureConverter(coreTypes, info);
  program = convert.visitProgram(program);
  return new InvalidateClosures().visitProgram(program);
}

void transformLibraries(CoreTypes coreTypes, List<Library> libraries) {
  var info = new ClosureInfo();
  for (var library in libraries) {
    info.visitLibrary(library);
  }

  var convert = new ClosureConverter(coreTypes, info);
  for (int i = 0; i < libraries.length; i++) {
    libraries[i] = convert.visitLibrary(libraries[i]);
  }
  var invalidator = new InvalidateClosures();
  for (int i = 0; i < libraries.length; i++) {
    invalidator.visitLibrary(libraries[i]);
  }
}

Remove one more unused import

// 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.

library kernel.transformations.closure_conversion;

import '../ast.dart' show Program, Library;

import '../core_types.dart' show CoreTypes;

import 'closure/converter.dart' show ClosureConverter;

import 'closure/info.dart' show ClosureInfo;

import 'closure/invalidate_closures.dart';

Program transformProgram(CoreTypes coreTypes, Program program) {
  var info = new ClosureInfo();
  info.visitProgram(program);

  var convert = new ClosureConverter(coreTypes, info);
  program = convert.visitProgram(program);
  return new InvalidateClosures().visitProgram(program);
}

void transformLibraries(CoreTypes coreTypes, List<Library> libraries) {
  var info = new ClosureInfo();
  for (var library in libraries) {
    info.visitLibrary(library);
  }

  var convert = new ClosureConverter(coreTypes, info);
  for (int i = 0; i < libraries.length; i++) {
    libraries[i] = convert.visitLibrary(libraries[i]);
  }
  var invalidator = new InvalidateClosures();
  for (int i = 0; i < libraries.length; i++) {
    invalidator.visitLibrary(libraries[i]);
  }
}


import 'package:flutter_web/material.dart';

void main() => runApp(new MyBrokenApp());

class MyBrokenApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(primarySwatch: Colors.blue),
      home: new MyBrokenHomePage(),
    );
  }
}

class MyBrokenHomePage extends StatelessWidget {
  MyBrokenHomePage({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    throw new Exception("Oops");
  }
}

Make is easier to find the error in the call stack

import 'package:flutter_web/material.dart';

void main() => runApp(new MyBrokenApp());

class MyBrokenApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(primarySwatch: Colors.blue),
      home: new MyBrokenHomePage(),
    );
  }
}

class MyBrokenHomePage extends StatelessWidget {
  MyBrokenHomePage({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return methodThatThrows();
  }

  Widget methodThatThrows() {
    throw new Exception("Oops");
  }
}


//  Copyright (c) 2011, 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.

// WARNING: Do not edit - generated code.

interface TextMetrics {

  num get width();
}

Undo accidental changed in r3337


// 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.

/// Watches the given directory and prints each modification to it.
library watch;

import 'dart:io';

import 'package:path/path.dart' as p;
import 'package:watcher/watcher.dart';

main() {
  var args = new Options().arguments;
  if (args.length != 1) {
    print("Usage: watch <directory path>");
    return;
  }

  var watcher = new DirectoryWatcher(p.absolute(args[0]));
  watcher.events.listen((event) {
    print(event);
  });
}

Remove uses of Options from pkg, samples, tests, and third_party directories.

// 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.

/// Watches the given directory and prints each modification to it.
library watch;

import 'dart:io';

import 'package:path/path.dart' as p;
import 'package:watcher/watcher.dart';

main(List<String> arguments) {
  if (arguments.length != 1) {
    print("Usage: watch <directory path>");
    return;
  }

  var watcher = new DirectoryWatcher(p.absolute(arguments[0]));
  watcher.events.listen((event) {
    print(event);
  });
}


// Copyright (c) 2017, 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.

// Tests of generic functions.

import 'package:expect/expect.dart';

typedef R Foo<R>();

bar<R>(int body()) {
  var function = () {
    if (body is Foo<R>) {
      return body();
    }
    return 42;
  };
  return function();
}

main(args) {
  Expect.isTrue(bar(() => 43) == 43);
}

Remove the argument from main in a test

// Copyright (c) 2017, 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.

// Tests of generic functions.

import 'package:expect/expect.dart';

typedef R Foo<R>();

bar<R>(int body()) {
  var function = () {
    if (body is Foo<R>) {
      return body();
    }
    return 42;
  };
  return function();
}

main() {
  Expect.isTrue(bar(() => 43) == 43);
}


library all_test;

import 'package:euler/euler.dart';
import 'package:unittest/unittest.dart';

void main() {
  allProblemsDo((problem, executor) {
    test('Problem $problem', () {
      expect(executor().exitCode, 0, reason: 'Exit code');
    });
  }, arguments: ['--checked']);
}

Fix the error reporting when running the tests

library all_test;

import 'package:euler/euler.dart';
import 'package:unittest/unittest.dart';

void main() {
  allProblemsDo((problem, executor) {
    test('Problem $problem', () {
      var result = executor();
      if (result.exitCode != 0) {
        logMessage(result.stderr);
      }
      expect(executor().exitCode, 0, reason: 'Exit code');
    });
  }, arguments: ['--checked']);
}


import 'validators.dart' show Validator, ValidatorFn;

ValidatorFn normalizeValidator(dynamic validator) {
  if (validator is Validator) {
    return (c) => validator.validate(c);
  } else {
    return validator as ValidatorFn;
  }
}

Stop relying on Dart 1.0 behavior of callable classes.

import 'validators.dart' show Validator, ValidatorFn;

ValidatorFn normalizeValidator(dynamic validator) {
  if (validator is Validator) {
    return (c) => validator.validate(c);
  } else if (validator is Function) {
    return validator as ValidatorFn;
  } else {
    return validator.call as ValidatorFn;
  }
}


// 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);
  }
}

Remove an infinity in layout code.

// 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);
  }
}


// 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.

/**
 * Representation of the invocation of a member on an object.
 *
 * This is the type of objects passed to [Object.noSuchMethod] when
 * an object doesn't support the member invocation that was attempted
 * on it.
 */
abstract class InvocationMirror {
  /** The name of the invoked member. */
  String get memberName;

  /** An unmodifiable view of the positional arguments of the call. */
  List get positionalArguments;

  /** An unmodifiable view of the named arguments of the call. */
  Map<String, Dynamic> get namedArguments;

  /** Whether the invocation was a method call. */
  bool get isMethod;

  /**
   * Whether the invocation was a getter call.
   * If so, both types of arguments will be null.
   */
  bool get isGetter;

  /**
   * Whether the invocation was a setter call.
   *
   * If so, [arguments] will have exactly one positonal argument,
   * and namedArguments will be null.
   */
  bool get isSetter;

  /**
   * Whether the invocation was a getter or a setter call.
   */
  bool get isAccessor => isGetter || isSetter;

  /**
   * Perform the invocation on the provided object.
   *
   * If the object doesn't support the invocation, it's [noSuchMethod]
   * method will be called with either this [InvocationMirror] or another
   * equivalent [InvocationMirror].
   */
  invokeOn(Object receiver);
}

Add InvocationMirror interface to the core library.

// 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.

/**
 * Representation of the invocation of a member on an object.
 *
 * This is the type of objects passed to [Object.noSuchMethod] when
 * an object doesn't support the member invocation that was attempted
 * on it.
 */
abstract class InvocationMirror {
  /** The name of the invoked member. */
  String get memberName;

  /** An unmodifiable view of the positional arguments of the call. */
  List get positionalArguments;

  /** An unmodifiable view of the named arguments of the call. */
  Map<String, Dynamic> get namedArguments;

  /** Whether the invocation was a method call. */
  bool get isMethod;

  /**
   * Whether the invocation was a getter call.
   * If so, both types of arguments will be null.
   */
  bool get isGetter;

  /**
   * Whether the invocation was a setter call.
   *
   * If so, [arguments] will have exactly one positonal argument,
   * and namedArguments will be null.
   */
  bool get isSetter;

  /** Whether the invocation was a getter or a setter call. */
  bool get isAccessor => isGetter || isSetter;

  /**
   * Perform the invocation on the provided object.
   *
   * If the object doesn't support the invocation, its [noSuchMethod]
   * method will be called with either this [InvocationMirror] or another
   * equivalent [InvocationMirror].
   */
  invokeOn(Object receiver);
}


import 'package:analysis_server/src/analysis_server_abstract.dart';
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/instrumentation/instrumentation.dart';

/// An instrumentation service to show instrumentation errors as error
/// notifications to the user.
class ErrorNotifier extends NoopInstrumentationService {
  AbstractAnalysisServer server;

  @override
  void logException(dynamic exception,
      [StackTrace stackTrace,
      List<InstrumentationServiceAttachment> attachments]) {
    if (exception is SilentException) {
      // Silent exceptions should not be reported to the user.
      return;
    }

    var message = 'Internal error';
    if (exception is CaughtException && exception.message != null) {
      // TODO(mfairhurst): Use the outermost exception once crash reporting is
      // fixed and this becomes purely user-facing.
      exception = exception.rootCaughtException;
      // TODO(mfairhurst): Use the outermost message rather than the innermost
      // exception as its own message.
      message = exception.exception;
    }

    server.sendServerErrorNotification(message, exception, stackTrace,
        fatal: exception is FatalException);
  }
}

/// Server may throw a [FatalException] to send a fatal error response to the
/// IDEs.
class FatalException extends CaughtException {
  FatalException(String message, Object exception, stackTrace)
      : super.withMessage(message, exception, stackTrace);
}

Fix crash reporting bug, casting exception to a string

import 'package:analysis_server/src/analysis_server_abstract.dart';
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/instrumentation/instrumentation.dart';

/// An instrumentation service to show instrumentation errors as error
/// notifications to the user.
class ErrorNotifier extends NoopInstrumentationService {
  AbstractAnalysisServer server;

  @override
  void logException(dynamic exception,
      [StackTrace stackTrace,
      List<InstrumentationServiceAttachment> attachments]) {
    if (exception is SilentException) {
      // Silent exceptions should not be reported to the user.
      return;
    }

    var message = 'Internal error';
    if (exception is CaughtException && exception.message != null) {
      // TODO(mfairhurst): Use the outermost exception once crash reporting is
      // fixed and this becomes purely user-facing.
      exception = exception.rootCaughtException;
      // TODO(mfairhurst): Use the outermost message rather than the innermost
      // exception as its own message.
      message = exception.message;
    }

    server.sendServerErrorNotification(message, exception, stackTrace,
        fatal: exception is FatalException);
  }
}

/// Server may throw a [FatalException] to send a fatal error response to the
/// IDEs.
class FatalException extends CaughtException {
  FatalException(String message, Object exception, stackTrace)
      : super.withMessage(message, exception, stackTrace);
}


import 'package:drift/drift.dart';

// #docregion
// import the migrations tooling
import 'package:drift_dev/api/migrations.dart';
// #enddocregion

const kDebugBuild = true;

abstract class _$MyDatabase extends GeneratedDatabase {
  _$MyDatabase(QueryExecutor executor) : super(executor);
}

// #docregion

class MyDatabase extends _$MyDatabase {
// #enddocregion
  MyDatabase(QueryExecutor executor) : super(executor);

  @override
  Iterable<TableInfo<Table, dynamic>> get allTables =>
      throw UnimplementedError();

  @override
  int get schemaVersion => throw UnimplementedError();

  // #docregion
  @override
  MigrationStrategy get migration => MigrationStrategy(
        onCreate: (m) async {/* ... */},
        onUpgrade: (m, from, to) async {/* your existing migration logic */},
        beforeOpen: (details) async {
          // your existing beforeOpen callback, enable foreign keys, etc.

          if (kDebugBuild) {
            // This check pulls in a fair amount of code that's not needed
            // anywhere else, so we recommend only doing it in debug builds.
            await validateDatabaseSchema();
          }
        },
      );
}
// #enddocregion

Fix runtime migration verification typo

import 'package:drift/drift.dart';

// #docregion
// import the migrations tooling
import 'package:drift_dev/api/migrations.dart';
// #enddocregion

const kDebugMode = true;

abstract class _$MyDatabase extends GeneratedDatabase {
  _$MyDatabase(QueryExecutor executor) : super(executor);
}

// #docregion

class MyDatabase extends _$MyDatabase {
// #enddocregion
  MyDatabase(QueryExecutor executor) : super(executor);

  @override
  Iterable<TableInfo<Table, dynamic>> get allTables =>
      throw UnimplementedError();

  @override
  int get schemaVersion => throw UnimplementedError();

  // #docregion
  @override
  MigrationStrategy get migration => MigrationStrategy(
        onCreate: (m) async {/* ... */},
        onUpgrade: (m, from, to) async {/* your existing migration logic */},
        beforeOpen: (details) async {
          // your existing beforeOpen callback, enable foreign keys, etc.

          if (kDebugMode) {
            // This check pulls in a fair amount of code that's not needed
            // anywhere else, so we recommend only doing it in debug builds.
            await validateDatabaseSchema();
          }
        },
      );
}
// #enddocregion


// Copyright (c) 2018, 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/dart/analysis/analysis_context.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/src/dart/analysis/analysis_context_collection.dart';
import 'package:meta/meta.dart';

/// A collection of analysis contexts.
///
/// Clients may not extend, implement or mix-in this class.
abstract class AnalysisContextCollection {
  /// Initialize a newly created collection of analysis contexts that can
  /// analyze the files that are included by the list of [includedPaths].
  ///
  /// All paths must be absolute and normalized.
  ///
  /// If a [resourceProvider] is given, then it will be used to access the file
  /// system, otherwise the default resource provider will be used.
  factory AnalysisContextCollection({
    @required List<String> includedPaths,
    ResourceProvider resourceProvider,
  }) = AnalysisContextCollectionImpl;

  /// Return the existing [AnalysisContext] that should be used to analyze
  /// the given [path], or throw [StateError] if the [path] is not analyzed
  /// in any of the created analysis contexts.
  AnalysisContext contextFor(String path);
}

Add support for accessing all of the created contexts

// Copyright (c) 2018, 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/dart/analysis/analysis_context.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/src/dart/analysis/analysis_context_collection.dart';
import 'package:meta/meta.dart';

/// A collection of analysis contexts.
///
/// Clients may not extend, implement or mix-in this class.
abstract class AnalysisContextCollection {
  /// Initialize a newly created collection of analysis contexts that can
  /// analyze the files that are included by the list of [includedPaths].
  ///
  /// All paths must be absolute and normalized.
  ///
  /// If a [resourceProvider] is given, then it will be used to access the file
  /// system, otherwise the default resource provider will be used.
  factory AnalysisContextCollection({
    @required List<String> includedPaths,
    ResourceProvider resourceProvider,
  }) = AnalysisContextCollectionImpl;

  /// Return all of the analysis contexts in this collection.
  List<AnalysisContext> get contexts;

  /// Return the existing analysis context that should be used to analyze the
  /// given [path], or throw [StateError] if the [path] is not analyzed in any
  /// of the created analysis contexts.
  AnalysisContext contextFor(String path);
}


// Copyright (c) 2018, 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:async';
import 'dart:io';

import 'package:analysis_server/src/lsp/channel/lsp_byte_stream_channel.dart';
import 'package:analysis_server/src/lsp/lsp_socket_server.dart';

/**
 * Instances of the class [StdioServer] implement a simple server operating
 * over standard input and output. The primary responsibility of this server
 * is to split incoming messages on newlines and pass them along to the
 * analysis server.
 */
class LspStdioAnalysisServer {
  /**
   * An object that can handle either a WebSocket connection or a connection
   * to the client over stdio.
   */
  LspSocketServer socketServer;

  /**
   * Initialize a newly created stdio server.
   */
  LspStdioAnalysisServer(this.socketServer);

  /**
   * Begin serving requests over stdio.
   *
   * Return a future that will be completed when stdin closes.
   */
  Future serveStdio() {
    LspByteStreamServerChannel serverChannel = new LspByteStreamServerChannel(
        stdin, stdout, socketServer.instrumentationService);
    socketServer.createAnalysisServer(serverChannel);
    return serverChannel.closed;
  }
}

Use nonBlocking stdio for LSP

// Copyright (c) 2018, 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:async';
import 'dart:io';

import 'package:analysis_server/src/lsp/channel/lsp_byte_stream_channel.dart';
import 'package:analysis_server/src/lsp/lsp_socket_server.dart';

/**
 * Instances of the class [StdioServer] implement a simple server operating
 * over standard input and output. The primary responsibility of this server
 * is to split incoming messages on newlines and pass them along to the
 * analysis server.
 */
class LspStdioAnalysisServer {
  /**
   * An object that can handle either a WebSocket connection or a connection
   * to the client over stdio.
   */
  LspSocketServer socketServer;

  /**
   * Initialize a newly created stdio server.
   */
  LspStdioAnalysisServer(this.socketServer);

  /**
   * Begin serving requests over stdio.
   *
   * Return a future that will be completed when stdin closes.
   */
  Future serveStdio() {
    LspByteStreamServerChannel serverChannel = new LspByteStreamServerChannel(
        stdin, stdout.nonBlocking, socketServer.instrumentationService);
    socketServer.createAnalysisServer(serverChannel);
    return serverChannel.closed;
  }
}


// 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.

library dartbase_console_client.test;

import 'package:dartbase_console_client/dartbase_console_client.dart';
import 'package:unittest/unittest.dart';

import 'package:dartbase_server/gamelogic.dart';

void main() {
  test('Start local client', () {
    LocalConsoleClient client = new LocalConsoleClient(2);
    expect(client.state, GameState.started);
  });

}

Fix game state getter name

// 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.

library dartbase_console_client.test;

import 'package:dartbase_console_client/dartbase_console_client.dart';
import 'package:unittest/unittest.dart';

import 'package:dartbase_server/gamelogic.dart';

void main() {
  test('Start local client', () {
    LocalConsoleClient client = new LocalConsoleClient(2);
    expect(client.gameState, GameState.started);
  });

}


@TestOn('browser')
import 'package:angular/angular.dart';
import 'package:angular/experimental.dart';
import 'package:test/test.dart';

void main() {
  // This is relied on by internal clients until we introduce a sharding API.
  test('rootLegacyInjector should allow overriding ExceptionHandler', () {
    final appInjector = rootLegacyInjector(([parent]) {
      return new Injector.map({
        ExceptionHandler: new _CustomExceptionHandler(),
      }, parent);
    });

    // Normally errors here are forwarded to the ExceptionHandler.
    //
    // In the case of #1227, we accidentally always used the default
    // ExceptionHandler (BrowserExceptionHandler), meaning the user-defined
    // handler was ignored.
    (appInjector.get(NgZone) as NgZone).runGuarded(() {
      throw new _IntentionalError();
    });
    expect(
      _CustomExceptionHandler.lastCaught,
      const isInstanceOf<_IntentionalError>(),
    );
  });
}

class _IntentionalError extends Error {}

class _CustomExceptionHandler implements ExceptionHandler {
  static Object lastCaught;

  @override
  void call(exception, [stackTrace, String reason]) {
    lastCaught = exception;
  }
}

Add a test that rootLegacyInjector supports SlowComponentLoader.

@TestOn('browser')
import 'package:angular/angular.dart';
import 'package:angular/experimental.dart';
import 'package:test/test.dart';

void main() {
  // This is relied on by internal clients until we introduce a sharding API.
  test('rootLegacyInjector should allow overriding ExceptionHandler', () {
    final appInjector = rootLegacyInjector(([parent]) {
      return new Injector.map({
        ExceptionHandler: new _CustomExceptionHandler(),
      }, parent);
    });

    // Normally errors here are forwarded to the ExceptionHandler.
    //
    // In the case of #1227, we accidentally always used the default
    // ExceptionHandler (BrowserExceptionHandler), meaning the user-defined
    // handler was ignored.
    (appInjector.get(NgZone) as NgZone).runGuarded(() {
      throw new _IntentionalError();
    });
    expect(
      _CustomExceptionHandler.lastCaught,
      const isInstanceOf<_IntentionalError>(),
    );
  });

  test('rootLegacyInjector should provide a working SlowComponentLoader', () {
    final appInjector = rootLegacyInjector(([parent]) {
      return new Injector.empty(parent);
    });

    // Easiest way to tell is make sure its the same const instance.
    expect(
      appInjector.get(SlowComponentLoader),
      const SlowComponentLoader(const ComponentLoader()),
    );
  });
}

class _IntentionalError extends Error {}

class _CustomExceptionHandler implements ExceptionHandler {
  static Object lastCaught;

  @override
  void call(exception, [stackTrace, String reason]) {
    lastCaught = exception;
  }
}


// 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 'package:angular/angular.dart';
import 'package:angular_components/mixins/material_dropdown_base.dart';

/// A directive providing a [MenuRoot] through the injected [DropdownHandle].
@Directive(
  selector: '[menu-root]',
  providers: [ExistingProvider(MenuRoot, MenuRootDirective)],
)
class MenuRootDirective extends MenuRoot {
  final DropdownHandle _dropdown;

  MenuRootDirective(@Optional() this._dropdown) {
    visible = true;
  }

  @override
  void closeHierarchy() {
    visible = false;
    _dropdown.close();
  }
}

/// The root of a hierarchy of [MenuItemGroups].
///
/// This must be provided as it permits to close the menu hierarchy on menu
/// actions.
abstract class MenuRoot {
  void closeHierarchy();

  /// Is this menu closed or closing.
  bool visible;
}

Use nullable access to the dropdown, as it is passed optionally in menu-root.

// 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 'package:angular/angular.dart';
import 'package:angular_components/mixins/material_dropdown_base.dart';

/// A directive providing a [MenuRoot] through the injected [DropdownHandle].
@Directive(
  selector: '[menu-root]',
  providers: [ExistingProvider(MenuRoot, MenuRootDirective)],
)
class MenuRootDirective extends MenuRoot {
  final DropdownHandle _dropdown;

  MenuRootDirective(@Optional() this._dropdown) {
    visible = true;
  }

  @override
  void closeHierarchy() {
    visible = false;
    _dropdown?.close();
  }
}

/// The root of a hierarchy of [MenuItemGroups].
///
/// This must be provided as it permits to close the menu hierarchy on menu
/// actions.
abstract class MenuRoot {
  void closeHierarchy();

  /// Is this menu closed or closing.
  bool visible;
}


import 'dart:async';
import 'dart:io';

import 'package:dartz/dartz.dart';
import 'package:meta/meta.dart';

import '../../../../core/error/exception.dart';
import '../../../../core/error/failure.dart';
import '../../../../core/network/network_info.dart';
import '../../domain/repositories/activity_repository.dart';
import '../datasources/activity_data_source.dart';

class ActivityRepositoryImpl implements ActivityRepository {
  final ActivityDataSource dataSource;
  final NetworkInfo networkInfo;

  ActivityRepositoryImpl({
    @required this.dataSource,
    @required this.networkInfo,
  });

  @override
  Future<Either<Failure, Map<String, Map<String, Object>>>>
      getActivity() async {
    if (await networkInfo.isConnected) {
      try {
        final activity = await dataSource.getActivity();
        return Right(activity);
      } on MissingServerException {
        return Left(MissingServerFailure());
      } on SettingsException {
        return Left(SettingsFailure());
      } on ServerException {
        return Left(ServerFailure());
      } on SocketException {
        return Left(SocketFailure());
      } on TlsException {
        return Left(TlsFailure());
      } on FormatException {
        return Left(UrlFormatFailure());
      } on ArgumentError {
        return Left(UrlFormatFailure());
      } on TimeoutException {
        return Left(TimeoutFailure());
      } on JsonException {
        return Left(JsonFailure());
      }
    } else {
      return Left(ConnectionFailure());
    }
  }
}

Update exception catch to JsonDecodeException.

import 'dart:async';
import 'dart:io';

import 'package:dartz/dartz.dart';
import 'package:meta/meta.dart';

import '../../../../core/error/exception.dart';
import '../../../../core/error/failure.dart';
import '../../../../core/network/network_info.dart';
import '../../domain/repositories/activity_repository.dart';
import '../datasources/activity_data_source.dart';

class ActivityRepositoryImpl implements ActivityRepository {
  final ActivityDataSource dataSource;
  final NetworkInfo networkInfo;

  ActivityRepositoryImpl({
    @required this.dataSource,
    @required this.networkInfo,
  });

  @override
  Future<Either<Failure, Map<String, Map<String, Object>>>>
      getActivity() async {
    if (await networkInfo.isConnected) {
      try {
        final activity = await dataSource.getActivity();
        return Right(activity);
      } on MissingServerException {
        return Left(MissingServerFailure());
      } on SettingsException {
        return Left(SettingsFailure());
      } on ServerException {
        return Left(ServerFailure());
      } on SocketException {
        return Left(SocketFailure());
      } on TlsException {
        return Left(TlsFailure());
      } on FormatException {
        return Left(UrlFormatFailure());
      } on ArgumentError {
        return Left(UrlFormatFailure());
      } on TimeoutException {
        return Left(TimeoutFailure());
      } on JsonDecodeException {
        return Left(JsonFailure());
      }
    } else {
      return Left(ConnectionFailure());
    }
  }
}


// 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 'package:angular_components/model/selection/selection_model.dart';

import 'delegating_selection_model.dart';

/// Single selection model that always has a value selected
class RadioGroupSingleSelectionModel<T>
    extends DelegatingSingleSelectionModel<T> {
  RadioGroupSingleSelectionModel([T initialValue])
      : super(new SelectionModel<T>.withList(
            selectedValues: initialValue == null ? const [] : [initialValue]));

  @override
  void clear() {}

  @override
  bool deselect(T value) => false;
}

Use SelectionModel.single(), SelectionModel.multi() etc. instead of deprecated SelectionModel.withList() Use SelectionModel.empty() instead of deprecated SelectionModel()

// 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 'package:angular_components/model/selection/selection_model.dart';

import 'delegating_selection_model.dart';

/// Single selection model that always has a value selected
class RadioGroupSingleSelectionModel<T>
    extends DelegatingSingleSelectionModel<T> {
  RadioGroupSingleSelectionModel([T initialValue])
      : super(new SelectionModel<T>.single(
            selected: initialValue == null ? null : initialValue));

  @override
  void clear() {}

  @override
  bool deselect(T value) => false;
}


import 'package:hello_dart/hello_dart.dart';

/// Your player.
class MyPlayer extends Player {

  /// Your program.
  start() {
  }

}

main() {
  createWorld('scenario.txt', new MyPlayer());
}

Add some help to write the first function

import 'package:hello_dart/hello_dart.dart';

/// Your player.
class MyPlayer extends Player {

  /// Your program.
  start() {
    move();
    goAroundTree();
  }

  goAroundTree() {

  }
}

main() {
  createWorld('scenario.txt', new MyPlayer());
}


// 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 'package:scheduled_test/scheduled_stream.dart';

import '../../../lib/src/exit_codes.dart' as exit_codes;
import '../../descriptor.dart' as d;
import '../../test_pub.dart';

main() {
  initConfig();
  integration("errors if an executable's script can't be found", () {
    d.dir("foo", [
      d.pubspec({
        "name": "foo",
        "executables": {
          "missing": "not_here",
          "nope": null
        }
      })
    ]).create();

    var pub = startPub(args: ["global", "activate", "-spath", "../foo"]);

    pub.stderr.expect('Warning: Executable "missing" runs '
        '"bin/not_here.dart", which was not found in foo.');
    pub.stderr.expect('Warning: Executable "nope" runs "bin/nope.dart", which '
        'was not found in foo.');
    pub.shouldExit();
  });
}

Fix binstub test on windows.

// 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 'package:path/path.dart' as p;

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

main() {
  initConfig();
  integration("errors if an executable's script can't be found", () {
    d.dir("foo", [
      d.pubspec({
        "name": "foo",
        "executables": {
          "missing": "not_here",
          "nope": null
        }
      })
    ]).create();

    var pub = startPub(args: ["global", "activate", "-spath", "../foo"]);

    pub.stderr.expect('Warning: Executable "missing" runs '
        '"bin/not_here.dart", which was not found in foo.');
    pub.stderr.expect('Warning: Executable "nope" runs '
        '"${p.join('bin', 'nope.dart')}", which was not found in foo.');
    pub.shouldExit();
  });
}


// Copyright (c) 2017, 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 fasta.function_type_builder;

import 'builder.dart' show LibraryBuilder, TypeBuilder, TypeVariableBuilder;

abstract class FunctionTypeBuilder extends TypeBuilder {
  final TypeBuilder returnType;
  final List typeVariables;
  final List formals;

  FunctionTypeBuilder(this.returnType, this.typeVariables, this.formals);

  @override
  String get name => null;

  @override
  String get debugName => "Function";

  @override
  StringBuffer printOn(StringBuffer buffer) {
    if (typeVariables != null) {
      buffer.write("<");
      bool isFirst = true;
      for (TypeVariableBuilder t in typeVariables) {
        if (!isFirst) {
          buffer.write(", ");
        } else {
          isFirst = false;
        }
        buffer.write(t.name);
      }
      buffer.write(">");
    }
    buffer.write("(");
    if (formals != null) {
      bool isFirst = true;
      for (TypeBuilder t in formals) {
        if (!isFirst) {
          buffer.write(", ");
        } else {
          isFirst = false;
        }
        buffer.write(t.fullNameForErrors);
      }
    }
    buffer.write(") -> ");
    buffer.write(returnType.fullNameForErrors);
    return buffer;
  }

  @override
  build(LibraryBuilder library) {}
}

Make debug printing of function types more robust.

// Copyright (c) 2017, 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 fasta.function_type_builder;

import 'builder.dart' show LibraryBuilder, TypeBuilder, TypeVariableBuilder;

abstract class FunctionTypeBuilder extends TypeBuilder {
  final TypeBuilder returnType;
  final List typeVariables;
  final List formals;

  FunctionTypeBuilder(this.returnType, this.typeVariables, this.formals);

  @override
  String get name => null;

  @override
  String get debugName => "Function";

  @override
  StringBuffer printOn(StringBuffer buffer) {
    if (typeVariables != null) {
      buffer.write("<");
      bool isFirst = true;
      for (TypeVariableBuilder t in typeVariables) {
        if (!isFirst) {
          buffer.write(", ");
        } else {
          isFirst = false;
        }
        buffer.write(t.name);
      }
      buffer.write(">");
    }
    buffer.write("(");
    if (formals != null) {
      bool isFirst = true;
      for (dynamic t in formals) {
        if (!isFirst) {
          buffer.write(", ");
        } else {
          isFirst = false;
        }
        buffer.write(t?.fullNameForErrors);
      }
    }
    buffer.write(") -> ");
    buffer.write(returnType?.fullNameForErrors);
    return buffer;
  }

  @override
  build(LibraryBuilder library) {}
}


part of kcaa_model;

class RepairSlot extends Observable {
  @observable int id;
  @observable Ship ship;
  @observable DateTime eta;
  @observable String etaDatetimeString;

  RepairSlot();

  void update(Map<String, dynamic> data, Map<int, Ship> shipMap) {
    id = data["id"];
    if (data["ship_id"] != 0) {
      ship = shipMap[data["ship_id"]];
    }

    // ETA.
    if (data["eta"] != 0) {
      eta = new DateTime.fromMillisecondsSinceEpoch(data["eta"], isUtc: true)
        .toLocal();
      etaDatetimeString = formatShortTime(eta);
    }
  }
}

void handleRepairDock(Assistant assistant, AssistantModel model,
                      Map<String, dynamic> data) {
  model.numShipsBeingRepaired =
      data["slots"].where((s) => s["ship_id"] != 0).length;

  var slotsLength = data["slots"].length;
  resizeList(model.repairSlots, slotsLength, () => new RepairSlot());
  for (var i = 0; i < slotsLength; i++) {
    model.repairSlots[i].update(data["slots"][i], model.shipMap);
  }
}

Clear a repair slot when completed.

part of kcaa_model;

class RepairSlot extends Observable {
  @observable int id;
  @observable Ship ship;
  @observable DateTime eta;
  @observable String etaDatetimeString;

  RepairSlot();

  void update(Map<String, dynamic> data, Map<int, Ship> shipMap) {
    id = data["id"];
    if (data["ship_id"] != 0) {
      ship = shipMap[data["ship_id"]];
    } else {
      ship = null;
    }

    // ETA.
    if (data["eta"] != 0) {
      eta = new DateTime.fromMillisecondsSinceEpoch(data["eta"], isUtc: true)
        .toLocal();
      etaDatetimeString = formatShortTime(eta);
    } else {
      eta = null;
      etaDatetimeString = null;
    }
  }
}

void handleRepairDock(Assistant assistant, AssistantModel model,
                      Map<String, dynamic> data) {
  model.numShipsBeingRepaired =
      data["slots"].where((s) => s["ship_id"] != 0).length;

  var slotsLength = data["slots"].length;
  resizeList(model.repairSlots, slotsLength, () => new RepairSlot());
  for (var i = 0; i < slotsLength; i++) {
    model.repairSlots[i].update(data["slots"][i], model.shipMap);
  }
}


// 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.

library playfair;

import 'dart:sky' as sky;
import 'dart:math' as math;

import 'package:sky/rendering.dart';
import 'package:sky/theme/typography.dart';
import 'package:sky/widgets.dart';

part 'src/base.dart';

Update imports after material.dart rename

// 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.

library playfair;

import 'dart:sky' as sky;
import 'dart:math' as math;

import 'package:sky/material.dart';
import 'package:sky/rendering.dart';
import 'package:sky/widgets.dart';

part 'src/base.dart';


import 'package:slugify/src/replacements.dart';

const dupeSpacePattern = r'\s{2,}';
const punctuationPattern = r'[^\w\s-]';

Slugify(String text, {String delimiter = '-', bool lowercase = true}) {
  // Trim leading and trailing whitespace
  String slug = text.trim();

  // Make the text lowercase (optional)
  if (lowercase) {
    slug = slug.toLowerCase();
  }

  // Substitute characters for their latin equivalent
  replacements.forEach((k, v) => slug = slug.replaceAll(k, v));

  slug = slug
      // Condense whitespaces to 1 space
      .replaceAll(RegExp(dupeSpacePattern), ' ')
      // Remove punctuation
      .replaceAll(RegExp(punctuationPattern), '')
      // Add delimiter
      .replaceAll(' ', delimiter);

  return slug;
}

Convert RegExp to final vars

import 'package:slugify/src/replacements.dart';

final _dupeSpaceRegExp = RegExp(r'\s{2,}');
final _punctuationRegExp = RegExp(r'[^\w\s-]');

/// Converts [text] to a slugified [String] separated by the [delimiter].
Slugify(String text, {String delimiter = '-', bool lowercase = true}) {
  // Trim leading and trailing whitespace.
  String slug = text.trim();

  // Make the text lowercase (optional).
  if (lowercase) {
    slug = slug.toLowerCase();
  }

  // Substitute characters for their latin equivalent.
  replacements.forEach((k, v) => slug = slug.replaceAll(k, v));

  slug = slug
      // Condense whitespaces to 1 space.
      .replaceAll(_dupeSpaceRegExp, ' ')
      // Remove punctuation.
      .replaceAll(_punctuationRegExp, '')
      // Replace space with the delimiter.
      .replaceAll(' ', delimiter);

  return slug;
}


/**
 * By importing this library, you get the two most important fuzzy logic hedges:
 * [very] and [fairly].
 *
 * This means you can do:
 *
 *     (fairly(joke.funny) & very(situation.tense)) >> (laughter.loud)
 */
library fuzzyhedges;

import 'fuzzylogic.dart';
import 'dart:math';

class _FuzzyHedge extends FuzzyTerm {
  _FuzzyHedge(FuzzyNode a, this.hedgeFunction) {
    children = new Set.from([a]);
  }

  final _HedgeFunction hedgeFunction;

  num getDegreeOfMembership(List<FuzzyValue> inputs) {
    return hedgeFunction(children.single.getDegreeOfMembershipWithInputs(inputs));
  }

  void setDegreeOfTruth(num degreeOfTruth, List<FuzzyValue> outputs) {
    // TODO: change DOT through hedgeFunction?
    children.single.setDegreeOfTruth(degreeOfTruth, outputs);
  }
}

typedef num _HedgeFunction(num degreeOfMembership);

FuzzyNode very(FuzzyNode node) =>
    new _FuzzyHedge(node, (num dom) => pow(dom, 2));
FuzzyNode fairly(FuzzyNode node) =>
    new _FuzzyHedge(node, (num dom) => sqrt(dom));

Rename getDegreeOfMembership to getDegreeOfMembershipWithInputs even in FuzzyHedges

/**
 * By importing this library, you get the two most important fuzzy logic hedges:
 * [very] and [fairly].
 *
 * This means you can do:
 *
 *     (fairly(joke.funny) & very(situation.tense)) >> (laughter.loud)
 */
library fuzzyhedges;

import 'fuzzylogic.dart';
import 'dart:math';

class _FuzzyHedge extends FuzzyTerm {
  _FuzzyHedge(FuzzyNode a, this.hedgeFunction) {
    children = new Set.from([a]);
  }

  final _HedgeFunction hedgeFunction;

  num getDegreeOfMembershipWithInputs(List<FuzzyValue> inputs) {
    return hedgeFunction(children.single.getDegreeOfMembershipWithInputs(inputs));
  }

  void setDegreeOfTruth(num degreeOfTruth, List<FuzzyValue> outputs) {
    // TODO: change DOT through hedgeFunction?
    children.single.setDegreeOfTruth(degreeOfTruth, outputs);
  }
}

typedef num _HedgeFunction(num degreeOfMembership);

FuzzyNode very(FuzzyNode node) =>
    new _FuzzyHedge(node, (num dom) => pow(dom, 2));
FuzzyNode fairly(FuzzyNode node) =>
    new _FuzzyHedge(node, (num dom) => sqrt(dom));


import 'package:ddays/list_tasks.dart';
import 'package:test/test.dart';
import 'dart:html';

void main() {
  test('sinlgeTaskElement returns a LIElement with correct p children', () {
  LIElement st = singleTaskElement('task1');
  expect(st.children[0].text, 'task1');
  expect(st.classes.contains('singletask'),true);
  expect(st.children[0].classes.contains('summarytext'),true);
  LIElement st2 = singleTaskElement('');
  expect(st2.children[0].text, '');
  expect(st2.children[0].classes.contains('summarytext'),true);
  });

}

Add tests for insertTask function

import 'package:ddays/list_tasks.dart';
import 'package:test/test.dart';
import 'dart:html';

void main() {
  test('sinlgeTaskElement returns a LIElement with correct p children', () {
  LIElement st = singleTaskElement('task1');
  expect(st.children[0].text, 'task1');
  expect(st.classes.contains('singletask'),true);
  expect(st.children[0].classes.contains('summarytext'),true);
  LIElement st2 = singleTaskElement('');
  expect(st2.children[0].text, '');
  expect(st2.children[0].classes.contains('summarytext'),true);
  });
  test('insertTask should prepend a singleTaskElement into #listtasks children.',() {
    insertTask('some task');
    var li = querySelector('#listtasks').children[0];
    expect(li.children[0].text, 'some task');
    insertTask('other task');
    var li2 = querySelector('#listtasks').children[0];
    expect(li2.children[0].text, 'other task');
  });
  test('inserted tasks should be retrievable by their classname "singletask"', () {
    insertTask('more tasks');
    var retrieved = querySelector('.singletask');
    expect(retrieved.children[0].text, 'more tasks');
  });

}


import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

// [START listen_to_realtime_updates_listen_for_updates2]
class UserInformation extends StatefulWidget {
  @override
  _UserInformationState createState() => _UserInformationState();
}

class _UserInformationState extends State<UserInformation> {
  final Stream<QuerySnapshot> _usersStream =
      FirebaseFirestore.instance.collection('users').snapshots();

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: _usersStream,
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasError) {
          return const Text('Something went wrong');
        }

        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Text("Loading");
        }

        return ListView(
          children: snapshot.data!.docs
              .map((DocumentSnapshot document) {
                Map<String, dynamic> data =
                    document.data()! as Map<String, dynamic>;
                return ListTile(
                  title: Text(data['full_name']),
                  subtitle: Text(data['company']),
                );
              })
              .toList()
              .cast(),
        );
      },
    );
  }
}
// [EMD listen_to_realtime_updates_listen_for_updates2]

Fix typo in region tag

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

// [START listen_to_realtime_updates_listen_for_updates2]
class UserInformation extends StatefulWidget {
  @override
  _UserInformationState createState() => _UserInformationState();
}

class _UserInformationState extends State<UserInformation> {
  final Stream<QuerySnapshot> _usersStream =
      FirebaseFirestore.instance.collection('users').snapshots();

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: _usersStream,
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasError) {
          return const Text('Something went wrong');
        }

        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Text("Loading");
        }

        return ListView(
          children: snapshot.data!.docs
              .map((DocumentSnapshot document) {
                Map<String, dynamic> data =
                    document.data()! as Map<String, dynamic>;
                return ListTile(
                  title: Text(data['full_name']),
                  subtitle: Text(data['company']),
                );
              })
              .toList()
              .cast(),
        );
      },
    );
  }
}
// [END listen_to_realtime_updates_listen_for_updates2]


import 'dart:ui';

import 'package:flutter/material.dart';

import 'poster_chooser.dart';

class PosterCard extends StatelessWidget {
  final dynamic item;
  final Widget details;

  const PosterCard({
    Key key,
    @required this.item,
    @required this.details,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      child: ClipRRect(
        borderRadius: BorderRadius.circular(4),
        child: Container(
          height: 100,
          child: Stack(
            children: [
              Positioned.fill(
                child: ImageFiltered(
                  imageFilter: ImageFilter.blur(
                    sigmaX: 25,
                    sigmaY: 25,
                  ),
                  child: Image.network(
                    item.posterUrl != null ? item.posterUrl : '',
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              Container(
                color: Colors.black.withOpacity(0.4),
              ),
              Padding(
                padding: const EdgeInsets.all(4),
                child: Row(
                  children: [
                    PosterChooser(item: item),
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.only(left: 6),
                        child: details,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Add Hero widget support to PosterCard.

import 'dart:ui';

import 'package:flutter/material.dart';

import 'poster_chooser.dart';

class PosterCard extends StatelessWidget {
  final dynamic item;
  final Widget details;
  final Key heroTag;

  const PosterCard({
    Key key,
    @required this.item,
    @required this.details,
    this.heroTag,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      child: ClipRRect(
        borderRadius: BorderRadius.circular(4),
        child: Container(
          height: 100,
          child: Stack(
            children: [
              Positioned.fill(
                child: ImageFiltered(
                  imageFilter: ImageFilter.blur(
                    sigmaX: 25,
                    sigmaY: 25,
                  ),
                  child: Image.network(
                    item.posterUrl != null ? item.posterUrl : '',
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              Container(
                color: Colors.black.withOpacity(0.4),
              ),
              Padding(
                padding: const EdgeInsets.all(4),
                child: Row(
                  children: [
                    Hero(
                      tag: heroTag ?? UniqueKey(),
                      child: PosterChooser(item: item),
                    ),
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.only(left: 6),
                        child: details,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}


// 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_test.dart';

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

main() {
  initConfig();

  // An import error will cause the isolate API to fail synchronously while
  // loading the transformer.
  integration("fails to load a transform with an import error", () {
    d.dir(appPath, [
      d.pubspec({
        "name": "myapp",
        "transformers": ["myapp/src/transformer"]
      }),
      d.dir("lib", [d.dir("src", [
        d.file("transformer.dart", "import 'does/not/exist.dart';")
      ])])
    ]).create();

    createLockFile('myapp', pkg: ['barback']);
    var pub = startPubServe();
    pub.stderr.expect(endsWith("error: line 1 pos 1: library handler failed"));
    pub.shouldExit(1);
  });
}

Fix another transformer load error test.

// 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_test.dart';

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

main() {
  initConfig();

  // An import error will cause the isolate API to fail synchronously while
  // loading the transformer.
  integration("fails to load a transform with an import error", () {
    d.dir(appPath, [
      d.pubspec({
        "name": "myapp",
        "transformers": ["myapp/src/transformer"]
      }),
      d.dir("lib", [d.dir("src", [
        d.file("transformer.dart", "import 'does/not/exist.dart';")
      ])])
    ]).create();

    createLockFile('myapp', pkg: ['barback']);
    var pub = startPubServe();
    pub.stderr.expect("'Unhandled exception:");
    pub.stderr.expect(startsWith("Failure getting "));
    pub.shouldExit(1);
  });
}


// 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')));
  });
}

Fix test for analyzer error message.

// 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')));
  });
}


// 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.transformer.bad;

import 'dart:async';

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

import 'mock.dart';

/// A transformer that tries to load a secondary input and catches an
/// [AssetNotFoundException] if the input doesn't exist.
class CatchAssetNotFoundTransformer extends MockTransformer {
  /// The extension of assets this applies to.
  final String extension;

  /// The id of the secondary input to load.
  final AssetId input;

  CatchAssetNotFoundTransformer(this.extension, String input)
      : input = new AssetId.parse(input);

  Future<bool> doIsPrimary(Asset asset) =>
      new Future.value(asset.id.extension == extension);

  Future doApply(Transform transform) {
    return transform.getInput(input).then((_) {
      transform.addOutput(new Asset.fromString(
          transform.primaryInput.id, "success"));
    }).catchError((e) {
      if (e is! AssetNotFoundException) throw e;
      transform.addOutput(new Asset.fromString(
          transform.primaryInput.id, "failed to load $input"));
    });
  }
}

Fix an analyzer warning in barback.

// 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.transformer.catch_asset_not_found;

import 'dart:async';

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

import 'mock.dart';

/// A transformer that tries to load a secondary input and catches an
/// [AssetNotFoundException] if the input doesn't exist.
class CatchAssetNotFoundTransformer extends MockTransformer {
  /// The extension of assets this applies to.
  final String extension;

  /// The id of the secondary input to load.
  final AssetId input;

  CatchAssetNotFoundTransformer(this.extension, String input)
      : input = new AssetId.parse(input);

  Future<bool> doIsPrimary(Asset asset) =>
      new Future.value(asset.id.extension == extension);

  Future doApply(Transform transform) {
    return transform.getInput(input).then((_) {
      transform.addOutput(new Asset.fromString(
          transform.primaryInput.id, "success"));
    }).catchError((e) {
      if (e is! AssetNotFoundException) throw e;
      transform.addOutput(new Asset.fromString(
          transform.primaryInput.id, "failed to load $input"));
    });
  }
}


// Copyright (c) 2021, 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:async";

T id<T>(T value) => value;

main() async {
  FutureOr<int> x = 1 + id(1); // Should work, gives error.

  // Checking it!
  FutureOr<int> y = 1 + id(1)
    ..checkStaticType<Exactly<int>>();
  FutureOr<int> z = 1 + contextType(1)
    ..checkStaticType<Exactly<int>>();
}

extension<T> on T {
  void checkStaticType<R extends Exactly<T>>() {}
}

typedef Exactly<T> = T Function(T);
T contextType<T>(Object? o) => o as T;

Remove misleading comment from test

// Copyright (c) 2021, 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:async";

T id<T>(T value) => value;

main() async {
  FutureOr<int> x = 1 + id(1);

  FutureOr<int> y = 1 + id(1)
    ..checkStaticType<Exactly<int>>();
  FutureOr<int> z = 1 + contextType(1)
    ..checkStaticType<Exactly<int>>();
}

extension<T> on T {
  void checkStaticType<R extends Exactly<T>>() {}
}

typedef Exactly<T> = T Function(T);
T contextType<T>(Object? o) => o as T;


// 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 'package:logging/logging.dart' as logging;

logging.Logger _logger = new logging.Logger("sintr_common");

info(String message) => _logger.info(message);
trace(String message) => _logger.finer(message);
debug(String message) => _logger.fine(message);
alert(String message) => _logger.shout(message);

perf(String name, int ms) => _logger.fine("PERF: $name : $ms");

/// Setup log streaming to the right place for local and remote deployment.
setupLogging() {
  // TODO(lukechurch): Add support for container logs
  _setupLocalLogging();
}

/// Setup log streaming to stdOut.
_setupLocalLogging() {
  // Setup the logging
  logging.hierarchicalLoggingEnabled = false;
  logging.Logger.root.level = logging.Level.FINE;
  logging.Logger.root.onRecord.listen((logging.LogRecord rec) {
    print('${rec.level.name}: ${rec.time}: ${rec.message}');
  });
}

Increase logging level on worker nodes

// 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 'package:logging/logging.dart' as logging;

logging.Logger _logger = new logging.Logger("sintr_common");

info(String message) => _logger.info(message);
trace(String message) => _logger.finer(message);
debug(String message) => _logger.fine(message);
alert(String message) => _logger.shout(message);

perf(String name, int ms) => _logger.fine("PERF: $name : $ms");

/// Setup log streaming to the right place for local and remote deployment.
setupLogging() {
  // TODO(lukechurch): Add support for container logs
  _setupLocalLogging();
}

/// Setup log streaming to stdOut.
_setupLocalLogging() {
  // Setup the logging
  logging.hierarchicalLoggingEnabled = false;
  logging.Logger.root.level = logging.Level.FINER;
  logging.Logger.root.onRecord.listen((logging.LogRecord rec) {
    print('${rec.level.name}: ${rec.time}: ${rec.message}');
  });
}


import 'package:endpoints/endpoints.dart';
import 'package:appengine/appengine.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf_appengine/shelf_appengine.dart' as shelf_ae;
import 'tictactoe_api.dart';

_handler(Request request) {
  var headers = {'Content-Type' : 'text/plain'};

  if (request.url.toString() != '/') {
    return ApiServer.cascadeResponse;
  }

  return context.assets.read('/index.html').then((stream) {
    return new Response.ok(stream);
  });
}

void main() {
  var api_server = new ApiServer();
  api_server.addApi(new TicTacToe());
  var cascade = new Cascade(statusCodes: [501])
    .add(api_server.handler)
    .add(_handler)
    .add(shelf_ae.assetHandler);

  shelf_ae.serve(cascade.handler);
}

Use normal request handler instead of shelf

import 'package:endpoints/endpoints.dart';
import 'package:appengine/appengine.dart';
import 'tictactoe_api.dart';

import 'dart:io';

ApiServer api_server;

_handler(HttpRequest request) {
  if (request.uri.path.startsWith('/_ah/spi/')) {
    api_server.handleRequest(request);
    return;
  }
  if (request.uri.path == '/') {
    context.assets.serve(request.response, '/index.html');
    return;
  }
  context.assets.serve(request.response, request.uri.path);
}

void main() {
  api_server = new ApiServer();
  api_server.addApi(new TicTacToe());
  runAppEngine(_handler).then((_) {
    // Server running.
  });
}


// 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.
//
// Process test program to test process communication.
//
// VMOptions=
// VMOptions=--short_socket_read
// VMOptions=--short_socket_write
// VMOptions=--short_socket_read --short_socket_write

import "package:expect/expect.dart";
import 'dart:async';
import 'dart:io';
import 'dart:math';

import "process_test_util.dart";

void test(Future<Process> future, int expectedExitCode) {
  future.then((process) {
    process.exitCode.then((exitCode) {
      Expect.equals(expectedExitCode, exitCode);
    });

    process.stdout.listen((_) {});
    process.stderr.listen((_) {});
    process.stdin.writeln("Line1");
  });
}

main() {
  var scriptName = "process_stdin_transform_unsubscribe_script.dart";
  var scriptFile = new File("tests/standalone/io/$scriptName");
  if (!scriptFile.existsSync()) {
    scriptFile = new File("../tests/standalone/io/$scriptName");
  }
  Expect.isTrue(scriptFile.existsSync());
  test(Process.start(Platform.executable, [scriptFile.path]), 0);
}

Add call to flush() to avoid flakiness

// 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.
//
// Process test program to test process communication.
//
// VMOptions=
// VMOptions=--short_socket_read
// VMOptions=--short_socket_write
// VMOptions=--short_socket_read --short_socket_write

import "package:expect/expect.dart";
import 'dart:async';
import 'dart:io';
import 'dart:math';

import "process_test_util.dart";

void test(Future<Process> future, int expectedExitCode) {
  future.then((process) {
    process.exitCode.then((exitCode) {
      Expect.equals(expectedExitCode, exitCode);
    });

    process.stdout.listen((_) {});
    process.stderr.listen((_) {});
    process.stdin.writeln("Line1");
    process.stdin.flush().then((_) {
      print("flush completed");
    });
  });
}

main() {
  var scriptName = "process_stdin_transform_unsubscribe_script.dart";
  var scriptFile = new File("tests/standalone/io/$scriptName");
  if (!scriptFile.existsSync()) {
    scriptFile = new File("../tests/standalone/io/$scriptName");
  }
  Expect.isTrue(scriptFile.existsSync());
  test(Process.start(Platform.executable, [scriptFile.path]), 0);
}


import 'dart:io';
import 'package:expect/minitest.dart';
import 'package:dev_compiler/src/kernel/command.dart';

main(List<String> args) {
  // Various URL schemes
  expect(stringToUri("dart:io").toString(), "dart:io");
  expect(stringToUri("package:expect/minitest.dart").toString(),
      "package:expect/minitest.dart");
  expect(stringToUri("foobar:whatnot").toString(), "foobar:whatnot");

  // Full Windows path
  expect(stringToUri("C:\\full\\windows\\path.foo", windows: true).toString(),
      "file:///C:/full/windows/path.foo");
  expect(stringToUri("C:/full/windows/path.foo", windows: true).toString(),
      "file:///C:/full/windows/path.foo");

  // Relative Windows path
  expect(
      stringToUri("partial\\windows\\path.foo", windows: true).toString(),
      "file://${Directory.current.path.replaceAll(r'\', r'/')}"
      "/partial/windows/path.foo");

  // Full Unix path
  expect(stringToUri("/full/path/to/foo.bar", windows: false).toString(),
      "file:///full/path/to/foo.bar");

  // Relative Unix path
  expect(
      stringToUri("partial/path/to/foo.bar", windows: false).toString(),
      "file://${Directory.current.path.replaceAll(r'\', r'/')}"
      "/partial/path/to/foo.bar");
}

Revert "Fixup DDC test on Windows"

import 'dart:io';
import 'package:expect/minitest.dart';
import 'package:dev_compiler/src/kernel/command.dart';

main(List<String> args) {
  // Various URL schemes
  expect(stringToUri("dart:io").toString(), "dart:io");
  expect(stringToUri("package:expect/minitest.dart").toString(),
      "package:expect/minitest.dart");
  expect(stringToUri("foobar:whatnot").toString(), "foobar:whatnot");

  // Full Windows path
  expect(stringToUri("C:\\full\\windows\\path.foo", windows: true).toString(),
      "file:///C:/full/windows/path.foo");
  expect(stringToUri("C:/full/windows/path.foo", windows: true).toString(),
      "file:///C:/full/windows/path.foo");

  // Relative Windows path
  expect(stringToUri("partial\\windows\\path.foo", windows: true).toString(),
      "file://${Directory.current.path}/partial/windows/path.foo");

  // Full Unix path
  expect(stringToUri("/full/path/to/foo.bar", windows: false).toString(),
      "file:///full/path/to/foo.bar");

  // Relative Unix path
  expect(stringToUri("partial/path/to/foo.bar", windows: false).toString(),
      "file://${Directory.current.path}/partial/path/to/foo.bar");
}


import 'dart:async';
import 'dart:io';
import 'dart:math';

import 'package:json_rpc_2/json_rpc_2.dart';

import 'package:dart_language_server/dart_language_server.dart';

final random = new Random();

Future main() async {
  var log = new File('/tmp/wirelog.txt').openWrite();
  var channel = new StdIOStreamChannel();
  var logged = wireLog(channel, log);
  Timer timer;
  var server = new Peer(logged);
  server
    ..registerMethod('random_ints', (params) {
      return _randomInts(params['count'].value).toList();
    })
    ..registerMethod('start_notifications', () {
      timer ??= new Timer.periodic(const Duration(seconds: 3), (_) {
        server.sendNotification('some_notification', _randomInts(2));
      });
    })
    ..registerMethod('stop_notifications', () {
      timer?.cancel();
      timer = null;
    })
    ..registerFallback(([params]) {
      return 'fallback for "${params.method}" with params ${params.value}';
    });
  await server.listen();
  timer?.cancel();
  log.write('Done\n');
  log.close();
}

Iterable<int> _randomInts(int count) sync* {
  for (var i = 0; i < count; i++) {
    yield random.nextInt(100);
  }
}

Add `shutdown` and `exit` method handlers

import 'dart:async';
import 'dart:io';
import 'dart:math';

import 'package:json_rpc_2/json_rpc_2.dart';

import 'package:dart_language_server/dart_language_server.dart';

final random = new Random();

Future main() async {
  var log = new File('/tmp/wirelog.txt').openWrite();
  var channel = new StdIOStreamChannel();
  var logged = wireLog(channel, log);
  Timer timer;
  bool hasShutdown = false;
  var server = new Peer(logged);
  server
    ..registerMethod('shutdown', () {
      hasShutdown = true;
    })
    ..registerMethod('exit', () {
      server.close();
    })
    ..registerMethod('random_ints', (params) {
      return _randomInts(params['count'].value).toList();
    })
    ..registerMethod('start_notifications', () {
      timer ??= new Timer.periodic(const Duration(seconds: 3), (_) {
        server.sendNotification('some_notification', _randomInts(2));
      });
    })
    ..registerMethod('stop_notifications', () {
      timer?.cancel();
      timer = null;
    })
    ..registerFallback(([params]) {
      return 'fallback for "${params.method}" with params ${params.value}';
    });
  await server.listen();
  timer?.cancel();
  if (hasShutdown) {
    exitCode = 0;
  } else {
    exitCode = 1;
  }
  log.write('Done\n');
  log.close();
}

Iterable<int> _randomInts(int count) sync* {
  for (var i = 0; i < count; i++) {
    yield random.nextInt(100);
  }
}


// Copyright (c) 2011, 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.

String getPlatformOutDir() {
  var os = new Platform().operatingSystem();
  if (os == 'linux') return 'out';
  if (os == 'macos') return 'xcodebuild';
  return '';  // Windows.
}

String getProcessTestFileName() {
  var outDir = getPlatformOutDir();
  var names = ['$outDir/Release_ia32/process_test',
               '$outDir/Debug_ia32/process_test'];

  for (var name in names) {
    if (new File(name).existsSync()) {
      return name;
    }
  }
  Expect.fail('Could not find the process_test executable.');
}

String getDartFileName() {
  var outDir = getPlatformOutDir();
  var names = ['$outDir/Release_ia32/dart',
               '$outDir/Debug_ia32/dart'];

  for (var name in names) {
    if (new File(name).existsSync()) {
      return name;
    }
  }
  Expect.fail('Could not find the dart executable.');
}

Fix running process tests on Windows

// Copyright (c) 2011, 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.

String getPlatformOutDir() {
  var os = new Platform().operatingSystem();
  if (os == 'linux') return 'out/';
  if (os == 'macos') return 'xcodebuild/';
  return '';  // Windows.
}

String getPlatformExecutableExtension() {
  var os = new Platform().operatingSystem();
  if (os == 'windows') return '.exe';
  return '';  // Linux and Mac OS.
}

String getProcessTestFileName() {
  var outDir = getPlatformOutDir();
  var extension = getPlatformExecutableExtension();
  var names = ['${outDir}Release_ia32/process_test$extension',
               '${outDir}Debug_ia32/process_test$extension'];

  for (var name in names) {
    if (new File(name).existsSync()) {
      return name;
    }
  }
  Expect.fail('Could not find the process_test executable.');
}

String getDartFileName() {
  var outDir = getPlatformOutDir();
  var extension = getPlatformExecutableExtension();
  var names = ['${outDir}Release_ia32/dart$extension',
               '${outDir}Debug_ia32/dart$extension'];

  for (var name in names) {
    if (new File(name).existsSync()) {
      return name;
    }
  }
  Expect.fail('Could not find the dart executable.');
}


import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:toml/toml.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('TOML example'),
      ),
      body: FutureBuilder<String>(
        future: rootBundle.loadString('assets/example.toml'),
        builder: (context, snapshot) {
          final text = snapshot.data;
          if (text == null) {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
          final toml = TomlDocument.parse(text).toMap();
          return Center(
            child: Text(toml['str'] as String),
          );
        },
      ),
    );
  }
}

Fix lints of Flutter example

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:toml/toml.dart';

void main() {
  runApp(MyApp());
}

/// The main widget of the example application.
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

/// The default route of [MyApp].
class MyHomePage extends StatelessWidget {
  /// Creates a [MyHomePage].
  MyHomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('TOML example'),
      ),
      body: FutureBuilder<String>(
        future: rootBundle.loadString('assets/example.toml'),
        builder: (context, snapshot) {
          final text = snapshot.data;
          if (text == null) {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
          final toml = TomlDocument.parse(text).toMap();
          return Center(
            child: Text(toml['str'] as String),
          );
        },
      ),
    );
  }
}