part of github.server;

class HookMiddleware {
  final StreamController<HookEvent> _eventController = new StreamController<HookEvent>();
  Stream<HookEvent> get onEvent => _eventController.stream;

  void handleHookRequest(HttpRequest request) {

    if (request.method != "POST") {
      request.response.write("Only POST is Supported");
      request.response.close();
      return;
    }

    if (request.headers['x-github-event'] == null) {
      request.response.write("X-GitHub-Event must be specified.");
      request.response.close();
      return;
    }

    request.transform(new Utf8Decoder()).join().then((content) {
      _eventController.add(new HookEvent(request.headers['x-github-event'].first, JSON.decode(content)));
      request.response.write(JSON.encode({
        "handled": true
      }));
      request.response.close();
    });
  }
}

class HookServer extends HookMiddleware {
  final String host;
  final int port;

  HttpServer _server;

  HookServer(this.port, [this.host = "0.0.0.0"]);

  void start() {
    HttpServer.bind(host, port).then((HttpServer server) {
      _server = server;
      server.listen(handleHookRequest);
    });
  }

  Future stop() => _server.close();
}

class HookEvent {
  final String event;
  final Map<String, Object> data;

  HookEvent(this.event, this.data);
}

Change HookServer to only hook on with /hook

part of github.server;

class HookMiddleware {
  final StreamController<HookEvent> _eventController = new StreamController<HookEvent>();
  Stream<HookEvent> get onEvent => _eventController.stream;

  void handleHookRequest(HttpRequest request) {

    if (request.method != "POST") {
      request.response.write("Only POST is Supported");
      request.response.close();
      return;
    }

    if (request.headers['x-github-event'] == null) {
      request.response.write("X-GitHub-Event must be specified.");
      request.response.close();
      return;
    }

    request.transform(new Utf8Decoder()).join().then((content) {
      _eventController.add(new HookEvent(request.headers['x-github-event'].first, JSON.decode(content)));
      request.response.write(JSON.encode({
        "handled": true
      }));
      request.response.close();
    });
  }
}

class HookServer extends HookMiddleware {
  final String host;
  final int port;

  HttpServer _server;

  HookServer(this.port, [this.host = "0.0.0.0"]);

  void start() {
    HttpServer.bind(host, port).then((HttpServer server) {
      _server = server;
      server.listen((request) {
        if (request.uri.path == "/hook") {
          handleHookRequest(request);
        } else {
          request.response.statusCode = 404;
          request.response.write("404 - Not Found");
          request.response.close();
        }
      });
    });
  }

  Future stop() => _server.close();
}

class HookEvent {
  final String event;
  final Map<String, Object> data;

  HookEvent(this.event, this.data);
}


Add regression test for buildbot flakiness due to smi-widening optimization in VM

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

// VMOptions=--deterministic --optimization-counter-threshold=102 --enable-inlining-annotations --optimization-filter=Box_

import 'package:expect/expect.dart';

const String NeverInline = 'NeverInline';
const String AlwaysInline = 'AlwaysInline';
const int kLimit = 100;

main() {
  // Get all 3 functions optimized with _Smi's.
  optimizeMilliseconds(1);
  optimizeMicroseconds(1);
  optimizeConstructor(1);

  // Now we trigger a store of a _Mint into the Box._value
  testMints(2048);
}

@NeverInline
optimizeConstructor(int value) {
  for (int i = 0; i < kLimit; ++i) {
    new Box(milliseconds: value);
  }
}

@NeverInline
optimizeMicroseconds(int value) {
  final d = new Box(milliseconds: value);
  for (int i = 0; i < kLimit; ++i) {
    Expect.equals(value * 1000, d.inMicroseconds);
  }
}

@NeverInline
optimizeMilliseconds(int value) {
  final d = new Box(seconds: value);
  for (int i = 0; i < kLimit; ++i) {
    Expect.equals(value * 1000, d.inMilliseconds);
  }
}

@NeverInline
testMints(int value) {
  final d = new Box(seconds: value);
  for (int i = 0; i < kLimit; ++i) {
    Expect.equals(value * 1000 * 1000, d.inMicroseconds);
    Expect.equals(value * 1000, d.inMilliseconds);
  }
}

int c = 0;

class Box {
  final int _value;

  @NeverInline
  Box(
      {int days: 0,
      int hours: 0,
      int minutes: 0,
      int seconds: 0,
      int milliseconds: 0,
      int microseconds: 0})
      : this._microseconds(1000 * 1000 * 60 * 60 * 24 * days +
            1000 * 1000 * 60 * 60 * hours +
            1000 * 1000 * 60 * minutes +
            1000 * 1000 * seconds +
            1000 * milliseconds +
            microseconds);

  Box._microseconds(this._value);

  @NeverInline
  int get inMilliseconds => _value ~/ 1000;

  @NeverInline
  int get inMicroseconds => _value;
}


Create Client class which extends oauth.Client

library twitter.client;

import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:oauth/oauth.dart' as oauth;

class Client extends oauth.Client {

	Client(oauth.Tokens tokens)
		: super(tokens);

	@override
	Future<http.Response> get(url, {Map<String,String> headers, body, Encoding encoding}){
		if (url is String) url = Uri.parse(url);
		var request = new http.Request("GET",url);

		if (headers != null) request.headers.addAll(headers);
		if (encoding != null) request.encoding = encoding;
		if (body != null){
			if (body is String){
				request.body = body;
			} else if (body is List){
				request.bodyBytes = body;
			} else if (body is Map){
				request.bodyFields = body;
			} else {
				throw new ArgumentError('Invalid request body "$body".');
			}
		}
		return super.send(request).then(http.Response.fromStream);
	}
}


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

// This tool cleans task objects from the project's datastore

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

import 'package:sintr_live_common/configuration.dart' as config;
import 'package:sintr_live_common/logging_utils.dart' as log;
import 'package:sintr_live_common/auth.dart' as auth;
import 'package:sintr_live_common/tasks.dart' as tasks;
import 'package:gcloud/src/datastore_impl.dart' as datastore_impl;
import 'package:gcloud/db.dart' as db;
import 'package:gcloud/service_scope.dart' as ss;

main(List<String> args) async {
  if (args.length < 1) {
    print("Usage: dart gc_tasks cloud_project_id");
    exit(1);
  }

  log.setupLogging();

  String projectId = args[0];

  config.configuration = new config.Configuration(projectId,
      cryptoTokensLocation:
          "${config.userHomePath}/Communications/CryptoTokens");

  var client = await auth.getAuthedClient();

  tasks.TaskController taskController =
      new tasks.TaskController("example_task");

  var datastore = new datastore_impl.DatastoreImpl(client, 's~$projectId');
  var datastoreDB = new db.DatastoreDB(datastore);

  log.info("Setup done");

  await ss.fork(() async {
    db.registerDbService(datastoreDB);

    await taskController.deleteAllTasks();
  });
  log.info("Tasks deleted");
}


library annotation_src_spec;

import 'package:angular/core/annotation_src.dart';
import 'dart:mirrors';
import '../_specs.dart';

var _SYMBOL_NAME = new RegExp('"([^@]*).*"');
_getName(VariableMirror v) => _SYMBOL_NAME.firstMatch(v.simpleName.toString()).group(1);

Map<String, dynamic> variables(x) {
  Map variables = {};
  InstanceMirror mirror = reflect(x) as InstanceMirror;
  ClassMirror type = mirror.type;
  do {
    type.declarations.forEach((k,v) {
      if (v is VariableMirror && !v.isStatic) {
        variables[_getName(v)] = mirror.getField(v.simpleName).reflectee;
      }
    });
  } while ((type = type.superclass) != null);

  return variables;
}

List<String> nullFields(x) {
  var ret = [];
  variables(x).forEach((k, v) {
    if (v == null) ret.add(k);
  });
  return ret;
}

void main() => describe('annotations', () {
  describe('component', () {
    it('should set all fields on clone when all the fields are set', () {
      var component = new Component(
        template: '',
        templateUrl: '',
        cssUrl: [''],
        applyAuthorStyles: true,
        resetStyleInheritance: true,
        publishAs: '',
        module: (){},
        map: {},
        selector: '',
        visibility: Directive.LOCAL_VISIBILITY,
        exportExpressions: [],
        exportExpressionAttrs: []
      );

      // Check that no fields are null
      expect(nullFields(component)).toEqual([]);

      // Check that the clone is the same as the original.
      expect(variables(cloneWithNewMap(component, {}))).toEqual(variables(component));
    });
  });

  describe('decorator', () {
    it('should set all fields on clone when all the fields are set', () {
      var decorator = new Decorator(
          children: 'xxx',
          map: {},
          selector: '',
          module: (){},
          visibility: Directive.LOCAL_VISIBILITY,
          exportExpressions: [],
          exportExpressionAttrs: []
      );

      // Check that no fields are null
      expect(nullFields(decorator)).toEqual([]);

      // Check that the clone is the same as the original.
      expect(variables(cloneWithNewMap(decorator, {}))).toEqual(variables(decorator));
    });
  });

  describe('controller', () {
    it('should set all fields on clone when all the fields are set', () {
      var controller = new Controller(
          publishAs: '',
          children: 'xxx',
          map: {},
          selector: '',
          module: (){},
          visibility: Directive.LOCAL_VISIBILITY,
          exportExpressions: [],
          exportExpressionAttrs: []
      );

      // Check that no fields are null
      expect(nullFields(controller)).toEqual([]);

      // Check that the clone is the same as the original.
      expect(variables(cloneWithNewMap(controller, {}))).toEqual(variables(controller));
    });
  });
});


Test with difficult to parse formal parameters.

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

// Tests for parsing closures with complex parameter types.

main() {
  test1();
  test2();
  test3();
}

class Pair<A, B> {
  final A fst;
  final B snd;
  Pair(A this.fst, B this.snd);
}

test1() {
  // Closures with nested parameterized types.
  var cdar1 = (Pair<int, Pair<int, int>> pr) => pr.snd.fst;
  var cdar2 = (Pair<int, Pair<int, int> > pr) => pr.snd.fst;

  var e = new Pair<int, Pair<int, int>>(100, new Pair<int, int>(200, 300));

  Expect.equals(200, cdar1(e));
  Expect.equals(200, cdar2(e));
}

test2() {
  // Closures with nested parameterized types in optional position
  var cdar1 = ([Pair<int, Pair<int, int>> pr = null]) => pr.snd.fst;
  var cdar2 = ([Pair<int, Pair<int, int> > pr = null]) => pr.snd.fst;

  var e = new Pair<int, Pair<int, int>>(100, new Pair<int, int>(200, 300));

  Expect.equals(200, cdar1(e));
  Expect.equals(200, cdar2(e));
}

test3() {
  // Closures with nested parameterized types.
  var f1 = (Pair<int, Pair<int, int>> pr) => pr.snd.fst + 1;
  var f2 = (Pair<int, Pair<int, int> > pr) => pr.snd.fst + 2;

  // Closures with function type with nested parameterized types.
  var ap1 = (f(Pair<int, Pair<int, int>> pr), Pair<int, Pair<int, int>> pr)
                 => f(pr) * 10;
  var ap2 = (f(Pair<int, Pair<int, int> > pr), Pair<int, Pair<int, int> > pr)
                 => f(pr) * 100;

  var e = new Pair<int, Pair<int, int>>(100, new Pair<int, int>(200, 300));

  Expect.equals(2010, ap1(f1, e));
  Expect.equals(2020, ap1(f2, e));
  Expect.equals(20100, ap2(f1, e));
  Expect.equals(20200, ap2(f2, e));
}


Add DeviceInfo class to get model, platform, etc.

import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';

abstract class DeviceInfo {
  /// The end-user-visible name for the device.
  Future<String?> get model;

  /// Returns `'ios'` if platform is iOS, otherwise returns `'android'`
  Future<String> get platform;

  /// A unique identifier for the device.
  Future<String?> get uniqueId;
}

class DeviceInfoImpl implements DeviceInfo {
  final DeviceInfoPlugin deviceInfoPlugin;

  DeviceInfoImpl(this.deviceInfoPlugin);

  @override
  Future<String?> get model async {
    if (Platform.isAndroid) {
      final androidInfo = await deviceInfoPlugin.androidInfo;
      return androidInfo.model;
    } else {
      final iosInfo = await deviceInfoPlugin.iosInfo;
      return iosInfo.name;
    }
  }

  @override
  Future<String?> get uniqueId async {
    if (Platform.isAndroid) {
      final androidInfo = await deviceInfoPlugin.androidInfo;
      return androidInfo.androidId;
    } else {
      final iosInfo = await deviceInfoPlugin.iosInfo;
      return iosInfo.identifierForVendor;
    }
  }

  @override
  Future<String> get platform async {
    final isIos = Platform.isIOS;
    if (isIos) {
      return 'ios';
    }
    return 'android';
  }
}


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

// This tool takes a time_to_fix file and emits summary information in a format
// that is easier to render

import 'dart:io';
import 'dart:convert';

main(List<String> args) async {
  String inputPath;
  if (args.length != 1) {
    print("usage: to_denorm_format.dart path");
    exit(1);
  }

  inputPath = args[0];

  // E.g. Resolved: {"severity":"ERROR","type":"SYNTACTIC_ERROR","message":"Expected an identifier","code":"missing_identifier","hasFix":false}, 1473891312265, 1473891313360, 1095

  await new File(inputPath).openRead().transform(UTF8.decoder).transform(new LineSplitter()).forEach((ln) {
    if (!ln.startsWith("Resolved:")) return;
    ln = ln.substring("Resolved:".length);

    int endOfJson = ln.lastIndexOf("}") + 1;
    int timeToFix = int.parse(ln.split(",").last);

    Map data = JSON.decode(ln.substring(0, endOfJson));

    print ("${data['code']}, ${data['hasFix']}, $timeToFix");

  });
}


import 'dart:sky';

import 'package:test/test.dart';

void main() {
  test("rect accessors", () {
    Rect r = new Rect.fromLTRB(1.0, 3.0, 5.0, 7.0);
    expect(r.left, equals(1.0));
    expect(r.top, equals(3.0));
    expect(r.right, equals(5.0));
    expect(r.bottom, equals(7.0));
  });

  test("rect created by width and height", () {
    Rect r = new Rect.fromLTWH(1.0, 3.0, 5.0, 7.0);
    expect(r.left, equals(1.0));
    expect(r.top, equals(3.0));
    expect(r.right, equals(6.0));
    expect(r.bottom, equals(10.0));
  });

  test("rect intersection", () {
    Rect r1 = new Rect.fromLTRB(0.0, 0.0, 100.0, 100.0);
    Rect r2 = new Rect.fromLTRB(50.0, 50.0, 200.0, 200.0);
    Rect r3 = r1.intersect(r2);
    expect(r3.left, equals(50.0));
    expect(r3.top, equals(50.0));
    expect(r3.right, equals(100.0));
    expect(r3.bottom, equals(100.0));
    Rect r4 = r2.intersect(r1);
    expect(r4, equals(r3));
  });
}


Add test for inadequate side-effects computation

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

// None of these methods have any side effects, but using [Selector] count to
// order side-effects computation will make [_callNoSideEffectsManyTimes] be
// computed last and thus make [callCallNoSideEffectsManyTimes] and with it
// [main] assume all side-effects from the call to
// [_callNoSideEffectsManyTimes].
//
// The methods are deliberately put in order of increasing [Selector] count to
// make the [InferrerEngineImpl.useSorterForTesting] flag mimmick the order in
// the old inference.

/*element: _noSideEffects:Depends on nothing, Changes nothing.*/
_noSideEffects() {}

/*element: callCallNoSideEffectsManyTimes:Depends on [] field store static store, Changes [] field static.*/
callCallNoSideEffectsManyTimes() {
  _callNoSideEffectsManyTimes();
}

/*element: main:Depends on [] field store static store, Changes [] field static.*/
main() {
  callCallNoSideEffectsManyTimes();
  callCallNoSideEffectsManyTimes();
}

/*element: _callNoSideEffectsManyTimes:Depends on nothing, Changes nothing.*/
_callNoSideEffectsManyTimes() {
  _noSideEffects();
  _noSideEffects();
  _noSideEffects();
  _noSideEffects();
  _noSideEffects();
  _noSideEffects();
  _noSideEffects();
  _noSideEffects();
  _noSideEffects();
  _noSideEffects();
  _noSideEffects();
  _noSideEffects();
  _noSideEffects();
  _noSideEffects();
  _noSideEffects();
  _noSideEffects();
}


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

import '1358_rebind_injector_test.template.dart' as ng;

void main() {
  ng.initReflector();

  ReflectiveInjector parentInjector;

  setUp(() {
    parentInjector = ReflectiveInjector.resolveAndCreate([
      new ClassProvider(Model),
      new ValueProvider(Place, new Place('Parent')),
    ]);
  });

  test('should have the expected bindings at the parent level', () {
    expect((parentInjector.get(Model) as Model).place.name, 'Parent');
  });

  test('should have the expected bindings at the child level', () {
    final childInjector = parentInjector.resolveAndCreateChild([
      new ValueProvider(Place, new Place('Child')),
    ]);
    expect(
      (childInjector.resolveAndInstantiate(Model) as Model).place.name,
      'Child',
    );
  });
}

class Place {
  final String name;

  Place(this.name);

  @override
  String toString() => '$Place {name=$name}';
}

@Injectable()
class Model {
  final Place place;

  Model(this.place);

  @override
  String toString() => '$Model {place=$place}';
}


Add a test for nested await argument subexpressions.

f(s) {
  return new Future(() => print(s));
}

g(x, y, z) {}

test1() async {
  g(print('a'),
      print('b'),
      g(print('1'), await f('2'), print('3')));
}

test2() async {
  g(print('a'),
      g(print('1'), await f('2'), print('3')),
      print('b'));
}

test3() async {
  g(print('a'),
      g(print('1'), await f('2'), print('3')),
      g(print('4'), await f('5'), print('6')));
}

test4() async {
  g(g(print('1'), await f('2'), print('3')),
      print('a'),
      print('b'));
}


// 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.
//
// Directory listing test.

class DirectoryTest {
  static void testListing() {
    bool listedSomething = false;
    Directory directory = new Directory.open(".");

    directory.setDirHandler((dir) {
      listedSomething = true;
    });

    directory.setFileHandler((f) {
      listedSomething = true;
    });

    directory.setDoneHandler((completed) {
      Expect.isTrue(completed, "directory listing did not complete");
      Expect.isTrue(listedSomething, "empty directory");
      directory.close();
    });

    directory.setDirErrorHandler((dir) {
      Expect.fail("error listing directory");
    });

    directory.list();
  }

  static void testMain() {
    testListing();
  }
}

main() {
  DirectoryTest.testMain();
}


Add simple HTTP server implementation in support of Chap. 6 exercises

import 'dart:io';
import 'package:http_server/http_server.dart' show VirtualDirectory;

final String PATH_TO_WEB_CONTENT = "web";

void main() {
  HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 3031).then((HttpServer server) {
    print("Serving at ${server.address}:${server.port}");
    final root = Platform.script.resolve(PATH_TO_WEB_CONTENT).toFilePath();
    final virDir = new VirtualDirectory(root)
        // The following are needed in dev mode to be able to access
        // Dart packages in the cache.
        ..followLinks = true
        ..jailRoot = false;
    server.listen((HttpRequest req) {
      print("${req.method} ${req.uri};\tcached ${req.headers.ifModifiedSince}");
      (req.method == "PUT" ? processPut : virDir.serveRequest)(req);
    });
  });
}

void processPut(HttpRequest request) {
  String filePath = request.uri.toFilePath();
  final file = new File(PATH_TO_WEB_CONTENT + filePath);
  request.pipe(file.openWrite()).then((_) {
    request.response
        ..statusCode = HttpStatus.NO_CONTENT
        ..close();
    print("Wrote to file '${file.path}'");
  });
}


Create class that mimic a map to handle properties

library prop_map;

import 'dart:collection';

class PropMap extends MapBase<String, Object> {
  final _src = {};

  Object operator [](String key) => _src[key];
  operator []=(String key, Object value) => _src[key] = value;
  Iterable<String> get keys => _src.keys;
  Object remove(String key) => _src.remove(key);
  void clear() => _src.clear();
}


// 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 'layout2.dart';
import 'dart:sky' as sky;

class AppView {
  RenderView _renderView;

  void _beginFrame(double timeStamp) {
    RenderNode.flushLayout();
    _renderView.paintFrame();
  }

  void _handleEvent(sky.Event event) {
    if (event is! sky.PointerEvent)
      return;
    HitTestResult result = new HitTestResult();
    _renderView.hitTest(result, x: event.x, y: event.y);
    result.path.reversed.forEach((RenderNode node) {
      node.handlePointer(event);
    });
  }

  AppView(RenderBox root) {
    sky.view.setEventCallback(_handleEvent);
    sky.view.setBeginFrameCallback(_beginFrame);

    _renderView = new RenderView(root: root);
    _renderView.layout(newWidth: sky.view.width, newHeight: sky.view.height);

    sky.view.scheduleFrame();
  }
}

Rearrange AppView so that the constructor is first.

// 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 'layout2.dart';
import 'dart:sky' as sky;

class AppView {

  AppView(RenderBox root) {
    sky.view.setEventCallback(_handleEvent);
    sky.view.setBeginFrameCallback(_beginFrame);

    _renderView = new RenderView(root: root);
    _renderView.layout(newWidth: sky.view.width, newHeight: sky.view.height);

    sky.view.scheduleFrame();
  }

  RenderView _renderView;

  void _beginFrame(double timeStamp) {
    RenderNode.flushLayout();
    _renderView.paintFrame();
  }

  void _handleEvent(sky.Event event) {
    if (event is! sky.PointerEvent)
      return;
    HitTestResult result = new HitTestResult();
    _renderView.hitTest(result, x: event.x, y: event.y);
    result.path.reversed.forEach((RenderNode node) {
      node.handlePointer(event);
    });
  }

}


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

import 'package:matcher/matcher.dart';
import 'package:test/test.dart' show test, group;

import 'test_utils.dart';

void main() {
  _test('Map', isMap, {});
  _test('List', isList, []);
  _test('ArgumentError', isArgumentError, new ArgumentError());
  _test('Exception', isException, const FormatException());
  _test('FormatException', isFormatException, const FormatException());
  _test('StateError', isStateError, new StateError('oops'));
  _test('RangeError', isRangeError, new RangeError('oops'));
  _test('UnimplementedError', isUnimplementedError,
      new UnimplementedError('oops'));
  _test('UnsupportedError', isUnsupportedError, new UnsupportedError('oops'));
  _test('ConcurrentModificationError', isConcurrentModificationError,
      new ConcurrentModificationError());
  _test('CyclicInitializationError', isCyclicInitializationError,
      new CyclicInitializationError());
  _test('NoSuchMethodError', isNoSuchMethodError, null);
  _test('NullThrownError', isNullThrownError, new NullThrownError());

  group('custom `TypeMatcher`', () {
    _test('String', const isInstanceOf<String>(), 'hello');
    _test('String', const _StringMatcher(), 'hello');
  });
}

// TODO: drop `name` and use a type argument – once Dart2 semantics are enabled
void _test(String name, Matcher typeMatcher, Object matchingType) {
  group('for `$name`', () {
    if (matchingType != null) {
      test('succeeds', () {
        shouldPass(matchingType, typeMatcher);
      });
    }

    test('fails', () {
      shouldFail(
          const _TestType(),
          typeMatcher,
          anyOf(
              // Handles the TypeMatcher case
              equalsIgnoringWhitespace('Expected: $name Actual: ?:<TestType>'),
              // Handles the `isInstanceOf` case
              equalsIgnoringWhitespace(
                  'Expected: an instance of $name Actual: ?:<TestType>')));
    });
  });
}

class _StringMatcher extends TypeMatcher {
  const _StringMatcher() : super('String');

  bool matches(item, Map matchState) => item is String;
}

class _TestType {
  const _TestType();

  String toString() => 'TestType';
}


// 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.
// Check that const objects (including literals) are immutable.

// should be 'const {}'
invalid([var p = {}]) {
}

main() {
  invalid();
}


Add test for certain cases of unreachable code

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

// Verifies that VM is able to handle certain cases of unreachable code.

// VMOptions=--no_background_compilation --optimization_counter_threshold=10

import "package:expect/expect.dart";

class A {
  dynamic next;
}

test1(A arg1, bool arg2, bool arg3) {
  assert(arg1.next == (arg2 ?? arg3));
}

test2(A arg1, bool arg2, bool arg3) {
  print(((throw 'Error') as dynamic).next == (arg2 ?? arg3));
}

void doTests() {
  test1(new A(), null, null);
  Expect.throws(() {
    test2(new A(), null, null);
  });
}

void main() {
  for (int i = 0; i < 20; i++) {
    doTests();
  }
}


Add test for reusing the port of a server socket, after the server's close future is completed.

// 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.
//
// VMOptions=
// VMOptions=--short_socket_read
// VMOptions=--short_socket_write
// VMOptions=--short_socket_read --short_socket_write

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

Future<int> runServer(int port, int connections, bool clean) {
  var completer = new Completer();
  HttpServer.bind("127.0.0.1", port).then((server) {
    int i = 0;
    server.listen((request) {
      request.pipe(request.response);
      i++;
      if (!clean && i == 10) {
        int port = server.port;
        server.close().then((_) => completer.complete(port));
      }
    });

    Future.wait(new List.generate(connections, (_) {
      var client = new HttpClient();
      return client.get("127.0.0.1", server.port, "/")
          .then((request) => request.close())
          .then((response) => response.drain())
          .catchError((e) { if (clean) throw e; });
    })).then((_) {
      if (clean) {
        int port = server.port;
        server.close().then((_) => completer.complete(port));
      }
    });
  });
  return completer.future;
}

void testReusePort() {
  var keepAlive = new ReceivePort();
  runServer(0, 10, true).then((int port) {
    // Stress test the port reusing it 10 times.
    Future.forEach(new List(10), (_) {
      return runServer(port, 10, true);
    }).then((_) {
      keepAlive.close();
    });
  });
}

void testUncleanReusePort() {
  var keepAlive = new ReceivePort();
  runServer(0, 10, false).then((int port) {
    // Stress test the port reusing it 10 times.
    Future.forEach(new List(10), (_) {
      return runServer(port, 10, false);
    }).then((_) {
      keepAlive.close();
    });
  });
}

void main() {
  testReusePort();
  testUncleanReusePort();
}


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

library solver.msrand;

import "dart:math";

class MSRandom implements Random {
  int _seed;

  MSRandom(this._seed);

  int _rand() {
    _seed = (_seed * 214013 + 2531011) & 0x7FFFFFFF;
    return ((_seed >> 16) & 0x7fff);
  }

  int nextInt(max) {
    return _rand() % max;
  }

  double nextDouble() {
    return _rand() % 101 / 100.0;
  }

  bool nextBool() {
    return nextDouble() > 0.5;
  }
}


// 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:analyzer/analyzer.dart';
import 'package:analyzer/plugin/options.dart';
import 'package:analyzer/src/lint/registry.dart';
import 'package:yaml/yaml.dart';

/**
 * An error code indicating an undefined lint rule.
 *
 * Parameters:
 * 0: the rule name
 */
const AnalysisOptionsWarningCode UNDEFINED_LINT_WARNING =
    const AnalysisOptionsWarningCode(
        'UNDEFINED_LINT_WARNING', "'{0}' is not a recognized lint rule");

/**
 * Validates `linter` rule configurations.
 */
class LinterRuleOptionsValidator extends OptionsValidator {
  static const linter = 'linter';
  static const rulesKey = 'rules';
  @override
  List<AnalysisError> validate(
      ErrorReporter reporter, Map<String, YamlNode> options) {
    List<AnalysisError> errors = <AnalysisError>[];
    var node = options[linter];
    if (node is YamlMap) {
      var rules = node.nodes[rulesKey];
      validateRules(rules, reporter);
    }
    return errors;
  }

  validateRules(dynamic rules, ErrorReporter reporter) {
    if (rules is YamlList) {
      Iterable<String> registeredLints =
          Registry.ruleRegistry.map((r) => r.name);
      rules.nodes.forEach((YamlNode ruleNode) {
        Object value = ruleNode.value;
        if (value != null && !registeredLints.contains(value)) {
          reporter.reportErrorForSpan(
              UNDEFINED_LINT_WARNING, ruleNode.span, [value]);
        }
      });
    }
  }
}


part of ThreeD;

class EventEmitterEvent {
  String type;
  String message;
  var content;
  EventEmitterEvent({this.type, this.message, this.content});
}

class EventEmitter {

	var listeners;

	EventEmitter() : listeners = {};

	addEventListener( type, listener ) {

		if ( listeners[ type ] == null ) {
			listeners[ type ] = [];
		}

		if ( listeners[ type ].indexOf( listener ) == - 1 ) {
			listeners[ type ].add( listener );
		}

	}

	dispatchEvent( event ) {
		if ( listeners[ event.type ] != null ) {
			listeners[ event.type ].forEach((listener) => listener( event ));
                }
	}

	removeEventListener ( type, listener ) {

		var index = listeners[ type ].indexOf( listener );

		if ( index != - 1 ) {
			listeners[ type ].removeRange( index, 1 );
		}

	}

}

Fix tabs on closing brace.


Add a NNBD test that needs NNBD migrated SDK.

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

// SharedOptions=--enable-experiment=non-nullable
void main() {
}

/// These tests will all pass only if run with the NNBD migrated SDK.
/// In not migrated SDK all types are unprefixed, so look non-nullable.
void f(List<int> list, Map<int, String> map, int a, int? b) {
  // List: E operator [](int index);
  list[a]; //# 00: ok
  list[b]; //# 01: compile-time error

  // Map: V? operator [](Object? key);
  map[a]; //# 02: ok
  map[b]; //# 03: ok

  // Map: void operator []=(K key, V value);
  map[a].length; //# 04: compile-time error
  map[a]?.length; //# 05: ok

  map[b] = ''; //# 06: compile-time error
  map[a] = b; //# 07: compile-time error
}


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

import "package:testing/src/run_tests.dart" as run_tests;

main(List<String> arguments) => run_tests.main(arguments);


Test for limited optimizations on native fields

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

import "dart:_js_helper";
import "package:expect/expect.dart";

// Test that compiler is cautious with optimizations on native fields.  The
// motivation is that DOM properties are getters and setters with arbitrary
// effects.  Setting CSSStyleDeclaration.borderLeft can canonicalize the value
// and changes the value of CSSStyleDeclaration.border.

@Native("Foo")
class Foo {
  var a;
  var b;
  var ab;
}

Foo makeFoo() native;

void setup() native """
function Foo() { this.i = 0; }

Object.defineProperty(Foo.prototype, 'a', {
  get: function () { return (this._a || '') + ++this.i; },
  set: function (v) { this._a = v.toLowerCase(); }
});

Object.defineProperty(Foo.prototype, 'b', {
  get: function () { return this._b || ''; },
  set: function (v) { this._b = v.toLowerCase(); }
});

Object.defineProperty(Foo.prototype, 'ab', {
  get: function () { return this.a + ' ' + this.b; },
  set: function (v) {
    var s = v.split(' ');
    this.a = s[0];
    this.b = s[1];
  }
});

makeFoo = function() { return new Foo() }
""";

test1() {
  var f = makeFoo();
  f.a = 'Hi';
  f.b = 'There';
  Expect.equals('hi1 there', f.ab);
}

test2() {
  // Test for CSE. dart2js currently does CSE loads. Is this the right choice?
  var f = makeFoo();
  var a1 = f.a;
  var b1 = f.b;
  var a2 = f.a;
  Expect.equals('1', a1);
  if (a2 == a1) {
    // We did CSE.
  } else {
    Expect.equals('2', a2);
  }
}

test3() {
  // Must not CSE over a native field store.
  var f = makeFoo();
  var a1 = f.a;
  f.ab = 'X Y';
  var a2 = f.a;
  Expect.equals('1', a1);
  Expect.equals('x2', a2);
}

test4() {
  // Must not store-forward.
  var f = makeFoo();
  f.a = 'A';
  var a2 = f.a;
  Expect.equals('a1', a2);
}

main() {
  setup();
  (test1)();
  (test2)();
  (test3)();
  (test4)();
}


Test that .dart files are copied to packages/ in debug mode.

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

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

main() {
  initConfig();

  integration("includes .dart files from dependencies in debug mode", () {
    // Dart2js can take a long time to compile dart code, so we increase the
    // timeout to cope with that.
    currentSchedule.timeout *= 3;

    d.dir("foo", [
      d.libPubspec("foo", "0.0.1"),
      d.dir("lib", [
        d.file('foo.dart', 'foo() => print("hello");'),
        d.dir("sub", [
          d.file('bar.dart', 'bar() => print("hello");'),
        ])
      ])
    ]).create();

    d.dir(appPath, [
      d.appPubspec({
        "foo": {"path": "../foo"}
      }),
      d.dir("example", [
        d.file("main.dart", 'myapp() => print("not entrypoint");'),
        d.dir("sub", [
          d.file("main.dart", 'myapp() => print("not entrypoint");')
        ])
      ])
    ]).create();

    schedulePub(args: ["build", "--mode", "debug", "example"],
        output: new RegExp(r"Built 4 files!"));

    d.dir(appPath, [
      d.dir('build', [
        d.dir('example', [
          d.file("main.dart", 'myapp() => print("not entrypoint");'),
          d.dir('packages', [
            d.dir('foo', [
              d.file('foo.dart', 'foo() => print("hello");'),
              d.dir("sub", [
                d.file('bar.dart', 'bar() => print("hello");'),
              ])
            ])
          ]),
          d.dir("sub", [
            d.file("main.dart", 'myapp() => print("not entrypoint");'),
            // Does *not* copy packages into subdirectories.
            d.nothing("packages")
          ])
        ])
      ])
    ]).validate();
  });
}


Add regression test for null `nodeIndex` argument passed to `View.injectorGet()`

/// This regression test demonstrates why `View.injectorGet()` must null-check
/// the `nodeIndex` argument, a rare and complex case that requires a number of
/// conditions to be met.
///
///   (1) Create a component whose template contains a top-level view container;
///   this ensures the view container has a null parent index.
///
///   (2) Add directive(s) with multiple providers to any node in the
///   component's template with at least one child node; this ensures that a
///   range check on `nodeIndex` is generated in `injectorGetInternal` and not
///   skipped due to short-circuit evaluation when a node only has one provider
///   and the token doesn't match. This range check is what will throw if
///   `nodeIndex` is null.
///
///   (3) Inject a dependency via the top-level view container's
///   `parentInjector`. This causes the null parent index to pass from
///   `ElementInjector.provideUntyped()` to `View.injectorGet()`.
@TestOn('browser')
import 'package:test/test.dart';
import 'package:angular/angular.dart';
import 'package:angular_test/angular_test.dart';

import 'b_133253211_null_node_index_test.template.dart' as ng;

void main() {
  tearDown(disposeAnyRunningTest);

  test('View.injectorGet() should handle a null nodeIndex argument', () async {
    final testValue = 'Hello world!';
    final testBed = NgTestBed.forComponent(
      ng.TestComponentNgFactory,
      rootInjector: ([parent]) => Injector.map({testToken: testValue}, parent),
    );
    final testFixture = await testBed.create();
    final testComponent = testFixture.assertOnlyInstance;
    expect(
      // This parent injector, an `ElementInjector`, passes a null nodeIndex
      // parameter to `View.injectorGet()`. Note that while this looks like a
      // bizarre use case that might not seem worth supporting, this is the
      // simplest reproduction of this pattern that can be achieved far more
      // indirectly via declarative means. Clients do depend on this behavior.
      testComponent.viewContainerRef.parentInjector.provideToken(testToken),
      testValue,
    );
  });
}

@Component(
  selector: 'test',
  directives: [ProvidersDirective],
  template: '''

      Some content to create a range check on nodeIndex

  ''',
)
class TestComponent {
  @ViewChild('container', read: ViewContainerRef)
  ViewContainerRef viewContainerRef;
}

const testToken = OpaqueToken<String>('test');
const tokenA = OpaqueToken<String>('a');
const tokenB = OpaqueToken<String>('b');

@Directive(
  selector: '[providers]',
  // Multiple providers to ensure the range check isn't skipped due to short
  // circuit evaluation of mismatched token query.
  providers: [
    ValueProvider.forToken(tokenA, 'a'),
    ValueProvider.forToken(tokenB, 'b'),
  ],
)
class ProvidersDirective {}


Add library to get a topic creating it if necessary

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

library sintr_common.pubsub_utils;

import 'dart:async';

import 'package:gcloud/pubsub.dart';
import "package:logging/logging.dart" as logging;

final _log = new logging.Logger("PubSub_support");

/// Gets a topic, if it doesn't already exist, create it.
Future<Topic> getTopic(String name, PubSub ps) async {

  // Try and find the topic.
  _log.finer("PRE: Getting topic for $name");

  Topic topic;

  try {
    topic = await ps.lookupTopic(name);
  } catch (e, st) {
    _log.finer("NOK: Topic lookup failed");
    _log.finest(e);
    _log.finest(st);
  }

  if (topic != null) {
    _log.finer("OK: Existing topic found: $name");
    return topic;
  }

  // Try and create the topic.
  try {
    topic = await ps.createTopic(name);
  } catch (e, st) {
    _log.finer("NOK: Topic creation failed");
    _log.finest(e);
    _log.finest(st);
  }

  if (topic != null) {
    _log.fine("OK: Topic created: $name");
    return topic;
  }

  // The creation make have failed because of a race between the lookup and
  // the creation.
  try {
    topic = await ps.lookupTopic(name);
  } catch (e, st) {
    _log.finer("NOK: Topic lookup failed");
    _log.finest(e);
    _log.finest(st);
  }

  if (topic != null) {
    _log.finer("OK: Topic found after race: $name");
    return topic;
  }

  _log.shout("FAIL: Topic not $name");
  throw "Topic not found: $name";
}


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

// Regression test for CL 194523002.

library js_custom_test;

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

class A extends HtmlElement {
  static final tag = 'x-a';
  factory A() => new Element.tag(tag);
  A.created() : super.created();
}

main() {
  useHtmlConfiguration();

  // Adapted from Blink's
  // fast/dom/custom/constructor-calls-created-synchronously test.

  var registered = false;
  setUp(() {
    return customElementsReady.then((_) {
      if (!registered) {
        registered = true;
        document.register(A.tag, A);
      }
    });
  });
}


Add test to validate SourceSpan values for nodes

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

import 'dart:convert';

import 'package:source_span/source_span.dart';
import 'package:test/test.dart';
import 'package:yaml/yaml.dart';

void _expectSpan(SourceSpan source, String expected) {
  final result = source.message('message');
  printOnFailure("r'''\n$result'''");

  expect(result, expected);
}

void main() {
  YamlMap yaml;

  setUpAll(() {
    yaml = loadYaml(const JsonEncoder.withIndent(' ').convert({
      'num': 42,
      'nested': {
        'null': null,
        'num': 42,
      },
      'null': null,
    })) as YamlMap;
  });

  test('first root key', () {
    _expectSpan(
      yaml.nodes['num'].span,
      r'''
line 2, column 9: message
  ╷
2 │  "num": 42,
  │         ^^
  ╵''',
    );
  });

  test('first root key', () {
    _expectSpan(
      yaml.nodes['null'].span,
      r'''
line 7, column 10: message
  ╷
7 │  "null": null
  │          ^^^^
  ╵''',
    );
  });

  group('nested', () {
    YamlMap nestedMap;

    setUpAll(() {
      nestedMap = yaml.nodes['nested'] as YamlMap;
    });

    test('first root key', () {
      _expectSpan(
        nestedMap.nodes['null'].span,
        r'''
line 4, column 11: message
  ╷
4 │   "null": null,
  │           ^^^^
  ╵''',
      );
    });

    test('first root key', () {
      _expectSpan(
        nestedMap.nodes['num'].span,
        r'''
line 5, column 10: message
  ╷
5 │     "num": 42
  │ ┌──────────^
6 │ │  },
  │ └─^
  ╵''',
      );
    });
  });
}


// Copyright (c) 2014, the Liquid 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 liquid.utils;

class AssertionFailure {
  final String message;

  const AssertionFailure(this.message);

  String toString() => message;
}

bool invariant(condition, [message]) {
  if (condition is Function){
    condition = condition();
  }
  if (!condition) {
    if (message is Function) {
      message = message();
    }
    throw new AssertionFailure(message);
  }
  return true;
}


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

// Example of retrieving a sensor using the Sensor API.

// C++ implementation can be found here:
// https://docs.microsoft.com/en-us/windows/win32/sensorsapi/retrieving-a-sensor

import 'dart:ffi';

import 'package:ffi/ffi.dart';
import 'package:win32/win32.dart';

void main() {
  CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);

  final sensorManager = SensorManager.createInstance();

  // Replace this with the sensor category you're looking for.
  final sampleDateTimeSensorCategory =
      GUIDFromString('{062A5C3B-44C1-4ad1-8EFC-0F65B2E4AD48}');
  final pSensorsColl = calloc<Pointer<COMObject>>();
  var hr = sensorManager.GetSensorsByCategory(
      sampleDateTimeSensorCategory, pSensorsColl);
  if (FAILED(hr)) throw WindowsException(hr);

  final coll = ISensorCollection(pSensorsColl.cast());
  final pCount = calloc<Uint32>();
  if (coll.GetCount(pCount) > 1) {
    print('Found items');
  }

  free(pCount);
  free(pSensorsColl);
  free(sampleDateTimeSensorCategory);

  CoUninitialize();
}


Add small integration test for generated upserts

import 'package:moor/moor.dart';
import 'package:moor_ffi/moor_ffi.dart';
@TestOn('vm')
import 'package:test/test.dart';

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

void main() {
  TodoDb db;

  setUp(() {
    db = TodoDb(VmDatabase.memory());
  });

  test('insertOnConflictUpdate', () async {
    await db.into(db.categories).insert(
        CategoriesCompanion.insert(description: 'original description'));

    var row = await db.select(db.categories).getSingle();

    await db.into(db.categories).insertOnConflictUpdate(CategoriesCompanion(
        id: Value(row.id), description: const Value('changed description')));

    row = await db.select(db.categories).getSingle();
    expect(row.description, 'changed description');
  });
}


Add the stringtoUint8List utility function

import 'dart:convert' show UTF8;
import 'dart:typed_data' show Uint8List;

final _padding = [
  0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0,
];

Uint8List stringToUint8List(String value) =>
  new Uint8List.fromList(
    (UTF8.encode(value).toList()
      ..addAll(_padding)
    ).sublist(0, 32),
  );


Test that expose a few quirks in the Dart VM parser.

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

// Test that a Dart implementation doesn't turn dynamic errors into
// compilation errors.

f(x) {}

class MyClass {
  MyClass(x, y);

  foo() {
    var z;
    // Neither y nor x are defined. So they are simply dynamic
    // (getter) sends to this, not compile-time errors.
    if (false) f(new MyClass(z, y[x.y.z]));
    if (false) print(y[x.y.z]);
  }
}

main() {
  var x;
  // We know the concrete type of f (a function closure) does not
  // support the index operator. However, this is a dynamic error, so
  // this program should compile.
  if (false) print(f[x.y.z]);
  new MyClass(0, 0).foo();
}


Add a simple test for HTMLOptionsCollection.

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

#library('HTMLOptionsCollectionTest');
#import('../../lib/unittest/unittest.dart');
#import('../../lib/unittest/html_config.dart');
#import('dart:html');

main() {
  useHtmlConfiguration();

  test('indexedAccessTest', () {
    // FIXME: we need some massaging to dart:html to enable HTMLOptionsCollection.add
    // and hence programatic building of collection.
    final selectElement = new Element.html('''
      <select>
        <option value="0">Option0</option>
        <option value="1">Option1</option>
        <option value="2">Option2</option>
      ''');
    final optionsCollection = selectElement.options;

    expect(optionsCollection[0].value, equals('0'));
    expect(optionsCollection[1].value, equals('1'));
    expect(optionsCollection[2].value, equals('2'));

    expect(optionsCollection[0].text, equals('Option0'));
    expect(optionsCollection[1].text, equals('Option1'));
    expect(optionsCollection[2].text, equals('Option2'));

    expect(() { optionsCollection[0] = 1; }, throws);

    optionsCollection[0] = new OptionElement(value: '42', data: 'Option42');
    expect(optionsCollection[0].value, equals('42'));
    expect(optionsCollection[0].text, equals('Option42'));
  });
}


Add test for missing initializer on final instance variable

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


Add test demonstrating that FutureOr<A> <: FutureOr<B> =/=> A <: B.

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

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

class A implements Future<Future<A>> {
  @override
  noSuchMethod(Invocation _) {}
}

void main() {
  Expect.notSubtype<A, Future<A>>();
  Expect.subtype<FutureOr<A>, FutureOr<Future<A>>>();
}


Test that safe saves are picked up by pub serve.

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

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

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

main() {
  // This is a regression test for http://dartbug.com/21402.
  initConfig();
  withBarbackVersions("any", () {
    integration("picks up files replaced after serving started when using the "
        "native watcher", () {
      d.dir(appPath, [
        d.pubspec({
          "name": "myapp",
          "transformers": ["myapp/src/transformer"]
        }),
        d.dir("lib", [d.dir("src", [
          d.file("transformer.dart", REWRITE_TRANSFORMER)
        ])]),
        d.dir("web", [
          d.file("file.txt", "before"),
        ]),
        d.file("other", "after")
      ]).create();

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

      pubServe(args: ["--no-force-poll"]);
      waitForBuildSuccess();
      requestShouldSucceed("file.out", "before.out");

      schedule(() {
        // Replace file.txt by renaming other on top of it.
        return new File(p.join(sandboxDir, appPath, "other"))
            .rename(p.join(sandboxDir, appPath, "web", "file.txt"));
      });

      // Read the transformed file to ensure the change is actually noticed by
      // pub and not that we just get the new file contents piped through
      // without pub realizing they've changed.
      waitForBuildSuccess();
      requestShouldSucceed("file.out", "after.out");

      endPubServe();
    });
  });
}


Add Dart implementation of Selection Sort

/// Selection Sort the input list
void selectionSort(List<int> items) {
  // Iterate through the array, knowing left-of-i is sorted and looking
  // for the lowest to-the-right element to place at the end of left
  for (int i = 0; i < items.length - 1; i++) {
    int lowestIndex = i;
    for (int j = i + 1; j < items.length; j++) {
      if (items[j] < items[lowestIndex]) {
        lowestIndex = j;
      }
    }

    // Swap the lowest item with this position (i)
    final int lowestNumber = items[lowestIndex];
    items[lowestIndex] = items[i];
    items[i] = lowestNumber;
  }
}
 // ----- Test -----
void main() {
  // 1. Arrange
  final List<int> testedList = [10, 2, 8, 5, 6, 1, 4, 7, 9, 3];
  final List<int> expectedOutput = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
   // 2. Act
  selectionSort(testedList);
  print(testedList);
   // 3. Assert
  // No simple list equality in dart yet so using 'fold' to recursively check
  // each sorted element compared to the expected output at each index.
  int i = 0;
  final bool isEqual = testedList.fold(
    true,
    (result, item) => result && item == expectedOutput[i++],
  );
  print(isEqual);
}


Support named parameters for super initializers and redirections.

// 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.
// Dart test program for default constructors.

String message;

foo() {
  message += 'foo';
  return 1;
}

bar() {
  message += 'bar';
  return 2;
}

class X {
  var i;
  var j;
  X([a = 'defa', b = 'defb']) : this.i = a, this.j = b;
  X.foo() : this(b: 1, a: 2);
  X.bar() : this(
                     1,  /// 01: compile-time error
                     a: 2);
  X.baz() : this(a: 1, b: 2);
  X.qux() : this(1, 2);
  X.hest() : this();
  X.fisk() : this(b: bar(), a: foo());
  X.naebdyr() : this(a: foo(), b: bar());
}

test(x, a, b) {
  Expect.equals(x.i, a);
  Expect.equals(x.j, b);
}

main() {
  test(new X.foo(), 2, 1);
  test(new X.bar(), 2, 'defb');
  test(new X.baz(), 1, 2);
  test(new X.qux(), 1, 2);
  test(new X.hest(), 'defa', 'defb');

  message = '';
  new X.fisk();
  Expect.equals('barfoo', message);

  message = '';
  new X.naebdyr();
  Expect.equals('foobar', message);
}


Add language test with nested function typedef with two references to argument

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

// Check function subtyping of type arguments. These cases use typedefs as type
// arguments, and the typedefs have type parameters that are used more than
// once.

import 'package:expect/expect.dart';

typedef A F<A>(A arg1, A arg2);
typedef B G<A,B>(B arg1, B arg2);

typedef Set<A> FS<A>(Set<A> arg1, Set<A> arg2);

@NoInline() @AssumeDynamic() dyn(x) => x;

class CheckEnv<X, Y> {
  test(bool intX) {
    Expect.isTrue(<F<X>>[] is List<F>);
    Expect.isTrue(<F<X>>[] is List<F<X>>);
    Expect.isTrue(<F<X>>[] is List<G<Y,X>>);

    Expect.isTrue(dyn(<F<X>>[]) is List<F>);
    Expect.isTrue(dyn(<F<X>>[]) is List<F<X>>);
    Expect.isTrue(dyn(<F<X>>[]) is List<G<Y,X>>);

    Expect.isTrue(<F<X>>[] is! List<F<Y>>);
    Expect.isTrue(<F<X>>[] is! List<G<X,Y>>);

    Expect.isTrue(dyn(<F<X>>[]) is! List<F<Y>>);
    Expect.isTrue(dyn(<F<X>>[]) is! List<G<X,Y>>);

    Expect.isTrue(dyn(<FS<X>>[]) is List<FS>);
    Expect.isTrue(dyn(<FS<X>>[]) is List<FS<X>>);
    if (intX) {
      Expect.isTrue(dyn(<FS<X>>[]) is List<FS<int>>);
      Expect.isTrue(dyn(<FS<int>>[]) is List<FS<X>>);
      Expect.isTrue(dyn(<FS<Y>>[]) is! List<FS<int>>);
      Expect.isTrue(dyn(<FS<int>>[]) is! List<FS<Y>>);
    }
  }
}

main() {
  Expect.isTrue(<F<int>>[] is List<F<int>>);
  Expect.isTrue(dyn(<F<int>>[]) is List<F<int>>);
  Expect.isTrue(<F<int>>[] is List<G<bool,int>>);
  Expect.isTrue(dyn(<F<int>>[]) is List<G<bool,int>>);

  new CheckEnv<int,String>().test(true);
  new CheckEnv<String,int>().test(false);
}


Add platform-independent test to fix Ubuntu flake

import 'dart:ffi';

import 'package:ffi/ffi.dart';
import 'package:test/test.dart';
import 'package:win32/win32.dart';

// This test prevents CI from failing on other platforms (GitHub Actions fails
// unless at least one test is run successfully.)
void main() {
  test('Neutral test to give non-Windows platforms something to chew on', () {
    final point = calloc<POINT>()
      ..ref.x = 0x10
      ..ref.y = 0x7F;
    expect(point.ref.x + point.ref.y, equals(0x8F));
    free(point);
  });
}


Add a test that shows that "expression has changed" works.

import 'package:angular_test/angular_test.dart';
import 'package:test/test.dart';
import 'package:angular/angular.dart';

import 'expect_no_changes_dev_mode_test.template.dart' as ng_generated;

void main() {
  ng_generated.initReflector();

  test('should throw during change detection', () async {
    final testBed = new NgTestBed<IllegalChangeDetectionComponent>();
    expect(
      testBed.create(),
      throwsA(predicate(
        (e) => '$e'.contains('Expression has changed after it was checked'),
      )),
    );
  });
}

@Component(
  selector: 'illegal-change-detection',
  template: r'''
    <div>{{counter}}</div>
  ''',
)
class IllegalChangeDetectionComponent {
  var _counter = 0;
  int get counter => _counter++;
}


Add check that no aggressive & incorrect optimizations is done.

// 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.
// Dart test program checking that optimizations are not too aggresive and
// incorrect:
// - (a * (1.0 / b))
//
// VMOptions=--optimization-counter-threshold=8 --no-use-osr

import "package:expect/expect.dart";

var xx = 23.0;

main() {
  xx = 1e-6;
  scaleIt(1e-310);
  Expect.isTrue(xx.isInfinite);
  for (int i = 0; i < 10; i++) {
    xx = 24.0;
    scaleIt(6.0);
    Expect.equals(4.0, xx);
  }
  xx = 1e-6;
  scaleIt(1e-310);
  Expect.isTrue(xx.isInfinite);
}

scaleIt(double b) {
  scale(1.0 / b);
}

scale(a) {
  xx *= a;
}


Add computation for a floating point wheel

/// Computes what the probability should be set for each wheel if
/// there are five of them and success is 3+ successful wheels.
library compute_floating_setup;

import 'dart:math';

void main() {
  for (int i = 0; i <= 100; i++) {
    final p = i / 100;
    print('$p, ${computeTotalProbability(p)}');
  }
}

double computeTotalProbability(double wheelProbability, [int wheelCount = 5]) {
  final possibleResults = getPossibleResults(wheelCount);

  // print("count: ${possibleResults.length}");

  // print(possibleResults);
  // print(possibleResults.where((result) => result.isWinning).length);

  var total = 0.0;
  var winningTotal = 0.0;
  for (final result in possibleResults) {
    final partial = result.probability(wheelProbability);
    // print("$result (${result.isWinning ? 'win' : 'lose'}) = $partial");
    total += partial;
    winningTotal += result.isWinning ? partial : 0;
  }

  // print(total);
  return winningTotal;
}

List<Result> getPossibleResults(int wheelCount) {
  final pools =
      List<List<bool>>.filled(wheelCount, const [true, false], growable: false);
  final set = product(pools);
  assert(
      set.length == pow(2, wheelCount), "The resulting set should be n ** r.");
  return set.map((result) => Result(result)).toList(growable: false);
}

/// Returns Cartesian product of a list of [pools].
/// https://en.wikipedia.org/wiki/Cartesian_product
Iterable<List<T>> product<T>(List<List<T>> pools) sync* {
  if (pools.length < 2) throw ArgumentError(pools);
  if (pools.length == 2) {
    for (final x in pools.first) {
      for (final y in pools.last) {
        yield [x, y];
      }
    }
    return;
  }

  for (final x in pools.first) {
    for (final y in product(pools.sublist(1))) {
      yield [x] + y;
    }
  }
}

class Result {
  final List<bool> wheelResults;

  const Result(this.wheelResults);

  bool get isWinning =>
      wheelResults.where((result) => result).length > wheelResults.length / 2;

  /// Probability that this exact result will be shown, given probability
  /// setting of each wheel.
  double probability(double wheelProbability) {
    double result = 1.0;
    for (final wheelResult in wheelResults) {
      if (wheelResult) {
        result *= wheelProbability;
      } else {
        result *= (1 - wheelProbability);
      }
    }
    return result;
  }

  @override
  String toString() => wheelResults.toString();
}


@Tags(const ['codegen'])
@TestOn('browser')
import 'dart:async';

import 'package:angular_test/angular_test.dart';
import 'package:test/test.dart';
import 'package:angular/angular.dart';

void main() {
  tearDown(disposeAnyRunningTest);

  // Regression test for https://github.com/dart-lang/angular2/issues/164.
  test('should update an NgForm without throwing an NPE', () async {
    final testBed = new NgTestBed<AppComponent>();
    expect(
      (await testBed.create()).rootElement.innerHtml,
      contains(r'<input title="Input #0:true">'),
    );
  });
}

@Component(
  selector: 'root',
  directives: const [
    FORM_DIRECTIVES,
    NgFor,
  ],
  template: r'''
    <form>
      <input *ngFor="let val of values; let idx = index"
             [ngModel]="val"
             ngControl="input-{{idx}}"
             title="Input #{{idx}}:{{val}}">
    </form>
  ''',
)
class AppComponent {
  Iterable<String> values;
  bool b = false;

  AppComponent() {
    _update();
    Timer.run(_update);
  }

  void _update() {
    values = new List.from([b.toString()]);
    print(values);
    b = !b;
  }
}

Replace FORM_DIRECTIVES with formDirectives in one of the tests, this seems to work.

@Tags(const ['codegen'])
@TestOn('browser')
import 'dart:async';

import 'package:angular_test/angular_test.dart';
import 'package:test/test.dart';
import 'package:angular/angular.dart';

void main() {
  tearDown(disposeAnyRunningTest);

  // Regression test for https://github.com/dart-lang/angular2/issues/164.
  test('should update an NgForm without throwing an NPE', () async {
    final testBed = new NgTestBed<AppComponent>();
    expect(
      (await testBed.create()).rootElement.innerHtml,
      contains(r'<input title="Input #0:true">'),
    );
  });
}

@Component(
  selector: 'root',
  directives: const [
    formDirectives,
    NgFor,
  ],
  template: r'''
    <form>
      <input *ngFor="let val of values; let idx = index"
             [ngModel]="val"
             ngControl="input-{{idx}}"
             title="Input #{{idx}}:{{val}}">
    </form>
  ''',
)
class AppComponent {
  Iterable<String> values;
  bool b = false;

  AppComponent() {
    _update();
    Timer.run(_update);
  }

  void _update() {
    values = new List.from([b.toString()]);
    print(values);
    b = !b;
  }
}


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

// Test that dump-info has no effect on the compiler output.

import 'dart:io';

import 'package:path/path.dart' as path;
import 'package:expect/expect.dart';

import 'launch_helper.dart' show dart2JsCommand;

copyDirectory(Directory sourceDir, Directory destinationDir) {
  for (var element in sourceDir.listSync()) {
    if (element.path.endsWith('.git')) continue;
    String newPath =
        path.join(destinationDir.path, path.basename(element.path));
    if (element is File) {
      element.copySync(newPath);
    } else if (element is Directory) {
      Directory newDestinationDir = new Directory(newPath);
      newDestinationDir.createSync();
      copyDirectory(element, newDestinationDir);
    }
  }
}

void main() {
  Directory tmpDir = Directory.systemTemp.createTempSync('dump_info_test_');
  Directory out1 = new Directory.fromUri(tmpDir.uri.resolve('without'));
  out1.createSync();
  Directory out2 = new Directory.fromUri(tmpDir.uri.resolve('with'));
  out2.createSync();
  Directory sunflowerDir =
      new Directory.fromUri(Uri.base.resolve('third_party/sunflower'));

  print("Copying '${sunflowerDir.path}' to '${tmpDir.path}'.");
  copyDirectory(sunflowerDir, tmpDir);
  try {
    var command =
        dart2JsCommand(['--out=without/out.js', 'web/sunflower.dart']);
    print('Run $command');
    var result = Process.runSync(Platform.resolvedExecutable, command,
        workingDirectory: tmpDir.path);
    print('exit code: ${result.exitCode}');
    print('stdout:');
    print(result.stdout);
    print('stderr:');
    print(result.stderr);
    Expect.equals(0, result.exitCode);
    String output1 = new File.fromUri(tmpDir.uri.resolve('without/out.js'))
        .readAsStringSync();

    command = dart2JsCommand(
        ['--out=with/out.js', 'web/sunflower.dart', '--dump-info']);
    print('Run $command');
    result = Process.runSync(Platform.resolvedExecutable, command,
        workingDirectory: tmpDir.path);
    print('exit code: ${result.exitCode}');
    print('stdout:');
    print(result.stdout);
    print('stderr:');
    print(result.stderr);
    Expect.equals(0, result.exitCode);
    String output2 =
        new File.fromUri(tmpDir.uri.resolve('with/out.js')).readAsStringSync();

    print('Compare outputs...');
    Expect.equals(output1, output2);
    print('Done');
  } finally {
    print("Deleting '${tmpDir.path}'.");
    tmpDir.deleteSync(recursive: true);
  }
}


Test of dynamic argument type check for redirecting factories.

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

class A implements B {
  var x;
  A(Object this.x);
}

class B {
  factory B(String s) = A;
}

main() {
  B(42 as dynamic); //# 01: runtime error
}


/*
 * Package : dartivity_database
 * Author : S. Hamblett <steve.hamblett@linux.com>
 * Date   : 05/011/2015
 * Copyright :  S.Hamblett 2015
 */

part of dartivity_database;

class DartivityCache {
  /// The cache
  Map<String, dynamic> _cache;

  DartivityCache() {
    _cache = new Map<String, dynamic>();
  }

  /// get
  dynamic get(String key) {
    if (_cache.containsKey(key)) {
      return _cache[key];
    } else {
      return null;
    }
  }

  /// put
  put(String key, dynamic resource) {
    _cache[key] = resource;
  }

  /// clear
  void clear() {
    _cache.clear();
  }
}


Create a parent package that imports all extensions at once.

/// More Dart — Literally.
export 'package:more/async.dart';
export 'package:more/cache.dart';
export 'package:more/char_matcher.dart';
export 'package:more/collection.dart';
export 'package:more/hash.dart';
export 'package:more/iterable.dart';
export 'package:more/math.dart';
export 'package:more/number.dart';
export 'package:more/ordering.dart';
export 'package:more/printer.dart';
export 'package:more/tuple.dart';


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

// Test for type literals as compile-time constants.

class C<T> {
  void m() {
    const List lst = const [
                            T /// 01: compile-time error
                             ];
  }
}

main() {
  new C().m();
}


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

// This file is responsible for accepting the results of a map oepration
// and structuring it ready to be passed to the reducer

// This version performs the shuffling in memory and so is a potential scaling
// bottleneck
Map shuffle(List<Map> data) {
  Map results = {};
  for (Map kv in data) {
    assert(kv.length == 1);
    var key = kv.keys.first;
    var value = kv.values.first;

    results.putIfAbsent(key, () => []);
    results[key].add(value);
  }
  return results;
}

_main() {
  print (shuffle([{"a" : 1}, {"b" : 2}, {"a" : 2}]));
}


Add rule service in client to interact with rule server

import 'dart:async';

import 'package:angular/angular.dart';
import 'package:http/http.dart';

import '../data_model/create_user_request.pb.dart';
import '../data_model/rule.pb.dart';

/// A class to interact with the Rules Builder server.
@Injectable()
class RuleService {
  /// The base URL of the Rules Builder server.
  static const serverUrl =
      'https://rules-server-dot-spreadsheet-dv360-plugin.uc.r.appspot.com';

  /// The endpoint for operations on users.
  static const usersEndpoint = '$serverUrl/users';

  /// The endpoint for operations on rules.
  static const rulesEndpoint = '$serverUrl/rules';

  /// Creates a user using the user's ID token and refresh token.
  Future<void> createUser(String idToken, String refreshToken) async {
    final headers = {
      'Content-Type': 'application/x-protobuf',
      'Authorization': 'Bearer $idToken'
    };
    final createUserRequest = CreateUserRequest()..refreshToken = refreshToken;
    await post(usersEndpoint,
        body: createUserRequest.writeToBuffer(), headers: headers);
  }

  /// Creates a rule using the user's ID token and rule proto.
  Future<void> createRule(String idToken, Rule rule) async {
    final headers = {
      'Content-Type': 'application/x-protobuf',
      'Authorization': 'Bearer $idToken'
    };
    await post(rulesEndpoint, body: rule.writeToBuffer(), headers: headers);
  }
}


// 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.
library scissors.test.path_resolver_test;

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

import 'package:test/test.dart';
import 'package:scissors/src/utils/path_resolver.dart' show pathResolver;
import 'package:scissors/testing/transformer_test_utils.dart';

main() {
  if (Platform.environment['TRAVIS'] == 'true') {
    print("WARNING: Skipping path resolver tests on Travis.");
    return;
  }

  group('pathResolver', () {

    var executables = {
      'sassc': pathResolver.defaultSassCPath,
      'pngcrush': pathResolver.defaultPngCrushPath,
      'cssjanus': pathResolver.defaultCssJanusPath,
      'java': pathResolver.defaultJavaPath,
    };
    var files = {
      'jruby': pathResolver.defaultJRubyPath,
      'ruby sass': pathResolver.defaultRubySassPath,
      'closure': pathResolver.defaultClosureCompilerJarPath
    };
    var dirs = {
      'compass stylesheets': pathResolver.defaultCompassStylesheetsPath,
    };

    check(String kind, String name, String path, Future action(String resolved)) {
      if (path == null) {
        print("WARNING: No path set for $name.");
      } else {
        test('finds $kind $name ($path)', () async {
          var resolved = await pathResolver.resolvePath(path);
          await action(resolved);
        });
      }
    }

    executables.forEach((name, path) {
      check('executable', name, path, (resolved) async {
        expect(hasExecutable(resolved), true);
      });
    });
    files.forEach((name, path) {
      check('file', name, path, (resolved) async {
        expect(await new File(resolved).exists(), true);
      });
    });
    dirs.forEach((name, path) {
      check('directory', name, path, (resolved) async {
        expect(await new Directory(resolved).exists(), true);
      });
    });
  });
}


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

import 'dart:io';
import 'package:args/args.dart';
import 'package:http/http.dart' as http;
import 'package:source_maps/source_maps.dart';

ArgParser parser = new ArgParser()
  ..addFlag('inline',
      abbr: 'i',
      negatable: true,
      help: 'Inline untranslatable parts..',
      defaultsTo: false);

main(List<String> arguments) async {
  ArgResults options = parser.parse(arguments);

  if (options.rest.length != 1) {
    print('Usage: <script.dart> [<options>] <file or url for source map file>\n'
        'Options:\n'
        '${parser.usage}');
    exit(2);
  }

  String url = options.rest[0];
  String data;
  if (url.startsWith("http://") || url.startsWith("https://")) {
    data = (await http.get(url)).body;
  } else {
    data = new File(url).readAsStringSync();
  }

  SingleMapping sourceMap = parse(data);

  print("Now paste the stacktrace here. Finish with at least 3 empty lines...");

  int emptyInARow = 0;
  List<String> lines = [];
  while (true) {
    String line = stdin.readLineSync();
    if (line == null) break;
    if (line == "") {
      ++emptyInARow;
    } else {
      lines.add(line);
      emptyInARow = 0;
    }

    if (emptyInARow >= 3) break;
  }

  List<String> tailMessages = [];

  for (String line in lines) {
    Iterable<Match> ms = new RegExp(r"(\d+):(\d+)").allMatches(line);
    if (ms.isEmpty) {
      if (options['inline']) {
        print("----- (unparseable) -----");
      } else {
        tailMessages.add("Unparseable line: $line");
      }
      continue;
    }
    Match m = ms.first;
    int l = int.parse(m.group(1));
    int c = int.parse(m.group(2));
    SourceMapSpan span = sourceMap.spanFor(l, c);
    if (span?.start == null) {
      if (options['inline']) {
        print("----- (unparseable) -----");
      } else {
        tailMessages.add("No sourcemap entry for line line: $line");
      }
      continue;
    }
    print(span.start.toolString);
  }

  if (tailMessages.isNotEmpty) {
    print("");
    print("Messages:");
    print("");
    for (String line in tailMessages) {
      print(line);
    }
  }
}


Add another test for initializing dispatchPropertyName that runs outside the browser

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

// Test for initialization of dispatchPropertyName.

import "package:expect/expect.dart";
import 'dart:_foreign_helper' show JS;
import 'dart:_js_helper' show Native;

@Native("Foo")
class Foo {
  String method(String x) native;
}

makeFoo() native;

void setup() native r"""
function Foo() {}
Foo.prototype.method = function(x) { return 'Foo ' + x; }

self.makeFoo = function() { return new Foo(); }
""";

main() {
  setup();

  // If the dispatchPropertyName is uninitialized, it will be `undefined` or
  // `null` instead of the secret string or Symbol. These properties on
  // `Object.prototype` will be retrieved by the lookup instead of `undefined`
  // for the dispatch record.
  JS('', r'self.Object.prototype["undefined"] = {}');
  JS('', r'self.Object.prototype["null"] = {}');
  Expect.equals('Foo A', makeFoo().method('A'));

  // Slightly different version that has malformed dispatch records.
  JS('', r'self.Object.prototype["undefined"] = {p: false}');
  JS('', r'self.Object.prototype["null"] = {p: false}');
  Expect.equals('Foo B', makeFoo().method('B'));
}


Add a test for inferring the length of typed data lists.

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

import 'package:expect/expect.dart';
import "package:async_helper/async_helper.dart";
import 'package:compiler/implementation/types/types.dart'
    show ContainerTypeMask, TypeMask;

import 'memory_compiler.dart';
import 'compiler_helper.dart' show findElement;
import 'type_mask_test_helper.dart';

const TEST = const {
  'main.dart' : r'''
import 'dart:typed_data';

var myList = new Float32List(42);
var myOtherList = new Uint8List(32);

main() {
  var a = new Float32List(9);
  return myList[0] + myOtherList[0];
}
'''};

void main() {
  var compiler = compilerFor(TEST);
  asyncTest(() => compiler.run(Uri.parse('memory:main.dart')).then((_) {
    var typesInferrer = compiler.typesTask.typesInferrer;

    checkType(String name, type, length) {
      var element = findElement(compiler, name);
      TypeMask mask = typesInferrer.getTypeOfElement(element);
      Expect.isTrue(mask.isContainer);
      ContainerTypeMask container = mask;
      Expect.equals(type, simplify(container.elementType, compiler), name);
      Expect.equals(container.length, length);
    }

    checkType('myList', compiler.typesTask.numType, 42);
    checkType('myOtherList', compiler.typesTask.uint31Type, 32);
  }));
}


Create helper to detect public IP addresses.

import 'dart:io';

class IpAddressHelper {
  /// Returns true if IP address is not a loopback, link local, or private IP
  ///
  /// Throws a generic exception if [ipAddress] cannot be parsed
  static bool isPublic(String ipAddress) {
    final parsedAddress = InternetAddress.tryParse(ipAddress);

    if (parsedAddress == null) {
      throw Exception();
    }

    if (parsedAddress.isLinkLocal || parsedAddress.isLoopback) {
      return false;
    }

    if (parsedAddress.type == InternetAddressType.IPv4) {
      RegExp privateV4 = RegExp(
        r"(^192\.168\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])$)|(^172\.([1][6-9]|[2][0-9]|[3][0-1])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])$)|(^10\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])$)",
      );

      if (privateV4.hasMatch(parsedAddress.address)) {
        return false;
      }
    }

    if (parsedAddress.type == InternetAddressType.IPv6) {
      if (parsedAddress.address.startsWith('fe80')) {
        return false;
      }
    }

    return true;
  }
}


import "package:unittest/unittest.dart";

import "package:furi/furi.dart";

class STest extends ToStringOp {
  String call() => "my calculated string";
}

void main(){
  group( "basic Op extension", (){
    test( "ToStringOp", (){
       expect( new STest()(), equals("my calculated string") );
    });
  });
}


import 'dart:io';

void main() {
  int a = int.parse(stdin.readLineSync() ?? '');
  int b = int.parse(stdin.readLineSync() ?? '');

  int soma = a + b;

  print("SOMA = $soma");
}


import 'dart:io';

void main() {
  String _ = stdin.readLineSync() ?? '';
  double a = double.parse(stdin.readLineSync() ?? '');
  double b = double.parse(stdin.readLineSync() ?? '');
  double salary = a + b * 0.15 * 100 / 100;

  print("TOTAL = R\$ ${salary.toStringAsFixed(2)}");
}


Test error for -e and ~e when e is potentially nullable

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

class C {
  C e() => this;
  C operator -() => this;
  C operator ~() => this;
}

void main() {
  final C? c = new C();
  /**/ -c?.e();
  //    ^^^^^^
  // [analyzer] COMPILE_TIME_ERROR.UNCHECKED_USE_OF_NULLABLE_VALUE
  //   ^
  // [cfe] Operator 'unary-' cannot be called on 'C?' because it is potentially null.

  /**/ ~c?.e();
  //    ^^^^^^
  // [analyzer] COMPILE_TIME_ERROR.UNCHECKED_USE_OF_NULLABLE_VALUE
  //   ^
  // [cfe] Operator '~' cannot be called on 'C?' because it is potentially null.
}


Add a test of creating a subtype of Never

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

// SharedOptions=--enable-experiment=non-nullable

// Test that it is an error for a class to extend, implement, or mixin the type
// Never.
class A extends Never {} //# 01: compile-time error

class A implements Never {} //# 02: compile-time error

class A with Never {} //# 03: compile-time error

mixin M on Never {} //# 04: compile-time error

main() {}


Create helper for casting value to type.

import 'package:meta/meta.dart';
import 'package:quiver/strings.dart';

enum CastType {
  bool,
  int,
  double,
  string,
}

class ValueHelper {
  /// Casts [value] to specified [CastType].
  ///
  /// If casting fails returns null.
  /// If nullEmptyString is true returns null when item is empty string.
  static dynamic cast({
    @required dynamic value,
    @required CastType type,
    bool nullEmptyString = true,
  }) {
    if (type == CastType.bool) {
      if ([1, true, '1', 'true'].contains(value)) {
        return true;
      } else if ([0, false, '0', 'false'].contains(value)) {
        return false;
      } else {
        return null;
      }
    }
    if (type == CastType.int) {
      return int.tryParse(value.toString());
    }
    if (type == CastType.double) {
      return double.tryParse(value.toString());
    }
    if (type == CastType.string) {
      if (isEmpty(value)) {
        if (nullEmptyString) {
          return null;
        } else {
          return '';
        }
      } else {
        return value.toString();
      }
    }
  }
}


Create a ActiveItemDirective that will replace the ActiveItemMixin.

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

import 'dart:html' as dom;

import 'package:angular/angular.dart';
import 'package:js/js_util.dart' as js_util;
import 'package:angular_components/utils/browser/dom_service/dom_service.dart';

/// Directive for elements able to be activated through mouse or keyboard, like
/// list elements.
///
/// Will scroll the item into view as long as it was made active when mouse is
/// not hovering over it.
@Directive(selector: '[itemActive]')
class ActiveItemDirective {
  /// Dom element of the item, that will be scrolled to view on activate.
  dom.HtmlElement _element;

  /// An instance of DomService, used to coordinate scrolling.
  DomService _domService;

  bool _active = false;

  /// Whether the element is active.
  @HostBinding('class.active')
  bool get active => _active;

  ActiveItemDirective(this._element, this._domService);

  /// Marks item as active from keyboard selection.
  @Input()
  set itemActive(bool value) {
    if (value == _active) return;
    _active = value;
    if (_active && !_hasHover) {
      _domService.scheduleWrite(() {
        try {
          var options = js_util.newObject();
          js_util.setProperty(options, 'block', 'nearest');
          js_util.setProperty(options, 'inline', 'nearest');
          js_util.callMethod(_element, 'scrollIntoView', [options]);
        } catch (_) {
          _element.scrollIntoView();
        }
      });
    }
  }

  /// Whether the element has hover.
  bool _hasHover = false;

  @HostListener('mouseenter')
  void onMouseEnter() {
    _hasHover = true;
  }

  @HostListener('mouseleave')
  void onMouseLeave() {
    _hasHover = false;
  }
}


Validate the output and behavior of the travis shell script

@TestOn('!windows')

import 'package:mono_repo/src/package_config.dart';
import 'package:term_glyph/term_glyph.dart' as glyph;
import 'package:test/test.dart';
import 'package:test_descriptor/test_descriptor.dart' as d;
import 'package:test_process/test_process.dart';

import 'shared.dart';

void main() {
  glyph.ascii = false;

  test('integration', () async {
    await d.file('mono_repo.yaml', 'pretty_ansi: false').create();
    await d.dir('pkg_a', [
      d.file(
        monoPkgFileName,
        _monoPkgContent,
      ),
      d.file('pubspec.yaml', '''
name: pkg_a
      ''')
    ]).create();

    await d.dir('pkg_b', [
      d.file(
        monoPkgFileName,
        _monoPkgContent,
      ),
      d.file('pubspec.yaml', '''
name: pkg_b

dependencies:
  not_a_package_at_all: any
      ''')
    ]).create();

    await d.dir('pkg_c', [
      d.file(
        monoPkgFileName,
        _monoPkgContent,
      ),
      d.file('pubspec.yaml', '''
name: pkg_c
''')
    ]).create();

    testGenerateTravisConfig(
      printMatcher: stringContainsInOrder([
        'package:pkg_a',
        'package:pkg_b',
        'Make sure to mark `tool/travis.sh` as executable.'
      ]),
    );

    //print(File(p.join(d.sandbox, travisShPath)).readAsStringSync());

    final proc = await TestProcess.start(
      '/bin/bash',
      [
        'tool/travis.sh',
        'dartanalyzer',
      ],
      environment: {
        'PKGS': 'pkg_a pkg_b pkg_c',
      },
      workingDirectory: d.sandbox,
    );

    final output = await proc.stdoutStream().join('\n');
    expect(output, r'''
PKG: pkg_a
Resolving dependencies...
No dependencies changed.

PKG: pkg_a; TASK: dartanalyzer
dartanalyzer .
Analyzing pkg_a...

PKG: pkg_b
Resolving dependencies...
pub upgrade failed

PKG: pkg_c
Resolving dependencies...
No dependencies changed.

PKG: pkg_c; TASK: dartanalyzer
dartanalyzer .
Analyzing pkg_c...
''');

    await proc.shouldExit(3);
  });
}

const _monoPkgContent = r'''
dart:
 - stable

stages:
  - some_things:
    - dartanalyzer:
''';


Add tictac test command to run all tests in test dir.

import 'dart:async';
import 'package:tictac/util.dart';

main(){
  var exitCodes = [];
  var files = findTestFiles();
  for(final test in files){
    exitCodes.add(startProcess([test]));
  }
  Future.wait(exitCodes).then((codes){
    for(int i=0; i< codes.length; i++){
      if(codes[i] != 0){
        print('Error running ${files[i]}. Exit code: ${codes[i]}');
      }
    }
  });
}


Add version of fake_thing_test that is expected to passes.

// 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 "dart:_js_helper";
import "package:expect/expect.dart";

// Test that native objects cannot accidentally or maliciously be mistaken for
// Dart objects.
// The difference between fake_thing_test and fake_thing_2_test is the
// presence of a used declared native class.

class Thing {
}

@Native("NT")
class NativeThing {
}

make1() native;
make2() native;
make3() native;

void setup() native r"""
function A() {}
A.prototype.$isThing = true;
make1 = function(){return new A;};
make2 = function(){return {$isThing: true}};
function NT() {}
NT.prototype.$isThing = true;
make3 = function(){return new NT;};
""";

var inscrutable;
main() {
  setup();
  inscrutable = (x) => x;

  var a = new Thing();
  var b = make1();
  var c = make2();
  var d = make3();
  Expect.isTrue(inscrutable(a) is Thing);
  Expect.isFalse(inscrutable(b) is Thing);
  Expect.isFalse(inscrutable(c) is Thing);
  Expect.isFalse(inscrutable(d) is Thing);
}


Add unspecified nullability regression test

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

// Regression test for https://github.com/dart-lang/sdk/issues/46319.

import 'dart:async';

void main() {}

Future<T> fn<T>() {
  // DDC was crashing during compilation when trying to tag the following
  // function expression with a type.
  return hn(() => gn());
}

S gn<S>() {
  throw 'in gn';
}

Future<R> hn<R>(FutureOr<R> Function() foo) {
  throw 'in hn';
}


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

class IconCard extends StatelessWidget {
  final String assetPath;
  final Color backgroundColor;
  final Widget details;

  const IconCard({
    Key key,
    @required this.assetPath,
    this.backgroundColor,
    this.details,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      child: ClipRRect(
        borderRadius: BorderRadius.circular(4),
        child: Stack(
          children: [
            Container(
              height: 100,
              color: backgroundColor,
            ),
            if (backgroundColor != null)
              Positioned.fill(
                child: Container(
                  color: Colors.black.withOpacity(0.6),
                ),
              ),
            Positioned.fill(
              child: Padding(
                padding: const EdgeInsets.all(4),
                child: Row(
                  children: [
                    AspectRatio(
                      aspectRatio: 2 / 3,
                      child: Padding(
                        padding: const EdgeInsets.all(4),
                        child: WebsafeSvg.asset(assetPath),
                      ),
                    ),
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.only(left: 8),
                        child: details,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}


Add logic to remove doc tag comments from the examples code.

/// Returns [code] with filtered out doc tag comment lines.
String removeDocTags(String code) =>
    code.split('\n').where(_isNotDocTagComment).join('\n');

final _docTags = ['#docregion', '#enddocregion', '#docplaster'];
final _commentPrefixes = ['//', '<--'];

/// Returns true if [line] is a not a comment line with a doc tag.
bool _isNotDocTagComment(String line) => !_isDocTagComment(line);

/// Returns true if [line] is a comment line with a doc tag.
bool _isDocTagComment(String line) =>
    _isComment(line) && _docTags.any((String tag) => line.contains(tag));

/// Returns true if [line] starts with any of the prefixes indicating the start
/// of a doc tag comment.
bool _isComment(String line) =>
    _commentPrefixes.any((String prefix) => line.trimLeft().startsWith(prefix));


Add internal iterator node (for visitors)

library inventory;

App app(name, {price: 0}) => new App(name)..netPrice = price;
Mobile mobile([name]) => new Mobile()..name = name;
Tablet tablet([name]) => new Tablet()..name = name;
Laptop laptop([name]) => new Laptop()..name = name;

abstract class Inventory {
  String name;
  Inventory(this.name);

  double netPrice;
  double discountPrice() => netPrice;

  void accept(vistor);
}

class InventoryCollection {
  String name;
  List<Inventory> stuff = [];
  InventoryCollection(this.stuff);

  void accept(visitor) {
    stuff.forEach((thing) { thing.accept(visitor); });
  }
}

abstract class Equipment extends Inventory {
  Equipment(name): super(name);
  int watt;
}

class App extends Inventory {
  App(name): super(name);
  void accept(visitor) { visitor.visitApp(this); }
}

abstract class EquipmentWithApps extends Equipment {
  EquipmentWithApps(name): super(name);
  List<App> apps = [];
}

class Mobile extends EquipmentWithApps {
  Mobile(): super('Mobile Phone');
  double netPrice = 350.00;
  void accept(visitor) {
    apps.forEach((app) { app.accept(visitor); });
    visitor.visitMobile(this);
  }
}

class Tablet extends EquipmentWithApps {
  Tablet(): super('Tablet');
  double netPrice = 400.00;
  void accept(visitor) {
    apps.forEach((app) { app.accept(visitor); });
    visitor.visitTablet(this);
  }
}

class Laptop extends Equipment {
  Laptop(): super('Laptop');
  double netPrice = 1000.00;
  double discountPrice() => netPrice * .9;
  void accept(visitor) { visitor.visitLaptop(this); }
}


Mark fn2's EventListenerNode work for PointerEvent

// 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 'dart:sky' as sky;
import 'package:sky/framework/fn2.dart';

class ContainerApp extends App {
  UINode build() {
    return new EventListenerNode(
      new Rectangle(0xFF00FFFF),
      onPointerDown: _handlePointerDown);
  }

  void _handlePointerDown(sky.PointerEvent event) {
    print("_handlePointerDown");
  }
}

void main() {
  new ContainerApp();
}


Add a script that appends fields with previous results to result data

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

// Add fields with data about the test run and the commit tested, and
// with the result on the last build tested, to the test results file.

import 'dart:convert';
import 'dart:io';

import 'results.dart';

main(List<String> args) async {
  final resultsPath = args[0];
  final priorResultsPath = args[1];
  final flakyPath = args[2];
  final priorFlakyPath = args[3];
  final builderName = args[4];
  final buildNumber = args[5];
  final commitTime = int.parse(args[6]);
  final commitHash = args[7];
  final newResultsPath = args[8];
  // Load the input and the flakiness data if specified.
  final results = await loadResultsMap(resultsPath);
  final priorResults = await loadResultsMap(priorResultsPath);
  final flakes = await loadResultsMap(flakyPath);
  final priorFlakes = await loadResultsMap(priorFlakyPath);

  for (final String key in results.keys) {
    final Map<String, dynamic> result = results[key];
    final Map<String, dynamic> priorResult = priorResults[key];
    final Map<String, dynamic> flaky = flakes[key];
    final Map<String, dynamic> priorFlaky = priorFlakes[key];
    result['commit_hash'] = commitHash;
    result['commit_time'] = commitTime;
    result['build_number'] = buildNumber;
    result['builder_name'] = builderName;
    result['flaky'] = (flaky != null);
    result['previous_flaky'] = (priorFlaky != null);
    if (priorResult != null) {
      result['previous_result'] = priorResult['result'];
      result['previous_commit_hash'] = priorResult['commit_hash'];
      result['previous_commit_time'] = priorResult['commit_time'];
      result['previous_build_number'] = priorResult['build_number'];
    }
    result['changed'] = (result['result'] != result['previous_result'] ||
        result['flaky'] != result['previous_flaky']);
  }
  final sink = new File(newResultsPath).openWrite();
  final sorted = results.keys.toList()..sort();
  for (final key in sorted) {
    sink.writeln(jsonEncode(results[key]));
  }
  sink.close();
}


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

main() {
  test("APIResponse empty schema", () {
    var response = new APIResponse()
        ..statusCode = 200;
    expect(response.asMap()["schema"], isNull);
  });
}


import 'package:version/version.dart';

class MinimumVersion {
  /// Minimum Tautulli version required for Tautulli Remote to function.
  static Version tautulliServer = Version(2, 6, 6);
}


Add script to publish results.json to Cloud Pub/Sub

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

// Post results from Dart continuous integration testers to Cloud Pub/Sub.

import 'dart:convert';
import 'dart:io';

import 'package:args/args.dart';
import 'package:http/http.dart' as http;

void usage(ArgParser parser) {
  print('''
Usage: post_results_to_pubsub.dart [OPTIONS]
Posts Dart CI results as messages to Google cloud pubsub

The options are as follows:

${parser.usage}''');
  exit(1);
}

// Pubsub messages must be < 10MB long. This lower limit lets us add
// a full record at the end.
const messageLengthLimit = 9000000;
const postUrl =
    'https://pubsub.googleapis.com/v1/projects/dart-ci/topics/results:publish';

main(List<String> args) async {
  final parser = new ArgParser();
  parser.addFlag('help', help: 'Show the program usage.', negatable: false);
  parser.addOption('auth_token',
      abbr: 'a',
      help: 'Authorization token with a scope including pubsub publish.');
  parser.addOption('result_file',
      abbr: 'f', help: 'File containing the results to send');

  final options = parser.parse(args);
  if (options['help']) {
    usage(parser);
  }

  var client = http.Client();

  var lines = await File(options['result_file']).readAsLines();
  var token = await File(options['auth_token']).readAsString();
  // Construct pubsub messages.
  var line = 0;
  while (line < lines.length) {
    var message = StringBuffer();
    message.write('[');
    message.write(lines[line++]);
    var messageLines = 1;
    while (message.length < messageLengthLimit && line < lines.length) {
      message.write(',\n');
      message.write(lines[line++]);
      messageLines++;
    }
    message.write(']');
    var base64data = base64Encode(utf8.encode(message.toString()));
    var jsonMessage =
        '{"messages": [{"attributes": {}, "data": "$base64data"}]}';
    var headers = {'Authorization': 'Bearer $token'};
    var response =
        await client.post(postUrl, headers: headers, body: jsonMessage);
    print('Sent pubsub message containing ${messageLines} results');
    print('Status ${response.statusCode}');
    print('Response: ${response.body}');
  }
  client.close();
}