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

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

Remove one more unused import

Remove one more unused import

R=karlklose@google.com

Review-Url: https://codereview.chromium.org/2943653002 .


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

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

Make is easier to find the error in the call stack


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

Undo accidental changed in r3337

TBR=ager@google.com

BUG=
TEST=

Review URL: http://codereview.chromium.org//9183004

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


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

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

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

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

BUG=
R=sgjesse@google.com

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

git-svn-id: c53bd6455474c0a826d309663cf600546f7b0963@29552 260f80e4-7a28-3924-810f-c04153c831b5


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

/// Interface that defines how a type `T` should be formatted into a String.
abstract class Formatter<T> {
  String format(T value, [String parameters]);
}

/// Generates list of css classes based on cell value.
abstract class StyleFormatter<T> implements Formatter<T> {
  /// Returns list of classes to style value.
  List<String> computeStyle(T value, [String parameters]) => const [];
}

/// Formats a value using parameters and the entity containing the
/// source field.
///
/// T is the type of the value that is being formatted.
/// In order to use, extend the [Formatter] class and implement the
/// [EntityFormatter] interface, then have the format method return null.
///
/// Example usage:
/// ```dart
/// class MyFormatter extends Formatter implements EntityFormatter {
///   @override
///   String format(value, [String args]) => null;
///
///   @override
///   String formatEntityField(Map entity, value, [String args]) => ...
/// }
/// ```
abstract class EntityFormatter<T> implements Formatter<T> {
  String formatEntityField(Map entity, T value, [String parameters]);
}

/// Generates list of css classes based on entity value.
///
/// This list will be merged with one returned by [StyleFormatter.computeStyle].
abstract class EntityStyleFormatter<T> implements StyleFormatter<T> {
  /// Returns list of classes to style the value.
  List<String> computeEntityStyle(Map entity, T value, [String parameters]);
}

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

/// Interface that defines how a type `T` should be formatted into a String.
abstract class Formatter<T> {
  String format(T value, [String parameters]);
}

/// Generates list of css classes based on cell value.
abstract class StyleFormatter<T> implements Formatter<T> {
  /// Returns list of classes to style value.
  List<String> computeStyle(T value, [String parameters]) => const [];
}

/// Formats a value using parameters and the entity containing the
/// source field.
///
/// T is the type of the value that is being formatted.
///
/// Please keep it mind that this makes the formatter much less reusable,
/// it is worth documenting what entities it does support or what fields are
/// required/optional for it to work correctly.
abstract class EntityFormatter<T> implements Formatter<T> {
  String formatEntityField(Map entity, T value, [String parameters]);
}

/// Generates list of css classes based on entity value.
///
/// This list will be merged with one returned by [StyleFormatter.computeStyle].
abstract class EntityStyleFormatter<T> implements StyleFormatter<T> {
  /// Returns list of classes to style the value.
  List<String> computeEntityStyle(Map entity, T value, [String parameters]);
}

Remove part of documentation for EntityFormatter, it seems incorrect, I do not think we depend on format to return null.

Added a warning about using this one.

PiperOrigin-RevId: 217167468


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

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

Remove the argument from main in a test

Remove the argument from main in a test

Dartium looks for main() with no arguments.

BUG=
R=jensj@google.com, whesse@google.com

Review-Url: https://codereview.chromium.org/2878543006 .


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

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

Fix the error reporting when running the tests


import 'validators.dart' show Validator, ValidatorFn;

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

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

Stop relying on Dart 1.0 behavior of callable classes.

Due to an upcoming change in Dart language semantics
(https://github.com/dart-lang/sdk/issues/32152), we can no longer use "callable classes" (those that contain a ".call" method) in a place where function types are expected.

To avoid breaking a lot of code, the front end will implicitly tear off ".call" when assigning a callable type to a function type.  This covers most Google3 code.  However, in a small number of cases the implicit tear-off is not sufficient, so we need to fix those cases manually.

Tested:
    tap_presubmit: http://test/OCL:186287469:BASE:186415347:1519218277328:530e6725
    Some tests failed; test failures are believed to be unrelated to this CL
PiperOrigin-RevId: 186468920


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

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

class StatisticsBox extends RenderBox {

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

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

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

  bool get sizedByParent => true;

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

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

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

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

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

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

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

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

class StatisticsBox extends RenderBox {

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

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

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

  bool get sizedByParent => true;

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

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

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

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

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

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

Remove an infinity in layout code.

Remove an infinity in layout code.


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

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

Add InvocationMirror interface to the core library.

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

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


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

library barback;

export 'src/asset.dart';
export 'src/asset_id.dart';
export 'src/asset_set.dart';
export 'src/barback.dart';
export 'src/barback_settings.dart';
export 'src/build_result.dart';
export 'src/errors.dart' hide flattenAggregateExceptions;
export 'src/log.dart';
export 'src/package_provider.dart';
export 'src/transform.dart' show Transform;
export 'src/transform_logger.dart';
export 'src/transformer.dart';
export 'src/transformer_group.dart';

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

import 'src/transform.dart';
import 'src/transformer.dart';

export 'src/asset.dart';
export 'src/asset_id.dart';
export 'src/asset_set.dart';
export 'src/barback.dart';
export 'src/barback_settings.dart';
export 'src/build_result.dart';
export 'src/errors.dart' hide flattenAggregateExceptions;
export 'src/log.dart';
export 'src/package_provider.dart';
export 'src/transform.dart' show Transform;
export 'src/transform_logger.dart';
export 'src/transformer.dart';
export 'src/transformer_group.dart';

Enable re-export in docgen. Work in progress. More to come.

BUG=
R=alanknight@google.com

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

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


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

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

[analysis_server] Fix crash reporting bug, casting exception to a string

Brian noticed this running unit tests. Who knows how many bug reports we
have missed from this -- we can only hope it is very few.

```
type '_TypeError' is not a subtype of type 'String'

package:analysis_server/src/server/error_notifier.dart 26:7        ErrorNotifier.logException
package:analysis_server/src/analysis_server.dart 266:54            AnalysisServer.handleRequest.<fn>
dart:async/zone.dart 1222:13                                       _rootRunBinary
dart:async/zone.dart 1107:19                                       _CustomZone.runBinary
dart:async/zone.dart 1601:18                                       runZonedGuarded.<fn>
dart:async/zone.dart 751:19                                        _ZoneDelegate.handleUncaughtError
...
```
Change-Id: Ib83dc99a88a1566ead5d59a9f71afc80416eb341
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/151464
Auto-Submit: Mike Fairhurst <2002604e76601be549134505841fea93de80dc45@google.com>
Commit-Queue: Konstantin Shcheglov <09e4d7516628963212bf4aace2f97603d2b706e4@google.com>
Reviewed-by: Konstantin Shcheglov <09e4d7516628963212bf4aace2f97603d2b706e4@google.com>


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

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

Fix runtime migration verification typo

Fix runtime migration verification typo


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

/**
 * Tests date formatting and parsing using locale data read from the
 * local file system.
 */
library date_time_format_file_test;

import '../lib/intl.dart';
import '../lib/date_symbol_data_file.dart';
import 'date_time_format_test_core.dart';
import '../../../pkg/unittest/lib/unittest.dart';

main() {
  runDateTests(['en_US']);
}

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

/**
 * Tests date formatting and parsing using locale data read from the
 * local file system.
 */
library date_time_format_file_test;

import '../lib/intl.dart';
import '../lib/date_symbol_data_local.dart';
import 'date_time_format_test_core.dart';
import '../../../pkg/unittest/lib/unittest.dart';

main() {
  runDateTests(['en_US']);
}

Make uninitialized Intl test not import dart:io
Review URL: https://codereview.chromium.org//11746005

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


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

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

Add support for accessing all of the created contexts

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


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

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

Use nonBlocking stdio for LSP

Use nonBlocking stdio for LSP

Change-Id: I20f7ed183d08b7fc778b4cb643eff6f82c9f3f48
Reviewed-on: https://dart-review.googlesource.com/c/90001
Reviewed-by: Brian Wilkerson <1f7641b6b14c52b9163524ab8d9aabff80176f21@google.com>
Commit-Queue: Danny Tuppeny <596a1fc21c51678cfafc48cd1efd53705f8b4f1d@google.com>


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

}

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

}

Fix game state getter name

Fix game state getter name


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

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

test(Core): Add a test that rootLegacyInjector supports SlowComponentLoader.

PiperOrigin-RevId: 192625887


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

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

PiperOrigin-RevId: 256203326


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

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

Update exception catch to JsonDecodeException.


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

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

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

PiperOrigin-RevId: 200344866


import 'package:hello_dart/hello_dart.dart';

/// Your player.
class MyPlayer extends Player {

  /// Your program.
  start() {
  }

}

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

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

Add some help to write the first function


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

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

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

Fix binstub test on windows.

Fix binstub test on windows.

R=nweiz@google.com

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

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


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

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

Make debug printing of function types more robust.

Sometimes when printing stack states in the outline builder,
a formal in a function type is a FormalParameterBuilder,
and sometimes a formal or the return type is null.

Change-Id: I2bed0baae2a80e894e170a85744e382e763c8944
Reviewed-on: https://dart-review.googlesource.com/58207
Reviewed-by: Peter von der Ahé <ad40f903ca639ca334d95dc5a5f0ae92bd708079@google.com>
Commit-Queue: Aske Simon Christensen <589eb3fd9a84f06d0ac46d3aa71dddcfb0814ccd@google.com>


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

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

Clear a repair slot when completed.

Clear a repair slot when completed.


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

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

Update imports after material.dart rename


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

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

Convert RegExp to final vars

Convert RegExp to final vars


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

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

Rename getDegreeOfMembership to getDegreeOfMembershipWithInputs even in FuzzyHedges


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

}

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

}

Add tests for insertTask function

Add tests for insertTask function


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]

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]

Fix typo in region tag

Fix typo in region tag


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,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

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,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Add Hero widget support to PosterCard.

Add Hero widget support to PosterCard.


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

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

Fix another transformer load error test.

R=rnystrom@google.com
TBR

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

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


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

library pub_tests;

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

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

main() {
  initConfig();

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

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

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

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

library pub_tests;

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

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

main() {
  initConfig();

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

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

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

Fix test for analyzer error message.

Fix test for analyzer error message.

BUG=
R=nweiz@google.com

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

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


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

library barback.test.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"));
    });
  }
}

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

Fix an analyzer warning in barback.

Fix an analyzer warning in barback.

R=rnystrom@google.com
BUG=

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

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


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

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

Remove misleading comment from test

[cfe] Remove misleading comment from test

Change-Id: I97392718faf380d1431e76e808bbe775e25e3d4e
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/177860
Reviewed-by: Dmitry Stefantsov <95a4b7e39916a54bd6477bec6a6de014b977db32@google.com>
Commit-Queue: Johnni Winther <0f64ef784d57ffb064b634040f9eeba0d33d0be4@google.com>


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

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

Increase logging level on worker nodes

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 'dart:io';

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

const SCRIPT = """
import 'dart:io';

main() {
  ProcessSignal.SIGHUP.watch().listen(print);

  print("ready");
}
""";

main() {
  initConfig();
  integration('forwards signals to the inner script', () {
    d.dir(appPath, [
      d.appPubspec(),
      d.dir("bin", [
        d.file("script.dart", SCRIPT)
      ])
    ]).create();

    var pub = pubRun(args: ["bin/script"]);

    pub.stdout.expect("ready");
    pub.signal(Process.SIGINT);
    pub.stdout.expect("SIGINT");

    pub.kill();
  });
}

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

import 'dart:io';

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

const SCRIPT = """
import 'dart:io';

main() {
  ProcessSignal.SIGHUP.watch().listen(print);

  print("ready");
}
""";

main() {
  initConfig();
  integration('forwards signals to the inner script', () {
    d.dir(appPath, [
      d.appPubspec(),
      d.dir("bin", [
        d.file("script.dart", SCRIPT)
      ])
    ]).create();

    var pub = pubRun(args: ["bin/script"]);

    pub.stdout.expect("ready");
    pub.signal(ProcessSignal.SIGHUP);
    pub.stdout.expect("SIGHUP");

    pub.kill();
  });
}

Fix windows signal test
(this amends a bit the changes in
https://code.google.com/p/dart/source/detail?r=44902)

R=kevmoo@google.com

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

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


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

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

Use normal request handler instead of shelf


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

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

Add call to flush() to avoid flakiness

Add call to flush() to avoid flakiness

Related to #28558.

R=zra@google.com

Review-Url: https://codereview.chromium.org/2688243003 .


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

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

Revert "Fixup DDC test on Windows"

Revert "Fixup DDC test on Windows"

This reverts commit 70020cd30d9c8d4b42c42b702df2cf2bf6a77d18.

Reason for revert: Didn't quite work.

Original change's description:
> Fixup DDC test on Windows
>
> Directory.current.path on Windows uses "\" and not "/".
>
> Bug:
> Change-Id: I6ef789d586622f78d0401c1a892f6a475bf6d93a
> Reviewed-on: https://dart-review.googlesource.com/34100
> Reviewed-by: Jens Johansen <05223a3c6bdf76af6f84755eae231abeebcf4530@google.com>

TBR=dmitryas@google.com,05223a3c6bdf76af6f84755eae231abeebcf4530@google.com

Change-Id: Ied8897801005f1a1b83075c1fb2a0b905129bb18
No-Presubmit: true
No-Tree-Checks: true
No-Try: true
Reviewed-on: https://dart-review.googlesource.com/34001
Reviewed-by: Jens Johansen <05223a3c6bdf76af6f84755eae231abeebcf4530@google.com>
Commit-Queue: Jens Johansen <05223a3c6bdf76af6f84755eae231abeebcf4530@google.com>


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

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

Add `shutdown` and `exit` method handlers

This matches the language server protocol. Shutdown does not need to do
any useful cleanup. Correctly sets the exit code against the protocol
spec based on whether shutdown was called.


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

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

Fix running process tests on Windows

Fix running process tests on Windows

TBR=ager@google.com

BUG=
TEST=

Review URL: http://codereview.chromium.org//8679008

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


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

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

Fix lints of Flutter example

Fix lints of Flutter example


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

// Patch file for dart:developer library.

import 'dart:_js_helper' show patch, ForceInline;
import 'dart:_foreign_helper' show JS;

@patch
@ForceInline()
bool debugger({bool when: true, String message}) {
  if (when) {
    JS('', 'debugger');
  }
  return when;
}

@patch
Object inspect(Object object) {
  return object;
}

@patch
void log(String message,
         {DateTime time,
          int sequenceNumber,
          int level: 0,
          String name: '',
          Zone zone,
          Object error,
          StackTrace stackTrace}) {
  // TODO.
}

final _extensions = new Map<String, ServiceExtensionHandler>();

@patch
ServiceExtensionHandler _lookupExtension(String method) {
  return _extensions[method];
}

@patch
_registerExtension(String method, ServiceExtensionHandler handler) {
  _extensions[method] = handler;
}

@patch
int _getTraceClock() {
  // TODO.
  return _clockValue++;
}
int _clockValue = 0;

@patch
void _reportCompleteEvent(int start,
                          int end,
                          String category,
                          String name,
                          String argumentsAsJson) {
  // TODO.
}

@patch
int _getNextAsyncId() {
  return 0;
}

@patch
void _reportTaskEvent(int start,
                      int taskId,
                      String phase,
                      String category,
                      String name,
                      String argumentsAsJson) {
 // TODO.
}

Add missing patch methods to dart2js implementation of timeline

BUG=

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


import "package:polymorphic_bot/plugin.dart";
export "package:polymorphic_bot/plugin.dart";

@Command("reverse", allowVariables: true)
reverse(CommandEvent event) =>
    event.transform((input) => new String.fromCharCodes(input.codeUnits.reversed));

import "package:polymorphic_bot/plugin.dart";
export "package:polymorphic_bot/plugin.dart";

@Command("reverse", allowVariables: true)
reverse(CommandEvent event) =>
    event.transform((input) => flip(input));

Use Quiver for Reversing Strings

Use Quiver for Reversing Strings


library task;

class TaskNote {
  String notebody;
  TaskNote(this.notebody);
}

class Task {
  String summary;
  List<TaskNote> tasknotes = [];
  DateTime scheduled;
  Set<String> taskcategories = new Set();
  Task(this.summary, this.scheduled);

  void addNote(TaskNote note) {
    tasknotes.add(note);
  }

  void addCategory(String cat ) {
    taskcategories.add(cat);
  }
  void removeCategory(String cat) {
    taskcategories.remove(cat);
  }
}

library task;

class TaskNote {
  String notebody;
  TaskNote(this.notebody);
}

class Task {
  String summary;
  List<TaskNote> tasknotes = [];
  DateTime scheduled;
  int timestamp;
  Set<String> taskcategories = new Set();
  Task(this.summary, this.scheduled) {
    this.timestamp = new DateTime.now().millisecond;
  }

  void addNote(TaskNote note) {
    tasknotes.add(note);
  }

  void addCategory(String cat ) {
    taskcategories.add(cat);
  }
  void removeCategory(String cat) {
    taskcategories.remove(cat);
  }
}

Add timestamp to Task class.

Add timestamp to Task class.


// 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:analysis_server/starter.dart';

/**
 * Create and run an analysis server.
 */
void main(List<String> args) {
  ServerStarter starter = new ServerStarter();
  starter.start(args);
}

// 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:analysis_server/starter.dart';

/**
 * Create and run an analysis server.
 */
void main(List<String> args) async {
  ServerStarter starter = new ServerStarter();
  starter.start(args);
}

Normalize with the internal verison of this file.

Change-Id: I27d56a0f61bb68bfe9f0386dc7b140cdebba4522
Reviewed-on: https://dart-review.googlesource.com/72542
Reviewed-by: Brian Wilkerson <1f7641b6b14c52b9163524ab8d9aabff80176f21@google.com>
Commit-Queue: Devon Carew <e996497f4f2225f0ee7a9f4d1696ee710b488b66@google.com>