// 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.
  withBarbackVersions("any", () {
    integration("fails to load a transform with an import error", () {
      d.dir(appPath, [
        d.pubspec({
          "name": "myapp",
          "transformers": ["myapp/src/transformer"]
        }),
        d.dir("lib", [d.dir("src", [
          d.file("transformer.dart", "import 'does/not/exist.dart';")
        ])])
      ]).create();

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

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

library pub_tests;

import 'package:scheduled_test/scheduled_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.
  withBarbackVersions("any", () {
    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("Uncaught Error: Failure getting "));
      pub.shouldExit(1);
    });
  });
}

Update pub test with "Uncaught Error: " prefix on output.

R=ajohnsen@google.com

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

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@38857 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 byte_stream;

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

import 'utils.dart';

/// A stream of chunks of bytes representing a single piece of data.
class ByteStream extends StreamView<List<int>> {
  ByteStream(Stream<List<int>> stream)
    : super(stream);

  /// Returns a single-subscription byte stream that will emit the given bytes
  /// in a single chunk.
  factory ByteStream.fromBytes(List<int> bytes) =>
    new ByteStream(streamFromIterable([bytes]));

  /// Collects the data of this stream in a [Uint8List].
  Future<Uint8List> toBytes() {
    /// TODO(nweiz): use BufferList when issue 6409 is fixed.
    return reduce(<int>[], (buffer, chunk) {
      buffer.addAll(chunk);
      return buffer;
    }).then(toUint8List);
  }

  /// Collect the data of this stream in a [String], decoded according to
  /// [encoding], which defaults to `Encoding.UTF_8`.
  Future<String> bytesToString([Encoding encoding=Encoding.UTF_8]) =>
      toBytes().then((bytes) => decodeString(bytes, encoding));
}

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

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

import 'utils.dart';

/// A stream of chunks of bytes representing a single piece of data.
class ByteStream extends StreamView<List<int>> {
  ByteStream(Stream<List<int>> stream)
    : super(stream);

  /// Returns a single-subscription byte stream that will emit the given bytes
  /// in a single chunk.
  factory ByteStream.fromBytes(List<int> bytes) =>
    new ByteStream(streamFromIterable([bytes]));

  /// Collects the data of this stream in a [Uint8List].
  Future<Uint8List> toBytes() {
    /// TODO(nweiz): use BufferList when issue 6409 is fixed.
    return reduce(<int>[], (buffer, chunk) {
      buffer.addAll(chunk);
      return buffer;
    }).then(toUint8List);
  }

  /// Collect the data of this stream in a [String], decoded according to
  /// [encoding], which defaults to `Encoding.UTF_8`.
  Future<String> bytesToString([Encoding encoding=Encoding.UTF_8]) =>
      toBytes().then((bytes) => decodeString(bytes, encoding));

  Stream<String> toStringStream([Encoding encoding=Encoding.UTF_8]) =>
      mappedBy((bytes) => decodeString(bytes, encoding));
}

Use the dart:async Stream API thoroughly in Pub.

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

git-svn-id: a0fc6a377c96b9059f80895148836233a16d98be@17821 260f80e4-7a28-3924-810f-c04153c831b5


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

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

import 'runner.dart' as Process; // TODO(chalin) tmp name to avoid code changes
import 'options.dart';
import 'util.dart';

final Logger _logger = new Logger('generate_gh_pages');

/// Returns the path to the folder where the application assets have been
/// generated.
Future<String> generateApplication(
    Directory example, String exampleName) async {
  final applicationPath = p.join(workDirPath, '${exampleName}_app');

  // Copy the application code into a separate folder.
  await Process.run('cp', ['-a', p.join(example.path, '.'), applicationPath]);

  _logger.fine(
      'Adjust router <base href> in index.html so that it works under gh-pages');
  await transformFile(
      p.join(applicationPath, 'web/index.html'),
      (content) => content.replaceAll(
          '<base href="/">', '<base href="/$exampleName/">'));

  _logger.fine("Build the application assets into the 'build' folder");
  await Process.run('pub', ['get'], workingDirectory: applicationPath);
  await Process.run('pub', ['build'], workingDirectory: applicationPath);

  return p.join(applicationPath, 'build/web');
}

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

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

import 'runner.dart' as Process; // TODO(chalin) tmp name to avoid code changes
import 'options.dart';
import 'util.dart';

final Logger _logger = new Logger('generate_gh_pages');

/// Returns the path to the folder where the application assets have been
/// generated.
Future<String> generateApplication(
    Directory example, String exampleName) async {
  final applicationPath = p.join(workDirPath, '${exampleName}_app');

  // Copy the application code into a separate folder.
  await Process.run('cp', ['-a', p.join(example.path, '.'), applicationPath]);

  _logger
      .fine('Adjust <base href> in index.html so that app runs under gh-pages');

  // If the `index.html` either statically or dynamically sets <base href>
  // replace that element by a <base href> appropriate for serving via GH pages.
  final baseHrefEltOrScript = new RegExp(r'<base href="/">|'
      r'<script>(\s|[^<])+<base href(\s|[^<]|<[^/])+</script>');

  final appBaseHref = '<base href="/$exampleName/">';
  await transformFile(
      p.join(applicationPath, 'web/index.html'),
      (String content) =>
          content.replaceFirst(baseHrefEltOrScript, appBaseHref));

  _logger.fine("Build the application assets into the 'build' folder");
  await Process.run('pub', ['get'], workingDirectory: applicationPath);
  await Process.run('pub', ['build'], workingDirectory: applicationPath);

  return p.join(applicationPath, 'build/web');
}

Support setting <base href> even when set dynamically


import 'package:angular/src/runtime.dart';
import 'package:angular/src/di/reflector.dart' as reflector;
import 'package:meta/meta.dart';

import 'component_factory.dart' show ComponentFactory;

/// Transitional API: Returns a [ComponentFactory] for [typeOrFactory].
///
/// If [typeOrFactory] is already a [ComponentFactory] this does nothing.
///
/// This API is slated for removal once the transition to factories is done.
@experimental
ComponentFactory<T> typeToFactory<T>(Object typeOrFactory) =>
    typeOrFactory is ComponentFactory<T>
        ? typeOrFactory
        : unsafeCast<ComponentFactory<T>>(
            reflector.getComponent(unsafeCast<Type>(typeOrFactory)));

import 'package:angular/src/runtime.dart';
import 'package:angular/src/di/reflector.dart' as reflector;
import 'package:meta/meta.dart';

import 'component_factory.dart' show ComponentFactory;

/// Transitional API: Returns a [ComponentFactory] for [typeOrFactory].
///
/// If [typeOrFactory] is already a [ComponentFactory] this does nothing.
///
/// This API is slated for removal once the transition to factories is done.
@experimental
ComponentFactory typeToFactory(Object typeOrFactory) =>
    typeOrFactory is ComponentFactory
        ? typeOrFactory
        : unsafeCast<ComponentFactory>(
            reflector.getComponent(unsafeCast<Type>(typeOrFactory)));

Drop <T> type in typeToFactory.

fix(Internal): Drop <T> type in typeToFactory.

It can never work, because [typeToFactory] doesn't often get a <T> type that is correct.

PiperOrigin-RevId: 190963426


#library("objectory_mirror_requirements_test");
#import("domain_model.dart");
#import("dart:mirrors");
// Possibility to use mirrors currently blocked by lack of VariableMirror.type implementation
// Full support required: For example in class Article we have to reflect on comments as a List of Comment.
//    class Article {
//      ...
//      List<Comment> comments
//    }
//

main() {
  var domainModelLib = currentMirrorSystem().libraries['domain_model'];
  domainModelLib.classes.forEach((name,classMirror) {
    if (classMirror.superinterfaces.length > 0 && classMirror.superinterfaces[0].simpleName == 'PersistentObject') {
      print(classMirror.simpleName);
      classMirror.variables.forEach((name,field) {
// Currently throws error "VariableMirror.type not yet implemented"
//        print(" field $name ${field.simpleName} ${field.type}");
        print(" field $name ${field.simpleName}");
      });
    }
  });
}

#library("objectory_mirror_requirements_test");
#import("domain_model.dart");
#import("dart:mirrors");
// Possibility to use mirrors currently blocked by lack of VariableMirror.type implementation
// Full support required: For example in class Article we have to reflect on comments as a List of Comment.
//    class Article {
//      ...
//      List<Comment> comments
//    }
//

main() {
  var domainModelLib = currentMirrorSystem().libraries['domain_model'];
  domainModelLib.classes.forEach((name,classMirror) {
    if (classMirror.superinterfaces.length > 0 && classMirror.superinterfaces[0].simpleName == 'PersistentObject') {
      print(classMirror.simpleName);
      classMirror.variables.forEach((name,field) {
        print(" field $name ${field.simpleName} ${field.type}");
        if (field.type.simpleName == 'List') {
          var tv = field.type.typeVariables["E"];
          print('       $tv');
          // last unimplemented feature:
          //print(tv.type);
          //print(field.type.typeArguments);
        }
      });
    }
  });
}

Test current situation with mirror

Test current situation with mirror


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

// A regression test for dart2js generating illegal JavaScript code
// dynamically in non-csp mode.  The name of the field "defaultValue"
// in JavaScript is "default".  This meant that dart2js would create a
// constructor function that looked like this:
//
// function TrackElement(default) { this.default = default; }

import 'dart:html';

void main() {
  document.body.append(new TrackElement()..defaultValue = true);
  if (!document.query('track').defaultValue) {
    throw 'Expected default value to be true';
  }
  document.query('track').defaultValue = false;
  if (document.query('track').defaultValue) {
    throw 'Expected default value to be false';
  }
}

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

// A regression test for dart2js generating illegal JavaScript code
// dynamically in non-csp mode.  The name of the field "defaultValue"
// in JavaScript is "default".  This meant that dart2js would create a
// constructor function that looked like this:
//
// function TrackElement(default) { this.default = default; }

import 'dart:html';

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

void main() {
  useHtmlConfiguration();
  test('', () {
    document.body.append(new TrackElement()..defaultValue = true);
    if (!document.query('track').defaultValue) {
      throw 'Expected default value to be true';
    }
    document.query('track').defaultValue = false;
    if (document.query('track').defaultValue) {
      throw 'Expected default value to be false';
    }
  });
}

Use unittest to avoid timeouts on Dartium.

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

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


import 'package:force/force_serverside.dart';

void main() {
  ForceServer fs = new ForceServer(clientFiles: "../client/web/",
      startPage: "index.html");

  fs.setupConsoleLog();

  fs.on("add", (receiver, sender) {
    sender.send("update",
        receiver.json["data"] == "" ? {"data":"Hello World!"} :
        {"data":"Hello ${receiver.json["data"]}!"});
  });

  fs.start();
}

import 'package:force/force_serverside.dart';

void main() {
  ForceServer fs = new ForceServer(clientFiles: "../client/build/web/",
      startPage: "index.html");

  fs.setupConsoleLog();

  fs.on("add", (receiver, sender) {
    sender.send("update",
        receiver.json["data"] == "" ? {"data":"Hello World!"} :
        {"data":"Hello ${receiver.json["data"]}!"});
  });

  fs.start();
}

Set build path as target

Set build path as target


import 'dart:typed_data';

import 'package:archive/archive.dart';
import 'package:test/test.dart';

void main() {
  group('archive', () {
    test('replace existing file', () {
      final archive = Archive();
      archive.addFile(ArchiveFile("a", 1, Uint8List.fromList([0])));
      archive.addFile(ArchiveFile("b", 1, Uint8List.fromList([1])));
      archive.addFile(ArchiveFile("c", 1, Uint8List.fromList([2])));

      archive.addFile(ArchiveFile("b", 1, Uint8List.fromList([3])));

      expect(archive.length, 3);
      expect(archive[0].name, "a");
      expect(archive[1].name, "b");
      expect(archive[2].name, "c");

      expect(archive[0].content[0], 0);
      expect(archive[1].content[0], 3);
      expect(archive[2].content[0], 2);
    });

    test('clear', () {
      final archive = Archive();
      archive.addFile(ArchiveFile("a", 1, Uint8List.fromList([0])));
      archive.addFile(ArchiveFile("b", 1, Uint8List.fromList([1])));
      archive.addFile(ArchiveFile("c", 1, Uint8List.fromList([2])));
      archive.clear();
      expect(archive.length, 0);
    });
  });
}

import 'dart:typed_data';

import 'package:archive/archive.dart';
import 'package:test/test.dart';

void main() {
  group('archive', () {
    test('replace existing file', () {
      final archive = Archive();
      archive.addFile(ArchiveFile("a", 1, Uint8List.fromList([0])));
      archive.addFile(ArchiveFile("b", 1, Uint8List.fromList([1])));
      archive.addFile(ArchiveFile("c", 1, Uint8List.fromList([2])));

      archive.addFile(ArchiveFile("b", 1, Uint8List.fromList([3])));

      archive.addFile(ArchiveFile("陳大文_1_test.png", 1, [4]));

      expect(archive.length, 4);
      expect(archive[0].name, "a");
      expect(archive[1].name, "b");
      expect(archive[2].name, "c");
      expect(archive[3].name, "陳大文_1_test.png");

      expect(archive[0].content[0], 0);
      expect(archive[1].content[0], 3);
      expect(archive[2].content[0], 2);
      expect(archive[3].content[0], 4);
    });

    test('clear', () {
      final archive = Archive();
      archive.addFile(ArchiveFile("a", 1, Uint8List.fromList([0])));
      archive.addFile(ArchiveFile("b", 1, Uint8List.fromList([1])));
      archive.addFile(ArchiveFile("c", 1, Uint8List.fromList([2])));
      archive.clear();
      expect(archive.length, 0);
    });
  });
}

Add non-ascii ArchiveFile name to test

Add non-ascii ArchiveFile name to test


part of alpha.async;

Future<List<dynamic>> where(List<dynamic> input, bool filter(dynamic it)) {
  var completer = new Completer();

  var elements = [];

  new Stream.fromIterable(input)
    .where(filter)
    .listen(elements.add)
    .onDone(() => completer.complete(elements));

  return completer.future;
}

typedef dynamic AsynchronousFunction();

Future async(AsynchronousFunction function) {
  return new Future(function);
}

Add an Asynchronous Function Execution

Add an Asynchronous Function Execution


import 'package:angular2/core.dart';
import 'package:path/path.dart' as path;

// Every Angular application has at least one component: the root component, named AppComponent here.
// Components are the basic building blocks of Angular applications. A component controls a portion of the screen—a view—through its associated template.
@Component(
    selector: 'my-app',
    templateUrl: "app_component.html")
class AppComponent {
  static const String baseURL = "http://127.0.0.1:8080/api";

  // Based on https://webdev.dartlang.org/articles/get-data/json-web-service
  void loadData() {
    var url = path.join(baseURL, "questions");

    // Call the web server asynchronously
    var request = HttpRequest.getString(url).then(onDataLoaded);
  }

  void onDataLoaded(String responseText) {
    var jsonString = responseText;
    print(jsonString);
  }
}

import 'package:angular2/core.dart';
import 'package:path/path.dart' as path;
import 'dart:html';
import 'dart:convert';

// Every Angular application has at least one component: the root component, named AppComponent here.
// Components are the basic building blocks of Angular applications. A component controls a portion of the screen—a view—through its associated template.
@Component(
    selector: 'my-app',
    templateUrl: "app_component.html")
class AppComponent {
  static const String baseURL = "http://127.0.0.1:8080/api";
  List questions;

  AppComponent() {
    loadData();
  }

  // Based on https://webdev.dartlang.org/articles/get-data/json-web-service
  void loadData() {
    var url = path.join(baseURL, "questions");

    // Call the web server asynchronously
    var request = HttpRequest.getString(url).then(onDataLoaded);
  }

  void onDataLoaded(String responseText) {
    var dataFromJson = JSON.decode(responseText);

    questions = new List<Question>();
    for (var obj in dataFromJson) {
      questions.add(new Question.fromJSON(obj));
    }
  }
}

class Question {
  int id;
  String description;
  String answer;

  Question(this.id, this.description, this.answer);
  factory Question.fromJSON(Map<String, dynamic> qst) =>
    new Question(_toInt(qst['index']), qst['description'], qst['answer']);

  Map toJSON() => {'index': id, 'description': description, 'answer': answer};
}

int _toInt(id) => id is int ? id : int.parse(id);

Load questions as objects from Aqueduct to Angular.


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

@TestOn('vm')
import 'package:test/test.dart';
import 'package:angular_router/src/url.dart';

void main() {
  group('$Url', () {
    group('parse', () {
      Url url;

      setUpAll(() {
        url = Url.parse('/foo?bar=true&path/param/key=uri?param#baz');
      });

      test('should parse the path', () {
        expect(url.path, '/foo');
      });

      test('should parse the fragment', () {
        expect(url.fragment, 'baz');
      });

      test('should parse the queryParameters', () {
        expect(url.queryParameters,
            {'bar': 'true', 'path/param/key': 'uri?param'});
      });
    });

    test('toUrl should return a Url string', () {
      var url1 = new Url('/1', fragment: '2', queryParameters: {'3': 'true'});
      expect(url1.toUrl(), '/1?3=true#2');
    });
  });
}

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

import 'package:test/test.dart';
import 'package:angular_router/src/url.dart';

void main() {
  group('$Url', () {
    group('parse', () {
      Url url;

      setUpAll(() {
        url = Url.parse('/foo?bar=true&path/param/key=uri?param#baz');
      });

      test('should parse the path', () {
        expect(url.path, '/foo');
      });

      test('should parse the fragment', () {
        expect(url.fragment, 'baz');
      });

      test('should parse the queryParameters', () {
        expect(url.queryParameters,
            {'bar': 'true', 'path/param/key': 'uri?param'});
      });
    });

    test('toUrl should return a Url string', () {
      var url1 = new Url('/1', fragment: '2', queryParameters: {'3': 'true'});
      expect(url1.toUrl(), '/1?3=true#2');
    });
  });
}

Migrate VM tests to Web

Migrate VM tests to Web

We will soon enforce that vm tests have dependencies that declare support for the vm platform. These tests transitively depend on web only targets, thus we must migrate them to web tests. There will be a minor performance impact because of this change. If you would like to revert the change, please consider cleaning up your build dependencies.

To determine which dependencies are web only targets, patch in cl/185764361 and revert this change. These tests will fail at build time with an explicit error detailing the offending packages.

Tested:
    TAP for global presubmit queue
    http://test/OCL:185868364:BASE:185868394:1518724559570:4c7a0388
PiperOrigin-RevId: 185892493


// 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 '../../framework/fn.dart';
import '../../framework/components/button.dart';

class WidgetsApp extends App {
  Node build() {
    return new Button(content: new Text('Go'), level: 1);
  }
}

// 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 '../../framework/fn.dart';
import '../../framework/components/button.dart';
import '../../framework/components/popup_menu.dart';
import '../../framework/components/popup_menu_item.dart';

class WidgetsApp extends App {
  static final Style _menuStyle = new Style('''
    position: absolute;
    top: 200px;
    left: 200px;''');

  Node build() {
    return new Container(
      children: [
        new Button(key: 'Go', content: new Text('Go'), level: 1),
        new Button(key: 'Back', content: new Text('Back'), level: 3),
        new Container(
          style: _menuStyle,
          children: [
            new PopupMenu(
              children: [
                  new PopupMenuItem(key: '1', children: [new Text('People & options')]),
                  new PopupMenuItem(key: '2', children: [new Text('New group conversation')]),
                  new PopupMenuItem(key: '3', children: [new Text('Turn history off')]),
                  new PopupMenuItem(key: '4', children: [new Text('Archive')]),
                  new PopupMenuItem(key: '5', children: [new Text('Delete')]),
                  new PopupMenuItem(key: '6', children: [new Text('Un-merge SMS')]),
                  new PopupMenuItem(key: '7', children: [new Text('Help & feeback')]),
              ],
              level: 4),
            ]
          )
        ]
      );
  }
}

Add a basic popup menu widget

Add a basic popup menu widget

Currently this widget is demoed in widgets-fn, but I'll move it into stocks-fn
soon.

R=eseidel@chromium.org

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


/// Calculator from the tutorial.
library petitparser.example.calc;

import 'package:petitparser/petitparser.dart';

void main(List<String> arguments) {
  final number = digit().plus().flatten().trim().map(int.parse);
  final term = undefined();
  final prod = undefined();
  final prim = undefined();
  final start = term.end();

  term.set(prod
      .seq(char('+').trim())
      .seq(term)
      .map((values) => values[0] + values[2])
      .or(prod));
  prod.set(prim
      .seq(char('*').trim())
      .seq(prod)
      .map((values) => values[0] * values[2])
      .or(prim));
  prim.set(char('(')
      .trim()
      .seq(term)
      .seq(char(')').trim())
      .map((values) => values[1])
      .or(number));

  print(start.parse(arguments.join(' ')).value);
}

/// Calculator from the tutorial.
library petitparser.example.calc;

import 'dart:math';
import 'package:petitparser/petitparser.dart';

Parser buildParser() {
  final builder = ExpressionBuilder();
  builder.group()
    ..primitive((pattern('+-').optional() &
            digit().plus() &
            (char('.') & digit().plus()).optional() &
            (pattern('eE') & pattern('+-').optional() & digit().plus())
                .optional())
        .flatten('number expected')
        .trim()
        .map(num.tryParse));
  builder.group()..prefix(char('-').trim(), (op, a) => -a);
  builder.group()..right(char('^').trim(), (a, op, b) => pow(a, b));
  builder.group()
    ..left(char('*').trim(), (a, op, b) => a * b)
    ..left(char('/').trim(), (a, op, b) => a / b);
  builder.group()
    ..left(char('+').trim(), (a, op, b) => a + b)
    ..left(char('-').trim(), (a, op, b) => a - b);
  return builder.build().end();
}

void main(List<String> arguments) {
  final parser = buildParser();
  final input = arguments.join(' ');
  final result = parser.parse(input);
  if (result.isSuccess) {
    print(' = ${result.value}');
  } else {
    print(input);
    print('${' ' * (result.position - 1)}^-- ${result.message}');
  }
}

Use the expression builder in the example.


import 'package:unittest/unittest.dart';
import 'package:workmantrainer/textmarker.dart';

void main() {
  test('check initialisation of TextMarker Class works.', () {
    var tm = new TextMarker('some text',0,2,"CORRECT");
    expect(tm.targettext, 'some text');
    expect(tm.startposition,0);
    expect(tm.endposition,2);
    expect(tm.textState, 'CORRECT');
  });
}

Add test for Class initialisation.

Add test for Class initialisation.


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

// Test that it is an error for a class with no generative constructors to
// have a final instance variable without an initializing expression, except
// if it is `abstract` or `external`. The latter also holds in a class with
// generative constructors.

// Has factory, hence no default, hence no generative constructors.
abstract class A {
  final dynamic n;
  //            ^
  // [analyzer] COMPILE_TIME_ERROR.FINAL_NOT_INITIALIZED
  // [cfe] unspecified

  // Uninitialized, but no errors.
  abstract final int x1;
  abstract final int? x2;
  external final String x3;
  external final String? x4;

  factory A() = B;
}

class B implements A {
  dynamic get n => 1;
  int get x1 => 1;
  int? get x2 => null;
  String get x3 => "";
  String? get x4 => null;
}

class C = Object with A;

// Has a generative constructor: default.
abstract class D {
  // Uninitialized, but no errors.
  abstract final int x1;
  abstract final int? x2;
  external final String x3;
  external final String? x4;
}

void main() {
  A();
  C();
  var _ = D;
}

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

// Test that it is an error for a class with no generative constructors to
// have a final instance variable without an initializing expression, except
// if it is `abstract` or `external`. The latter also holds in a class with
// generative constructors.

// Has factory, hence no default, hence no generative constructors.
abstract class A {
  final dynamic n;
  //            ^
  // [analyzer] COMPILE_TIME_ERROR.FINAL_NOT_INITIALIZED
  // [cfe] unspecified

  // Uninitialized, but no errors.
  abstract final int x1;
  abstract final int? x2;
  external final String x3;
  external final String? x4;

  factory A() = B;
}

class B implements A {
  dynamic get n => 1;
  int get x1 => 1;
  int? get x2 => null;
  String get x3 => "";
  String? get x4 => null;
}

class C = Object with A;
  //  ^
  // [analyzer] COMPILE_TIME_ERROR.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER

// Has a generative constructor: default.
abstract class D {
  // Uninitialized, but no errors.
  abstract final int x1;
  abstract final int? x2;
  external final String x3;
  external final String? x4;
}

void main() {
  A();
  C();
  var _ = D;
}

Fix test for abstract field, not impelemnetd by the mixin application.

Change-Id: I1d12a70a82a859d57516948672ed6a931904ae7a
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/161626
Reviewed-by: Brian Wilkerson <1f7641b6b14c52b9163524ab8d9aabff80176f21@google.com>
Reviewed-by: Leaf Petersen <9bef692239b5f624cec8e2cd5249ab1939a377aa@google.com>
Commit-Queue: Konstantin Shcheglov <09e4d7516628963212bf4aace2f97603d2b706e4@google.com>


@TestOn('browser')
library quark.test.contexts.html;

import 'package:test/test.dart';
import 'package:quark/integration.dart';
import 'package:quark/contexts/html.dart';
import '../mock_runner.dart';
import 'dart:html';
import 'dart:async';

class HtmlContextIntegrationTest = IntegrationTest with HtmlContext;

main() {
  MockRunner runner;

  setUp(() {
    runner = new MockRunner();
  });

  Future runShouldSucceed(String gherkin) async {
    final t = new HtmlContextIntegrationTest();
    t.useFeature(gherkin);
    await t.register(runner);
  }

  Future runShouldFail(String gherkin, [matching]) async {
    try {
      final completer = new Completer();
      runZoned(() {
        return runShouldSucceed(gherkin);
      }, onError: completer.completeError,
          zoneSpecification: new ZoneSpecification());
      await completer.future.timeout(
          const Duration(seconds: 10), onTimeout: () {
        fail('Test did not fail');
      });
    } catch (e) {
      if (matching != null)
        expect(e, matching);
    }
  }

  test('see on page', () async {
    final feature = '''
      Feature
        Scenario
          Then I see "content"
          Then I expect to see "content"
          Then I can see "content"
          Then I should see "content" on the page
          Then I should see "content" on the screen
    ''';
    await runShouldFail(feature);
    querySelector('body').appendText('content');
    await runShouldSucceed(feature);
  });
}

@TestOn('browser')
library quark.test.contexts.html;

import 'package:test/test.dart';
import 'package:quark/integration.dart';
import 'package:quark/contexts/html.dart';
import '../mock_runner.dart';
import 'dart:html';
import 'dart:async';

class HtmlContextIntegrationTest = IntegrationTest with HtmlContext;

main() {
  MockRunner runner;

  setUp(() {
    runner = new MockRunner();
  });

  Future runShouldSucceed(String gherkin) async {
    final t = new HtmlContextIntegrationTest();
    t.useFeature(gherkin);
    t.register(runner);
    await runner.run();
  }

  Future runShouldFail(String gherkin, [matching]) async {
    try {
      await runShouldSucceed(gherkin);
      fail('Test did not fail');
    } catch (e) {
      if (matching != null)
        expect(e, matching);
    }
  }
  test('see on page', () async {
    final feature = '''
      Feature
        Scenario
          Then I see "content"
          Then I expect to see "content"
          Then I can see "content"
          Then I should see "content" on the page
          Then I should see "content" on the screen
    ''';
    await runShouldFail(feature);
    querySelector('body').appendText('content');
    await runShouldSucceed(feature);
  });
}

Clean up context test given new async test mocking


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

/// The colorful library.
library colorful;

import 'package:color/color.dart';
import 'dart:math';

class ColorPalette {
  final int size;
  final double saturation;
  final double lightness;
  List<Color> colors = new List();

  ColorPalette(this.size, this.saturation, this.lightness) {
    var hr = hueRange(randomHue());
    hr.forEach((i) => colors.add(new Color.hsl(i, this.saturation, this.lightness)));
  }

  double randomHue() {
    var rand = new Random();
    return rand.nextInt(360).toDouble();
  }

  List<double> hueRange(double startValue) {
    var distance = 360.0 / this.size;
    var hrange = [startValue];
    var hue = startValue + distance;
    for (int i = 1;i < this.size; i++){
      hrange.add(hue % 360);
      hue += distance;
    }
    return hrange;
  }
}

class SoftPalette extends ColorPalette {

}

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

/// The colorful library.
library colorful;

import 'package:color/color.dart';
import 'dart:math';

class ColorPalette {
  final int size;
  final double saturation;
  final double lightness;
  List<Color> colors = new List();

  ColorPalette(this.size, this.saturation, this.lightness) {
    var hr = hueRange(randomHue());
    hr.forEach((i) => colors.add(new Color.hsl(i, saturation, lightness)));
  }

  double randomHue() {
    var rand = new Random();
    return rand.nextInt(360).toDouble();
  }

  List<double> hueRange(double startValue) {
    var distance = 360.0 / this.size;
    var hrange = [startValue];
    var hue = startValue + distance;
    for (int i = 1;i < this.size; i++){
      hrange.add(hue % 360);
      hue += distance;
    }
    return hrange;
  }
}

class SoftPalette extends ColorPalette {

}

Remove keyword this from constructor

Remove keyword this from constructor


// Generated by Spine Proto Dart Gradle plugin.
//
// https://github.com/SpineEventEngine/base
//
// Do NOT edit this file manually.
//

import "package:protobuf/protobuf.dart";

// @import@

Map<String, BuilderInfo> typeUrlToInfo = {
  // @type-to-info@

};

Map<GeneratedMessage, String> defaultToTypeUrl = {
  // @message-to-type@

};

// Generated by Spine Proto Dart Gradle plugin.
//
// https://github.com/SpineEventEngine/base
//
// Do NOT edit this file manually.
//

import "package:protobuf/protobuf.dart";

// @import@

Map<String, BuilderInfo> _typeUrlToInfo = {
  // @type-to-info@
};

Map<GeneratedMessage, String> _defaultToTypeUrl = {
  // @message-to-type@
};

dynamic types() {
    return _KnownTypesPart(_typeUrlToInfo, _defaultToTypeUrl);
}

class _KnownTypesPart {

    final Map<String, BuilderInfo> typeUrlToInfo;
    final Map<GeneratedMessage, String> defaultToTypeUrl;

    _KnownTypesPart(this.typeUrlToInfo, this.defaultToTypeUrl);
}

Make generated Dart type registry more useful


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

// example websocket server
// listens on ws://dart.dyndns.dk:15000
main(){
  listen(HttpServer server){
      print("listening for new connection");
      var sc = new StreamController();
      sc.stream
        .transform(new WebSocketTransformer())
        .listen((WebSocket ws) {
            int i = 0;
            ws.listen((data) {
              print("received: $data");
              ws.send("${i++}: $data");
              if( i > 10) ws.close();
              });
            });
      server.listen(sc.add);
  }
  HttpServer.bind("0.0.0.0",5000,0).then(listen);
}

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

// example websocket server
// listens on ws://dart.dyndns.dk:15000
main(){
  listen(HttpServer server){
      print("listening for new connection");
      var sc = new StreamController();
      sc.stream
        .transform(new WebSocketTransformer())
        .listen((WebSocket ws) {
            int i = 0;
            ws.listen((data) {
              print("received: $data");
              ws.add("${i++}: $data");
              if( i > 10) ws.close();
              });
            });
      server.listen(sc.add);
  }
  HttpServer.bind("0.0.0.0",5000,0).then(listen);
}

Send method changed to add in WebSocket

Send method changed to add in WebSocket


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

class PrivateFactoryResolutionTest {

  static testMain() {
    new TypeError._uninstantiable();
  }
}

main() {
  PrivateFactoryResolutionNegativeTest.testMain();
}

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

class PrivateFactoryResolutionNegativeTest {

  static testMain() {
    new TypeError._uninstantiable();
  }
}

main() {
  PrivateFactoryResolutionNegativeTest.testMain();
}

Improve frog error reporting when providing too few or too many arguments.

This is a partial re-landing of r3720, but without getting rid of the
duplicate errors and warnings.

R=floitsch@google.com
BUG=
TEST=

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

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


import 'dart:async';

import 'package:build/build.dart';
import 'package:angular/src/transform/common/names.dart';
import 'package:angular_compiler/angular_compiler.dart';

import 'processor.dart';

Builder stylesheetCompiler(BuilderOptions options) {
  final flags = new CompilerFlags.parseRaw(
      options.config, const CompilerFlags(genDebugInfo: false));
  return new StylesheetCompiler(flags);
}

/// Pre-compiles CSS stylesheet files to Dart code for Angular 2.
class StylesheetCompiler implements Builder {
  final CompilerFlags _flags;

  StylesheetCompiler(this._flags);

  @override
  final buildExtensions = {
    CSS_EXTENSION: const [
      SHIMMED_STYLESHEET_EXTENSION,
      NON_SHIMMED_STYLESHEET_EXTENSION
    ]
  };

  @override
  Future build(BuildStep buildStep) async {
    final outputs =
        await processStylesheet(buildStep, buildStep.inputId, _flags);
    outputs.forEach(buildStep.writeAsString);
  }
}

import 'dart:async';

import 'package:build/build.dart';
import 'package:angular/src/transform/common/names.dart';
import 'package:angular_compiler/angular_compiler.dart';

import 'processor.dart';

Builder stylesheetCompiler(BuilderOptions options) {
  final flags = new CompilerFlags.parseRaw(
    options.config,
    const CompilerFlags(genDebugInfo: false),
  );
  return new StylesheetCompiler(flags);
}

/// Pre-compiles CSS stylesheet files to Dart code for Angular 2.
class StylesheetCompiler implements Builder {
  final CompilerFlags _flags;

  const StylesheetCompiler(this._flags);

  @override
  final buildExtensions = const {
    CSS_EXTENSION: const [
      SHIMMED_STYLESHEET_EXTENSION,
      NON_SHIMMED_STYLESHEET_EXTENSION,
    ],
  };

  @override
  Future build(BuildStep buildStep) async {
    final outputs = await processStylesheet(
      buildStep,
      buildStep.inputId,
      _flags,
    );
    outputs.forEach(buildStep.writeAsString);
  }
}

refactor(Compiler): Use trailing commas for DSLs, and make something const.

PiperOrigin-RevId: 177529991


import "package:bitesize_screencasts/customer/customer.dart";
import "package:intl/intl.dart";
import "dart:html";

final wealthFormatter = new NumberFormat("###,###,###", "en_US");

void main () {

  Customer bruceWillis = new Customer("Bruce", "Willis", 59, 25000000);
  Customer johnMcClane = new Customer("John", "McClane", 32, 40000);

  writeCustomerToDiv(bruceWillis, "customer1");
  writeCustomerToDiv(johnMcClane, "customer2");

  document.querySelector("#mergeButton").onClick.listen((_) {
    Customer mergedCustomer = bruceWillis.merge(johnMcClane);
    print("Merged Customer Age: ${mergedCustomer.age}");
    writeCustomerToDiv(mergedCustomer, "mergedCustomer");
  });

}

void writeCustomerToDiv(Customer customer, String divId) {
  Element element = document.querySelector("#$divId");
  element.querySelector(".name").setInnerHtml("${customer.firstName} ${customer.lastName}");
  element.querySelector(".age").setInnerHtml(customer.age.toString());
  element.querySelector(".wealth").setInnerHtml(wealthFormatter.format(customer.wealth));
}

import "package:bitesize_screencasts/customer/customer.dart";
import "package:intl/intl.dart";
import "dart:html";

final wealthFormatter = new NumberFormat("###,###,###", "en_US");

Customer bruceWillis = new Customer("Bruce", "Willis", 59, 25000000);
Customer johnMcClane = new Customer("John", "McClane", 32, 40000);

void main () {
  writeCustomerToDiv(bruceWillis, "customer1");
  writeCustomerToDiv(johnMcClane, "customer2");

  document.querySelector("#mergeButton").onClick.listen(onMergeClick);
}

void onMergeClick(_) {
  Customer mergedCustomer = bruceWillis.merge(johnMcClane);
  print("Merged Customer Age: ${mergedCustomer.age}");
  writeCustomerToDiv(mergedCustomer, "mergedCustomer");
}

void writeCustomerToDiv(Customer customer, String divId) {
  Element element = document.querySelector("#$divId");
  element.querySelector(".name").setInnerHtml("${customer.firstName} ${customer.lastName}");
  element.querySelector(".age").setInnerHtml(customer.age.toString());
  element.querySelector(".wealth").setInnerHtml(wealthFormatter.format(customer.wealth));
}

Refactor customer merge click handler to be its own method


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

/**
 * This contains a reader that accesses data using the HttpRequest
 * facility, and thus works only in the web browser.
 */

library http_request_data_reader;

import 'dart:async';
import 'dart:html';
import 'intl_helpers.dart';

class HTTPRequestDataReader implements LocaleDataReader {

  /** The base url from which we read the data. */
  String url;
  HTTPRequestDataReader(this.url);

  Future read(String locale) {
    // TODO(alanknight): Remove this once it's not necessary for Chrome.
    // Without it, the tests will be flaky on Chrome. Issue 11834.
    var someNumber = new DateTime.now().millisecondsSinceEpoch;
    return HttpRequest.getString('$url$locale.json?cacheBlocker=$someNumber');
  }
}

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

/**
 * This contains a reader that accesses data using the HttpRequest
 * facility, and thus works only in the web browser.
 */

library http_request_data_reader;

import 'dart:async';
import 'dart:html';
import 'intl_helpers.dart';

class HTTPRequestDataReader implements LocaleDataReader {

  /** The base url from which we read the data. */
  String url;
  HTTPRequestDataReader(this.url);

  Future read(String locale) {
    // TODO(alanknight): Remove this once it's not necessary for Chrome.
    // Without it, the tests will be flaky on Chrome. Issue 11834.
    var someNumber = new DateTime.now().millisecondsSinceEpoch;
    var request = new HttpRequest();
    request.timeout = 5000;
    return _getString('$url$locale.json?cacheBlocker=$someNumber', request)
      .then((r) => r.responseText);
  }

  /// Read a string with the given request. This is a stripped down copy
  /// of HttpRequest getString, but was the simplest way I could find to
  /// issue a request with a timeout.
  Future<HttpRequest> _getString(String url, HttpRequest xhr) {
    var completer = new Completer<HttpRequest>();
    xhr.open('GET', url, async: true);
    xhr.onLoad.listen((e) {
      // Note: file:// URIs have status of 0.
      if ((xhr.status >= 200 && xhr.status < 300) ||
          xhr.status == 0 || xhr.status == 304) {
        completer.complete(xhr);
      } else {
        completer.completeError(e);
      }
    });

    xhr.onError.listen(completer.completeError);
    xhr.send();

    return completer.future;
  }
}

Add a timeout on HttpRequestDataReader

Add a timeout on HttpRequestDataReader

BUG=
R=efortuna@google.com

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

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


// Copyright (c) 2015 Justin Andresen. All rights reserved.
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.

library toml.example.string;

import 'package:toml/toml.dart';

var toml = '''
[table]
  [[table.array]]
  key = "Hello, World!"
''';

void main() {
  var parser = new TomlParser();
  var result = parser.parse(toml);
  var config = result.value;
  print(config['table']['array'][0]['key']);
}

// Copyright (c) 2015 Justin Andresen. All rights reserved.
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.

library toml.example.string;

import 'package:toml/decoder.dart';

var toml = '''
[table]
  [[table.array]]
  key = "Hello, World!"
''';

void main() {
  var parser = new TomlParser();
  var result = parser.parse(toml);
  var config = result.value;
  print(config['table']['array'][0]['key']);
}

Use new `decoder` library in examples.

Use new `decoder` library in examples.


library sprites;

import 'dart:sky';
import 'dart:math' as Math;
import 'package:vector_math/vector_math_64.dart';
import 'package:sky/framework/app.dart';
import 'package:sky/framework/rendering/box.dart';
import 'package:sky/framework/rendering/node.dart';
import 'package:sky/framework/scheduler.dart' as scheduler;
import 'package:sky/framework/net/image_cache.dart' as image_cache;

part 'sprite_box.dart';
part 'transform_node.dart';
part 'sprite_node.dart';
part 'image_map.dart';

library sprites;

import 'dart:sky';
import 'dart:math' as Math;
import 'package:vector_math/vector_math_64.dart';
import 'package:sky/framework/app.dart';
import 'package:sky/framework/rendering/box.dart';
import 'package:sky/framework/rendering/object.dart';
import 'package:sky/framework/scheduler.dart' as scheduler;
import 'package:sky/framework/net/image_cache.dart' as image_cache;

part 'sprite_box.dart';
part 'transform_node.dart';
part 'sprite_node.dart';
part 'image_map.dart';

Fix examples/game to work after Hixie's grand rename.

TBR=viktorl@google.com

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


part of monadart;

class ResourceRequest {

  final HttpRequest request;
  HttpResponse get response => request.response;

  Map<String, String> pathParameters = null;
  Map<dynamic, dynamic> context = null;

  ResourceRequest(HttpRequest req) : request = req {

  }

}

part of monadart;

class ResourceRequest {

  final HttpRequest request;
  HttpResponse get response => request.response;

  Map<String, String> pathParameters = null;
  Map<dynamic, dynamic> context = new Map();

  ResourceRequest(this.request) {

  }

}

Fix to ResourceRequest, cleaned up init

Fix to ResourceRequest, cleaned up init


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

/**
 * Handles the `list` pub command. This is mostly just used so we can pull
 * some basic data out of pub in the integration tests. Once pub is more
 * full-featured and has other commands that test everything it does, this
 * may go away.
 */
class ListCommand extends PubCommand {
  String get description() => 'print the contents of repositories';

  void onRun() {
    cache.listAll().then((packages) {
      for (final package in packages) {
        print(package.name);
      }
    });
  }
}

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

/**
 * Handles the `list` pub command. This is mostly just used so we can pull
 * some basic data out of pub in the integration tests. Once pub is more
 * full-featured and has other commands that test everything it does, this
 * may go away.
 */
class ListCommand extends PubCommand {
  String get description() => 'print the contents of repositories';

  void onRun() {
    cache.listAll().then((packages) {
      packages.sort((a, b) => a.name.compareTo(b.name));
      for (final package in packages) {
        print(package.name);
      }
    });
  }
}

Sort packages before listing them.

Sort packages before listing them.

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

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


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

abstract class PermutationsSettings implements JsOptimizationSettings {
  Setting<bool> get verbose;

  final expectedPartCounts =
      new Setting<Map>('expectedPartCounts', defaultValue: {});

  final potentialLocales = new Setting<List<String>>('potentialLocales',
      defaultValue: numberFormatSymbols.keys.toList());

  final ltrImport = new Setting<String>('ltrImport');
  final rtlImport = new Setting<String>('rtlImport');

  final generatePermutations = makeBoolSetting('generatePermutations');

  final reoptimizePermutations =
      makeOptimSetting('reoptimizePermutations', false);
}

class _PermutationsSettings extends SettingsBase
    with PermutationsSettings, JsOptimizationSettings {
  _PermutationsSettings(settings) : super(settings);
}

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

abstract class PermutationsSettings implements JsOptimizationSettings {
  Setting<bool> get verbose;

  final expectedPartCounts =
      new Setting<Map>('expectedPartCounts', defaultValue: {});

  final potentialLocales = new Setting<List<String>>('potentialLocales',
      defaultValue: numberFormatSymbols.keys.toList());

  final ltrImport = new Setting<String>('ltrImport');
  final rtlImport = new Setting<String>('rtlImport');
  final defaultLocale = new Setting<String>('defaultLocale',
      defaultValue: "en_US");

  final generatePermutations = makeBoolSetting('generatePermutations');

  final reoptimizePermutations =
      makeOptimSetting('reoptimizePermutations', false);
}

class _PermutationsSettings extends SettingsBase
    with PermutationsSettings, JsOptimizationSettings {
  _PermutationsSettings(settings) : super(settings);
}

Introduce default locale setting for permutations transformer


part of streamy.runtime;

final _observableJsonCodec = new JsonCodec.withReviver(_observableReviver);

/// Parses JSON into [Observable] lists and maps.
dynamic jsonParse(String json) {
  return _observableJsonCodec.decode(json);
}

_observableReviver(dynamic key, dynamic value) {
  if (value is Observable) {
    return value;
  } else if (value is List) {
    return new ObservableList.from(value);
  } else if (value is Map) {
    return new ObservableMap.from(value);
  } else {
    return value;
  }
}

part of streamy.runtime;

final _observableJsonCodec = new JsonCodec.withReviver(_observableReviver);

/// Parses JSON into [Observable] lists and maps.
dynamic jsonParse(String json) {
  return _observableJsonCodec.decode(json);
}

_observableReviver(dynamic key, dynamic value) {
  if (value is List) {
    return new ObservableList.from(value);
  } else {
    return value;
  }
}

Remove unnecessary observable wrapping logic


library sample_api;

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

import 'package:rpc/rpc.dart';

final List<String> names = ['Joe', 'John', 'Doe', 'Dohn'];

class StringResponse {
  String response;
  StringResponse(this.response);
}

@ApiClass(name: 'sample', version: 'v1')
class SampleApi {
  @ApiMethod(method: 'GET', path: 'hello/{name}')
  Future<StringResponse> hello(String name) async {
    if (names.contains(name) == false) {
      throw new RpcError(101, 'Name not found', '$name doesn\'t exists');
    }

    return new StringResponse('Hello, $name');
  }
}

library sample_api;

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

import 'package:rpc/rpc.dart';

final List<String> names = ['Joe', 'John', 'Doe', 'Dohn'];

class StringResponse {
  String response;
  StringResponse(this.response);
}

@ApiClass(name: 'sample', version: 'v1')
class SampleApi {
  @ApiMethod(method: 'GET', path: 'hello/{name}')
  StringResponse hello(String name) {
    if (names.contains(name) == false) {
      throw new RpcError(HttpStatus.NOT_FOUND, 'Name not found', '$name doesn\'t exists');
    }

    return new StringResponse('Hello, $name');
  }

  @ApiMethod(method: 'GET', path: 'helloasync/{name}')
  Future<StringResponse> helloAsync(String name) async {
    if (names.contains(name) == false) {
      throw new RpcError(HttpStatus.NOT_IMPLEMENTED, 'Name not found', '$name doesn\'t exists');
    }

    return new StringResponse('Hello, $name');
  }
}

Add hello api method without async

Add hello api method without async


library parser_tests;

import 'package:irc/parser.dart';
import 'package:unittest/unittest.dart';

main() {
  group("Hostmask", () {
    var inputs = {
      "samrg472!~deathcraz@I.got.g-lined.cu.cc": (it) {
        if (it.nickname != "samrg472") {
          throw new Exception("nickname: ${it.nickname}");
        }

        if (it.hostname != "I.got.g-lined.cu.cc") {
          throw new Exception("hostmask: ${it.hostmask}");
        }

        if (it.identity != "~deathcraz") {
          throw new Exception("identity: ${it.identity}");
        }
        return true;
      }
    };

    for (var input in inputs.keys) {
      test(input, () {
        var hostmask = new Hostmask.parse(input);
        var checker = inputs[input];
        expect(checker(hostmask), equals(true));
      });
    }
  });
}

library parser_tests;

import 'package:irc/parser.dart';
import 'package:unittest/unittest.dart';

typedef dynamic InputChecker<T>(T value);

main() {
  group("Hostmask", () {
    var inputs = <String, InputChecker<Hostmask>>{
      "samrg472!~deathcraz@I.got.g-lined.cu.cc": (it) {
        if (it.nickname != "samrg472") {
          throw new Exception("nickname: ${it.nickname}");
        }

        if (it.hostname != "I.got.g-lined.cu.cc") {
          throw new Exception("hostmask: ${it.hostmask}");
        }

        if (it.identity != "~deathcraz") {
          throw new Exception("identity: ${it.identity}");
        }
        return true;
      }
    };

    for (var input in inputs.keys) {
      test(input, () {
        var hostmask = new Hostmask.parse(input);
        var checker = inputs[input];
        expect(checker(hostmask), equals(true));
      });
    }
  });

  group("Regex IrcParser", () {
    var parser = new RegexIrcParser();
    var inputs = <String, InputChecker<Message>>{
      ":OverbotDL1!~OverbotDL@74.195.31.2 PRIVMSG kaendfinger :Overbot 0.1.14": (it) {
        if (it.parameters.length != 1) {
          throw new Exception("parameters length: ${it.params.length}");
        }

        if (it.parameters[0] != "kaendfinger") {
          throw new Exception("target: ${it.params[1]}");
        }

        if (it.message != "Overbot 0.1.14") {
          throw new Exception("message: ${it.message}");
        }

        return true;
      }
    };

    for (var input in inputs.keys) {
      test(input, () {
        var checker = inputs[input];
        var message = parser.convert(input);
        expect(checker(message), equals(true));
      });
    }
  });
}

Add Test for Message IRC Parser

Add Test for Message IRC Parser


import 'dart:async';

import 'dart_doc_syncer.dart' as syncer;

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

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

import 'dart:async';

import 'dart_doc_syncer.dart' as syncer;

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

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

Use ssh for github repositories.

Use ssh for github repositories.


import 'package:campus_mobile_experimental/app_styles.dart';
import 'package:campus_mobile_experimental/core/models/notices.dart';
import 'package:campus_mobile_experimental/ui/common/image_loader.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';

class NoticesCard extends StatelessWidget {
  const NoticesCard({
    Key? key,
    required this.notice,
  }) : super(key: key);

  final NoticesModel notice;

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: EdgeInsets.only(
          top: 0.0, right: 0.0, bottom: cardMargin * 1.5, left: 0.0),
      child: buildBannerView(notice),
    );
  }

  Widget buildBannerView(NoticesModel notice) {
    return GestureDetector(
        onTap: () {
          openLink(notice.link!);
        },
        child: ImageLoader(
          url: notice.imageUrl,
          fullSize: true,
        ));
  }

  openLink(String url) async {
    try {
      launch(url, forceSafariVC: true);
    } catch (e) {
      // an error occurred, do nothing
    }
  }
}

import 'package:campus_mobile_experimental/app_styles.dart';
import 'package:campus_mobile_experimental/core/models/notices.dart';
import 'package:campus_mobile_experimental/ui/common/image_loader.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';

class NoticesCard extends StatelessWidget {
  const NoticesCard({
    Key? key,
    required this.notice,
  }) : super(key: key);

  final NoticesModel notice;

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: EdgeInsets.only(
          top: 0.0, right: 0.0, bottom: cardMargin * 1.5, left: 0.0),
      child: buildBannerView(notice),
    );
  }

  Widget buildBannerView(NoticesModel notice) {
    // The screen reader will read - "image - (text on the image)"
    return Semantics(
      label: notice.title,
      image: true,
      button: true,
      child: GestureDetector(
          onTap: () {
            openLink(notice.link!);
          },
          child: ImageLoader(
            url: notice.imageUrl,
            fullSize: true,
          )),
    );
  }

  openLink(String url) async {
    try {
      launch(url, forceSafariVC: true);
    } catch (e) {
      // an error occurred, do nothing
    }
  }
}

Add description to Notices banner

Add description to Notices banner


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

/// The colorful library.
library colorful;

class Color {
  int _r;
  int _g;
  int _b;

  Color(this._r, this._g, this._b);
}

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

/// The colorful library.
library colorful;

class Color {
  int _r;
  int _g;
  int _b;

  Color(this._r, this._g, this._b);

  get r => _r;
  get g => _g;
  get b => _b;
}

Add getter methods for r, g, b;

Add getter methods for r, g, b;


library storageservice;

import 'dart:html';
import 'dart:convert';

final String STORAGE_KEY = 'ddays';

List tasklist = [];

// add an item to a given List, then save
// this list in localStorage with the key 'STORAGE_KEY'.
void saveToStorage(item) {
  tasklist.add(item);
  window.localStorage[STORAGE_KEY] = JSON.encode(storedlist);
}

// restore a to localstorage, under key 'STORAGE_KEY',
// saved List.
List loadFromStorage() {
  return JSON.decode(window.localStorage[STORAGE_KEY]);
}

// delete a item from local Storage object with key 'STORAGE_KEY'.
void deleteItemInStorage(item) {
  var storedlist = loadFromStorage().where((i) => i.timestamp == item.timestamp);
  window.localStorage[STORAGE_KEY] = JSON.encode(storedlist);
}

// delete localStorage key.
void deleteStorage() {
  window.localStorage.clear();
}

library storageservice;

import 'dart:html';
import 'dart:convert';

final String STORAGE_KEY = 'ddays';

List tasklist = [];

// add an item to a given List, then save
// this list in localStorage with the key 'STORAGE_KEY'.
void saveToStorage(item) {
  tasklist.add(item);
  window.localStorage[STORAGE_KEY] = JSON.encode(storedlist);
}

// restore a to localstorage, under key 'STORAGE_KEY',
// saved List.
List loadFromStorage() {
  tasklist = JSON.decode(window.localStorage[STORAGE_KEY]);
  return tasklist;
}

// delete a item from local Storage object with key 'STORAGE_KEY'.
void deleteItemInStorage(item) {
  var storedlist = loadFromStorage().where((i) => i.timestamp == item.timestamp);
  window.localStorage[STORAGE_KEY] = JSON.encode(storedlist);
}

// delete localStorage key.
void deleteStorage() {
  window.localStorage.clear();
}

Use tasklist global in loadFromStorage function.


library textmarker;

import 'dart:html';

class TextMarker {
  String targettext;
  int startposition;
  int endposition;
  String textState; // were characters from start to end position typed correctly.

  TextMarker(this.targettext,this.startposition, this.endposition,this.textState);

  SpanElement textSpan(int start,end, String classname) {
    var span = new SpanElement()
      ..classes.add(classname)
      ..text = targettext.substring(start,end);
    return span;
  }
  SpanElement typedCorrectly(int start,end) {
    return textSpan(start,end, 'typedcorrect');
  }
  SpanElement typedIncorrectly(int start,end) {
    return textSpan(start,end, 'typedincorrect');
  }
  SpanElement yetToBeTyped(int start,end) {
    return textSpan(start,end, 'nottyped');
  }
}

library textmarker;

import 'dart:html';

class TextMarker {
  String targettext;
  int startposition;
  int endposition;
  String textState; // were characters from start to end position typed correctly.

  TextMarker(this.targettext,this.startposition, this.endposition,this.textState);

  SpanElement textSpan(String classname) {
    var span = new SpanElement()
      ..classes.add(classname)
      ..text = targettext.substring(startposition,endposition);
    return span;
  }
  SpanElement typedCorrectly() {
    return textSpan('typedcorrect');
  }
  SpanElement typedIncorrectly() {
    return textSpan('typedincorrect');
  }
  SpanElement yetToBeTyped() {
    return textSpan('nottyped');
  }
}

Use initialised start and endpositions.

Use initialised start and endpositions.


library test_dump_render_tree;

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

void main() {
  testRun();
}

void testCore(Configuration config) {
  configure(config);
  groupSep = ' - ';
  testRun();
}

void testRun() {
  final browserTests = ['test/tests_browser.html'];

  group('DumpRenderTree', () {
    browserTests.forEach((file) {
      test(file, () {
        _runDrt(file);
      });
    });
  });
}

void _runDrt(String htmlFile) {
  final allPassedRegExp = new RegExp('All \\d+ tests passed');

  final future = Process.run('DumpRenderTree', [htmlFile])
    .then((ProcessResult pr) {
      expect(pr.exitCode, 0);
      expect(pr.stdout, matches(allPassedRegExp));
    });

  expect(future, completes);
}

library test_dump_render_tree;

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

void main() {
  testRun();
}

void testCore(Configuration config) {
  unittestConfiguration = config;
  groupSep = ' - ';
  testRun();
}

void testRun() {
  final browserTests = ['test/tests_browser.html'];

  group('DumpRenderTree', () {
    browserTests.forEach((file) {
      test(file, () {
        _runDrt(file);
      });
    });
  });
}

void _runDrt(String htmlFile) {
  final allPassedRegExp = new RegExp('All \\d+ tests passed');

  final future = Process.run('DumpRenderTree', [htmlFile])
    .then((ProcessResult pr) {
      expect(pr.exitCode, 0);
      expect(pr.stdout, matches(allPassedRegExp));
    });

  expect(future, completes);
}

Update unit test configuration setting.

Update unit test configuration setting.


// 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/model/ui/display_name.dart';
import 'package:angular_components/model/ui/has_renderer.dart';

/// Add this directive to any [SelectionContainer] or [SelectionItem]
/// component to render [HasUIDisplayName] objects.
@Directive(selector: '[displayNameRenderer]')
void displayNameRendererDirective(HasRenderer hasRenderer) {
  if (hasRenderer != null) hasRenderer.itemRenderer = _displayNameRenderer;
}

final _displayNameRenderer = (HasUIDisplayName item) => item.uiDisplayName;

// 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/model/ui/display_name.dart';
import 'package:angular_components/model/ui/has_renderer.dart';

/// Add this directive to any [SelectionContainer] or [SelectionItem]
/// component to render [HasUIDisplayName] objects.
@Directive(selector: '[displayNameRenderer]')
void displayNameRendererDirective(HasRenderer hasRenderer) {
  if (hasRenderer != null) hasRenderer.itemRenderer = _displayNameRenderer;
}

final _displayNameRenderer =
    (dynamic item) => (item as HasUIDisplayName).uiDisplayName;

Fix uses_bottom_as_dynamic ("fuzzy arrow") errors for material_select.

Using dynamic as bottom will become an error in Dart 2.0. https://github.com/dart-lang/sdk/issues/29630

PiperOrigin-RevId: 182020806


import 'package:sky/widgets.dart';
import 'package:test/test.dart';

import 'build_utils.dart';

void main() {
  test('Can select a day', () {
    WidgetTester tester = new WidgetTester();

    DateTime currentValue;

    Widget builder() {
      return new Block([
        new DatePicker(
          selectedDate: new DateTime.utc(2015, 6, 9, 7, 12),
          firstDate: new DateTime.utc(2013),
          lastDate: new DateTime.utc(2018),
          onChanged: (DateTime dateTime) {
            currentValue = dateTime;
          }
        )
      ]);
    }

    tester.pumpFrame(builder);
    // TODO(abarth): We shouldn't need to pump a second frame here.
    tester.pumpFrame(builder);

    expect(currentValue, isNull);
    tester.tap(tester.findText('30'));
    expect(currentValue, equals(new DateTime(2013, 1, 30)));

  });
}

import 'package:sky/widgets.dart';
import 'package:test/test.dart';

import 'build_utils.dart';

void main() {
  test('Can select a day', () {
    WidgetTester tester = new WidgetTester();

    DateTime currentValue;

    Widget builder() {
      return new Block([
        new DatePicker(
          selectedDate: new DateTime.utc(2015, 6, 9, 7, 12),
          firstDate: new DateTime.utc(2013),
          lastDate: new DateTime.utc(2018),
          onChanged: (DateTime dateTime) {
            currentValue = dateTime;
          }
        )
      ]);
    }

    tester.pumpFrame(builder);
    // TODO(abarth): We shouldn't need to pump a second frame here.
    tester.pumpFrame(builder);

    expect(currentValue, isNull);
    tester.tap(tester.findText('2015'));
    tester.pumpFrame(builder);
    // TODO(jackson): We shouldn't need to pump a second frame here.
    tester.pumpFrame(builder);
    tester.tap(tester.findText('2014'));
    tester.pumpFrame(builder);
    // TODO(jackson): We shouldn't need to pump a second frame here.
    tester.pumpFrame(builder);
    expect(currentValue, equals(new DateTime(2014, 6, 9)));
    tester.tap(tester.findText('30'));
    expect(currentValue, equals(new DateTime(2013, 1, 30)));
  });
}

Test year selection for date picker

Test year selection for date picker


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

import "package:expect/expect.dart";

var cyclicStatic = cyclicStatic + 1;

cyclicInitialization() {
  return cyclicStatic;
}

main() {
  bool hasThrown = false;
  try {
    cyclicStatic + 1;
  } catch(e) {
    hasThrown = true;
    Expect.isTrue(e.stackTrace is StackTrace,
                  "$e doesn't have a non-null stack trace");
  }
  Expect.isTrue(hasThrown);
}

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

import "package:expect/expect.dart";

class A {
  get foo => cyclicStatic;
}

var a = new A();
var cyclicStatic = (() => a.foo + 1)();

cyclicInitialization() {
  return cyclicStatic;
}

main() {
  bool hasThrown = false;
  try {
    cyclicStatic + 1;
  } catch(e2) {
    // Work around bug in analyzer that assigns "Object" type to caught error.
    var e = e2;
    hasThrown = true;
    Expect.isTrue(e.stackTrace is StackTrace,
                  "$e doesn't have a non-null stack trace");
  }
  Expect.isTrue(hasThrown);
}

Make cyclic error init more complicated to avoid static warnings.

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

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


part of discord;

/// A game.
class Game extends _BaseObj {
  /// The game name.
  String name;

  /// The game type. 0 if not streamed, 1 if being streamed.
  int type;

  /// The game URL, if provided.
  String url;

  Game._new(Client client, Map<String, dynamic> data) : super(client) {
    this.name = data['name'];
    this.url = data['url'];
    if (data['type'] is int) {
      this.type = data['type'];
    } else if (data['type'] is String) {
      try {
        this.type = int.parse(data['type']);
      } catch (err) {
        this.type = null;
      }
    }
  }
}

part of discord;

/// A game.
class Game {
  /// The game name.
  String name;

  /// The game type. 0 if not streamed, 1 if being streamed.
  int type;

  /// The game URL, if provided.
  String url;

  /// Makes a new game object.
  Game(this.name, {this.type: 0, this.url});

  Game._new(Client client, Map<String, dynamic> data) {
    try {
      this.name = data['name'].toString();
    } catch (err) {
      this.name = null;
    }

    try {
      this.url = data['url'].toString();
    } catch (err) {
      this.url = null;
    }

    if (data['type'] is int) {
      this.type = data['type'];
    } else if (data['type'] is String) {
      try {
        this.type = int.parse(data['type']);
      } catch (err) {
        this.type = null;
      }
    }
  }

  Map<String, dynamic> _toMap() {
    Map<String, dynamic> map = new Map<String, dynamic>();
    map['name'] = this.name;
    map['type'] = this.type;
    map['url'] = this.url;
    return map;
  }
}

Support for discord's latest feature

Support for discord's latest feature


/// Runtime library used by all generated APIs.
library streamy.runtime;

import 'dart:async';
import 'dart:json';
import 'dart:mirrors';

import 'package:meta/meta.dart';
import 'package:fixnum/fixnum.dart';
import 'package:streamy/collections.dart';

part 'runtime/entity/base.dart';
part 'runtime/entity/empty.dart';
part 'runtime/entity/raw.dart';
part 'runtime/entity/util.dart';
part 'runtime/entity/wrapper.dart';
part 'runtime/cache.dart';
part 'runtime/error.dart';
part 'runtime/metadata.dart';
part 'runtime/multiplexer.dart';
part 'runtime/proxy.dart';
part 'runtime/request.dart';
part 'runtime/transforms.dart';
part 'runtime/util.dart';

/// Runtime library used by all generated APIs.
library streamy.runtime;

import 'dart:async';
import 'dart:json';

import 'package:meta/meta.dart';
import 'package:fixnum/fixnum.dart';
import 'package:streamy/collections.dart';

part 'runtime/entity/base.dart';
part 'runtime/entity/empty.dart';
part 'runtime/entity/raw.dart';
part 'runtime/entity/util.dart';
part 'runtime/entity/wrapper.dart';
part 'runtime/cache.dart';
part 'runtime/error.dart';
part 'runtime/metadata.dart';
part 'runtime/multiplexer.dart';
part 'runtime/proxy.dart';
part 'runtime/request.dart';
part 'runtime/transforms.dart';
part 'runtime/util.dart';

Remove dependency on dart:mirrors from Streamy runtime.


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

// This code was auto-generated, is not intended to be edited, and is subject to
// significant change. Please see the README file for more information.

library engine.utilities.general;

/**
 * Helper for measuring how much time is spent doing some operation.
 */
class TimeCounter {
  Stopwatch _sw = new Stopwatch();

  /**
   * @return the number of milliseconds spent between [start] and [stop].
   */
  int get result => _sw.elapsedMilliseconds;

  /**
   * Starts counting time.
   *
   * @return the [TimeCounterHandle] that should be used to stop counting.
   */
  TimeCounter_TimeCounterHandle start() => new TimeCounter_TimeCounterHandle(this);
}

/**
 * The handle object that should be used to stop and update counter.
 */
class TimeCounter_TimeCounterHandle {
  final TimeCounter _counter;

  TimeCounter_TimeCounterHandle(this._counter) {
    _counter._sw.start();
  }

  /**
   * Stops counting time and updates counter.
   */
  void stop() {
    _counter._sw.stop();
  }
}

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

// This code was auto-generated, is not intended to be edited, and is subject to
// significant change. Please see the README file for more information.

library engine.utilities.general;

/**
 * Helper for measuring how much time is spent doing some operation.
 */
class TimeCounter {
  static TimeCounter _current = null;
  final Stopwatch _sw = new Stopwatch();

  /**
   * @return the number of milliseconds spent between [start] and [stop].
   */
  int get result => _sw.elapsedMilliseconds;

  /**
   * Starts counting time.
   *
   * @return the [TimeCounterHandle] that should be used to stop counting.
   */
  TimeCounter_TimeCounterHandle start() {
    return new TimeCounter_TimeCounterHandle(this);
  }
}

/**
 * The handle object that should be used to stop and update counter.
 */
class TimeCounter_TimeCounterHandle {
  final TimeCounter _counter;
  TimeCounter _prev;

  TimeCounter_TimeCounterHandle(this._counter) {
    // if there is some counter running, pause it
    _prev = TimeCounter._current;
    if (_prev != null) {
      _prev._sw.stop();
    }
    TimeCounter._current = _counter;
    // start this counter
    _counter._sw.start();
  }

  /**
   * Stops counting time and updates counter.
   */
  void stop() {
    _counter._sw.stop();
    // restore previous counter and resume it
    TimeCounter._current = _prev;
    if (_prev != null) {
      _prev._sw.start();
    }
  }
}

Correct or pause previous TimeCounters.

Correct or pause previous TimeCounters.

R=brianwilkerson@google.com, jwren@google.com
BUG=

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

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


import 'others.dart';
import 'package:expect/expect.dart';

const Map<Key, String> m = {someKey: "PASSED"};

main() {
  Expect.equals(m[someKey], "PASSED");
}

import 'others.dart';
import 'package:expect/expect.dart';

const Map<Key, String> m = {someKey: "PASSED"};

main() {
  Expect.equals("PASSED", m[someKey]);
}

Fix expected and actual ordering

[test] Fix expected and actual ordering

Not a big deal but I was confused for longer than I would like to
admit because the failure message labels the "expected" and "actual"
values as such.

Change-Id: I433d263b873286a54725b7a2a0ba536dd29aae47
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/262664
Reviewed-by: Mayank Patke <e0355b78204b67a55a952941c68c8f1b40235938@google.com>
Commit-Queue: Nicholas Shahan <03847abd2d8aadfe859ecb98095a31f9f515dc47@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:cli_util/cli_util.dart';
import 'package:unittest/unittest.dart';

void defineTests() {
  group('getSdkDir', () {
    test('arg parsing', () {
      expect(getSdkDir(['--dart-sdk', '/dart/sdk']).path, equals('/dart/sdk'));
      expect(getSdkDir(['--dart-sdk=/dart/sdk']).path, equals('/dart/sdk'));
    });
  });
}

main() {
  groupSep = ' | ';

  defineTests();
}

// 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:cli_util/cli_util.dart';
import 'package:unittest/unittest.dart';

void defineTests() {
  group('getSdkDir', () {
    test('arg parsing', () {
      expect(getSdkDir(['--dart-sdk', '/dart/sdk']).path, equals('/dart/sdk'));
      expect(getSdkDir(['--dart-sdk=/dart/sdk']).path, equals('/dart/sdk'));
    });
    test('finds the SDK without cli args', () {
      expect(getSdkDir(), isNotNull);
    });
  });
}

main() {
  groupSep = ' | ';

  defineTests();
}

Test that getSdkDir() finds the SDK without CLI args.


import 'package:test/test.dart';
import 'package:moor/moor.dart';

import '../data/tables/todos.dart';
import '../data/utils/expect_generated.dart';

void main() {
  final db = TodoDb();

  const innerExpression =
      CustomExpression<String>('name', precedence: Precedence.primary);
  group('values', () {
    test('in expressions are generated', () {
      final isInExpression = innerExpression.isIn(['Max', 'Tobias']);

      expect(isInExpression, generates('name IN (?, ?)', ['Max', 'Tobias']));
    });

    test('not in expressions are generated', () {
      final isNotIn = innerExpression.isNotIn(['Max', 'Tobias']);

      expect(isNotIn, generates('name NOT IN (?, ?)', ['Max', 'Tobias']));
    });
  });

  group('subquery', () {
    test('in expressions are generated', () {
      final isInExpression = innerExpression
          .isInQuery(db.selectOnly(db.users)..addColumns([db.users.name]));

      expect(isInExpression,
          generates('name IN (SELECT users.name AS "users.name" FROM users)'));
    });

    test('not in expressions are generated', () {
      final isInExpression = innerExpression
          .isNotInQuery(db.selectOnly(db.users)..addColumns([db.users.name]));

      expect(
          isInExpression,
          generates(
              'name NOT IN (SELECT users.name AS "users.name" FROM users)'));
    });
  });
}

import 'package:test/test.dart';
import 'package:moor/moor.dart';

import '../data/tables/todos.dart';
import '../data/utils/expect_generated.dart';

void main() {
  final db = TodoDb();

  const innerExpression =
      CustomExpression<String>('name', precedence: Precedence.primary);
  group('values', () {
    test('in expressions are generated', () {
      final isInExpression = innerExpression.isIn(['Max', 'Tobias']);

      expect(isInExpression, generates('name IN (?, ?)', ['Max', 'Tobias']));
    });

    test('not in expressions are generated', () {
      final isNotIn = innerExpression.isNotIn(['Max', 'Tobias']);

      expect(isNotIn, generates('name NOT IN (?, ?)', ['Max', 'Tobias']));
    });
  });

  group('subquery', () {
    test('in expressions are generated', () {
      final isInExpression = innerExpression
          .isInQuery(db.selectOnly(db.users)..addColumns([db.users.name]));

      expect(isInExpression,
          generates('name IN (SELECT users.name AS "users.name" FROM users)'));

      final ctx = GenerationContext(SqlTypeSystem.defaultInstance, null);
      isInExpression.writeInto(ctx);
      expect(ctx.watchedTables, contains(db.users));
    });

    test('not in expressions are generated', () {
      final isInExpression = innerExpression
          .isNotInQuery(db.selectOnly(db.users)..addColumns([db.users.name]));

      expect(
          isInExpression,
          generates(
              'name NOT IN (SELECT users.name AS "users.name" FROM users)'));
    });
  });
}

Test that isInQuery writes inner tables

Test that isInQuery writes inner tables


import 'package:flutter/material.dart';

void main() {
  runApp(new FriendlychatApp());
}

class FriendlychatApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: "FriendlyChat",
      home: new ChatScreen(),
    );
  }
}

class ChatScreen extends StatefulWidget {
  @override
  State createState() => new ChatScreenState();
}

class ChatScreenState extends State<ChatScreen> {
  final TextEditingController _textController = new TextEditingController();

  Widget _buildTextComposer() {
    return new Container(
      margin: const EdgeInsets.symmetric(horizontal: 8.0),
      child: new TextField(
        controller: _textController,
        onSubmitted: _handleSubmitted,
        decoration: new InputDecoration.collapsed(
            hintText: "Send a message"),
      ),
    );
  }

  void _handleSubmitted(String text) {
    _textController.clear();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
          title: new Text("FriendlyChat")
      ),
      body: _buildTextComposer(),
    );
  }
}

import 'package:flutter/material.dart';

void main() {
  runApp(new FriendlychatApp());
}

class FriendlychatApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: "FriendlyChat",
      home: new ChatScreen(),
    );
  }
}

class ChatScreen extends StatefulWidget {
  @override
  State createState() => new ChatScreenState();
}

class ChatScreenState extends State<ChatScreen> {
  final TextEditingController _textController = new TextEditingController();

  Widget _buildTextComposer() {
    return new Container(
      margin: const EdgeInsets.symmetric(horizontal: 8.0),
      child: new Row(                                              //new
        children: <Widget>[                                      //new
          new Flexible(
            child: new TextField(
              controller: _textController,
              onSubmitted: _handleSubmitted,
              decoration: new InputDecoration.collapsed(hintText: "Send a message"),
            ),
          )
        ]
      )
    );
  }

  void _handleSubmitted(String text) {
    _textController.clear();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
          title: new Text("FriendlyChat")
      ),
      body: _buildTextComposer(),
    );
  }
}

Prepare for adding the button to the right to enable sending the message


import 'dart:io';
import 'dart:convert' show JSON;

main() {
    var port = 3000;

    HttpServer.bind('localhost', port).then((HttpServer server) {
        print('Server started on port: ${port}');
        server.listen((HttpRequest request) {
                String str = request.uri.queryParameters['str'] ?? '';
                String ch = request.uri.queryParameters['ch'] ?? ' ';
                String len = request.uri.queryParameters['len'] ?? '0';

                Object output = {'str': str.padLeft(int.parse(len), ch)};

                request.response..headers.set(HttpHeaders.CONTENT_TYPE, 'application/json');
                request.response..headers.set('Access-Control-Allow-Origin','*');
                request.response..write(JSON.encode(output))..close();
            });
        });
}

import 'dart:io';
import 'dart:convert' show JSON;

main() {
    int port = 3000;

    HttpServer.bind('localhost', port).then((HttpServer server) {
        print('Server started on port: $port');
        server.listen((HttpRequest request) {
                String str = request.uri.queryParameters['str'] ?? '';
                String ch = request.uri.queryParameters['ch'] ?? ' ';
                String len = request.uri.queryParameters['len'] ?? '0';

                Map output = {'str': str.padLeft(int.parse(len), ch)};

                request.response..headers.set(HttpHeaders.CONTENT_TYPE, 'application/json');
                request.response..headers.set('Access-Control-Allow-Origin','*');
                request.response..write(JSON.encode(output))..close();
            });
        });
}

Fix some types, better way of interpolating values


class StringMapperHelper {
  static String mapStatIdToTitle(String statId) {
    switch (statId) {
      case ('top_tv'):
        return 'Most Watched TV Shows';
      case ('popular_tv'):
        return 'Most Popular TV Shows';
      case ('top_movies'):
        return 'Most Watched Movies';
      case ('popular_movies'):
        return 'Most Popular Movies';
      case ('top_music'):
        return 'Most Played Artists';
      case ('popular_music'):
        return 'Most Popular Artists';
      case ('last_watched'):
        return 'Recently Watched';
      case ('top_platforms'):
        return 'Most Active Platforms';
      case ('top_users'):
        return 'Most Active Users';
      case ('most_concurrent'):
        return 'Most Concurrent Streams';
      case ('top_libraries'):
        return 'Most Active Libraries';
      default:
        return 'UNKNOWN';
    }
  }
}

import '../../features/graphs/domain/entities/series_data.dart';

class StringMapperHelper {
  static String mapStatIdToTitle(String statId) {
    switch (statId) {
      case ('top_tv'):
        return 'Most Watched TV Shows';
      case ('popular_tv'):
        return 'Most Popular TV Shows';
      case ('top_movies'):
        return 'Most Watched Movies';
      case ('popular_movies'):
        return 'Most Popular Movies';
      case ('top_music'):
        return 'Most Played Artists';
      case ('popular_music'):
        return 'Most Popular Artists';
      case ('last_watched'):
        return 'Recently Watched';
      case ('top_platforms'):
        return 'Most Active Platforms';
      case ('top_users'):
        return 'Most Active Users';
      case ('most_concurrent'):
        return 'Most Concurrent Streams';
      case ('top_libraries'):
        return 'Most Active Libraries';
      default:
        return 'UNKNOWN';
    }
  }

  static String mapSeriesTypeToTitle(SeriesType seriesType) {
    switch (seriesType) {
      case (SeriesType.tv):
        return 'TV';
      case (SeriesType.movies):
        return 'Movies';
      case (SeriesType.music):
        return 'Music';
      case (SeriesType.live):
        return 'Live TV';
      default:
        return 'UNKNOWN';
    }
  }
}

Add title mapper for graph series type.

Add title mapper for graph series type.


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

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

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

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

Sort packages by name before listing them.

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

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


part of devtools.util;

class StringTrimmer implements StreamTransformer<String, String> {
  @override
  Stream<String> bind(Stream<String> stream) =>
      stream.map((value) => value.trim());
}

class StringSplitter implements StreamTransformer<String, List<String>> {
  final Pattern by;

  StringSplitter({this.by: " "});

  @override
  Stream<List<String>> bind(Stream<String> stream) =>
      stream.map((it) => it.split(by));
}

class StringJoiner implements StreamTransformer<List<String>, String> {
  final String by;

  StringJoiner({this.by: " "});

  @override
  Stream<String> bind(Stream<List<String>> stream) =>
      stream.map((it) => it.join(by));
}

class SkipEmptyStrings implements StreamTransformer<String, String> {
  @override
  Stream<String> bind(Stream<String> stream) =>
      stream.where((it) => it.isNotEmpty);
}

class SkipNulls<T> implements StreamTransformer<T, T> {
  @override
  Stream<T> bind(Stream<T> stream) => stream.where((it) => it != null);
}

class Matching implements StreamTransformer<String, String> {
  final RegExp expression;

  Matching(this.expression);

  @override
  Stream<String> bind(Stream<String> stream) =>
      stream.where((it) => expression.hasMatch(it));
}

part of devtools.util;

class StringTrimmer implements StreamTransformer<String, String> {
  @override
  Stream<String> bind(Stream<String> stream) =>
      stream.map((value) => value.trim());
}

class StringSplitter implements StreamTransformer<String, List<String>> {
  final Pattern by;

  StringSplitter({this.by: " "});

  @override
  Stream<List<String>> bind(Stream<String> stream) =>
      stream.map((it) => it.split(by));
}

class StringJoiner implements StreamTransformer<List<String>, String> {
  final String by;

  StringJoiner({this.by: " "});

  @override
  Stream<String> bind(Stream<List<String>> stream) =>
      stream.map((it) => it.join(by));
}

class SkipEmptyStrings implements StreamTransformer<String, String> {
  @override
  Stream<String> bind(Stream<String> stream) =>
      stream.where((it) => it.isNotEmpty);
}

class SkipNulls<T> implements StreamTransformer<T, T> {
  @override
  Stream<T> bind(Stream<T> stream) => stream.where((it) => it != null);
}

class StringsMatching implements StreamTransformer<String, String> {
  final RegExp expression;

  StringsMatching(this.expression);

  @override
  Stream<String> bind(Stream<String> stream) =>
      stream.where((it) => expression.hasMatch(it));
}

Rename 'Matching' transformer to 'StringsMatching'


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

import 'package:expect/expect.dart';
import 'package:async_helper/async_helper.dart';
import 'dart:async';

testEmptyZoneSpecification() {
  Expect.identical(Zone.ROOT, Zone.current);
  Zone forked = Zone.current.fork();
  Expect.isFalse(identical(Zone.ROOT, forked));

  asyncStart();
  bool timerDidRun = false;
  forked.createTimer(const Duration(milliseconds: 20), () {
    // The createTimer functions on the Zone binds the closures.
    Expect.identical(forked, Zone.current);
    timerDidRun = true;
    asyncEnd();
  });
  Expect.identical(Zone.ROOT, Zone.current);

  asyncStart();
  int periodicTimerCount = 0;
  forked.createPeriodicTimer(const Duration(milliseconds: 20), (Timer timer) {
    periodicTimerCount++;
    if (periodicTimerCount == 4) {
      timer.cancel();
      asyncEnd();
    }
    // The createPeriodicTimer functions on the Zone binds the closures.
    Expect.identical(forked, Zone.current);
  });
  Expect.identical(Zone.ROOT, Zone.current);
}

main() {
  testEmptyZoneSpecification();
}

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

import 'package:expect/expect.dart';
import 'package:async_helper/async_helper.dart';
import 'dart:async';

testEmptyZoneSpecification() {
  Expect.identical(Zone.ROOT, Zone.current);
  Zone forked = Zone.current.fork();
  Expect.isFalse(identical(Zone.ROOT, forked));

  asyncStart();
  bool timerDidRun = false;
  forked.createTimer(const Duration(milliseconds: 20), () {
    // The createTimer function on the Zone binds the closures.
    Expect.identical(forked, Zone.current);
    timerDidRun = true;
    asyncEnd();
  });
  Expect.identical(Zone.ROOT, Zone.current);

  asyncStart();
  int periodicTimerCount = 0;
  forked.createPeriodicTimer(const Duration(milliseconds: 20), (Timer timer) {
    periodicTimerCount++;
    if (periodicTimerCount == 4) {
      timer.cancel();
      asyncEnd();
    }
    // The createPeriodicTimer function on the Zone binds the closures.
    Expect.identical(forked, Zone.current);
  });
  Expect.identical(Zone.ROOT, Zone.current);
}

main() {
  testEmptyZoneSpecification();
}

Make the root zone's schduleMicrotask and create[Periodic]Timer bind the callback.

BUG= http://dartbug.com/15232
R=floitsch@google.com

Committed: https://code.google.com/p/dart/source/detail?r=30708

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

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