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

part of quiver.testing;

/**
 * Asserts that the current runtime has checked mode enabled.
 */
void assertCheckedMode() {
  if (_isCheckedMode == null) _isCheckedMode = _checkForCheckedMode();

  assert (_isCheckedMode);
}

bool _isCheckedMode = null;

bool _checkForCheckedMode() {
  Object sentinal = new Object();
  try {
    String string = 1;
    throw sentinal;
  } catch (e) {
    if (e == sentinal) return false;
  }
  return true;
}

Throw StateError explicitly instead of using assert. Document thrown exception.

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

part of quiver.testing;

/**
 * Asserts that the current runtime has checked mode enabled.
 *
 * Otherwise, throws [StateError}.
 */
void assertCheckedMode() {
  if (_isCheckedMode == null) _isCheckedMode = _checkForCheckedMode();

  if (!_isCheckedMode) {
    throw new StateError('Not in checked mode.');
  }
}

bool _isCheckedMode = null;

bool _checkForCheckedMode() {
  Object sentinal = new Object();
  try {
    String string = 1;
    throw sentinal;
  } catch (e) {
    if (e == sentinal) return false;
  }
  return true;
}


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

part of vdom.internal;

abstract class ComponentBase {
  /// Fast check to detect if the Component is changed.
  bool isChanged(ComponentBase other);

  /// Build Component subtree.
  Element build();
}

abstract class Component extends Node with ComponentBase {
  Element _element;

  Component(Object key) : super(key);

  ElementPatch diff(Component other) {
    if (isChanged(other)) {
      if (other._element == null) {
        other._element = other.build();
      }
      return _element.diff(other._element);
    }
    return null;
  }

  html.Node render() {
    assert(_element != null);

    return _element.render();
  }
}

class DelegatingComponent extends Component {
  final ComponentBase _component;

  DelegatingComponent(this._component, Object key) : super(key);

  bool isChanged(ComponentBase other) {
    return _component.isChanged(other);
  }

  Element build() {
    return _component.build();
  }
}

Rearrange arguments in DelegatingComponent constructor

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

part of vdom.internal;

abstract class ComponentBase {
  /// Fast check to detect if the Component is changed.
  bool isChanged(ComponentBase other);

  /// Build Component subtree.
  Element build();
}

abstract class Component extends Node with ComponentBase {
  Element _element;

  Component(Object key) : super(key);

  ElementPatch diff(Component other) {
    if (isChanged(other)) {
      if (other._element == null) {
        other._element = other.build();
      }
      return _element.diff(other._element);
    }
    return null;
  }

  html.Node render() {
    assert(_element != null);

    return _element.render();
  }
}

class DelegatingComponent extends Component {
  final ComponentBase _component;

  DelegatingComponent(Object key, this._component) : super(key);

  bool isChanged(ComponentBase other) {
    return _component.isChanged(other);
  }

  Element build() {
    return _component.build();
  }
}


part of dart_commons;

/**
 * Checks a [value] against a [Matcher] and throws a [PreconditionError] value is not valid.
 *
 * The default message in the [PreconditionError] details the nature of the validation failure,
 * but can be optionally overridden with an custom [message] if desired.
 */
checkThat(value, Matcher matcher, [String message]) {
  var matchState = new MatchState();
  if (!matcher.matches(value, matchState)) {

    String failureMsg = message;
    if (failureMsg == null) {
      failureMsg = _getDefaultMessageForMismatch(value, matcher, matchState);
    }
    throw new PreconditionError(failureMsg);
  }
  return value;
}

String _getDefaultMessageForMismatch(value, Matcher matcher, matchState) {
  var description = new StringDescription();
  description.add('Precondition Failed!\nExpected: ').addDescriptionOf(matcher).
  add('\n     but: ');
  matcher.describeMismatch(value, description, matchState, false);
  description.add('.\n');
  return description.toString();
}

class PreconditionError implements Error {
  final String message;
  PreconditionError(this.message);
  String toString() => message;
}

Fix for MatchState acting weird

part of dart_commons;

/**
 * Checks a [value] against a [Matcher] and throws a [PreconditionError] value is not valid.
 *
 * The default message in the [PreconditionError] details the nature of the validation failure,
 * but can be optionally overridden with an custom [message] if desired.
 */
checkThat(value, Matcher matcher, [String message]) {
  var matchState = new Map();
  if (!matcher.matches(value, matchState)) {

    String failureMsg = message;
    if (failureMsg == null) {
      failureMsg = _getDefaultMessageForMismatch(value, matcher, matchState);
    }
    throw new PreconditionError(failureMsg);
  }
  return value;
}

String _getDefaultMessageForMismatch(value, Matcher matcher, matchState) {
  var description = new StringDescription();
  description.add('Precondition Failed!\nExpected: ').addDescriptionOf(matcher).
  add('\n     but: ');
  matcher.describeMismatch(value, description, matchState, false);
  description.add('.\n');
  return description.toString();
}

class PreconditionError implements Error {
  final String message;
  PreconditionError(this.message);
  String toString() => message;
}


part of devtools.util;

class ProgressBar {
  final int width;
  final int complete;

  int current = 0;

  ProgressBar({int width, this.complete: 100}) : this.width = width != null ? width : stdout.terminalColumns;

  void update(int progress) {
    if (progress == current) {
      return;
    }

    current = progress;

    if (current == 0) {
      stdout.write("");
    }

    var ratio = progress / complete;
    var percent = (ratio * 100).toInt();

    var digits = percent.toString().length;

    var w = width - digits - 4;

    var count = (ratio * w).toInt();
    var before = "${percent}% [";
    var after = "]";

    var out = new StringBuffer(before);

    for (int x = 0; x < count -1; x++)
      out.write("=");

    out.write(">");

    for (int x = count; x < w; x++)
      out.write(" ");

    out.write(after);

    Console.overwriteLine(out.toString());
  }
}

Make the Progress Bar auto-resize.

part of devtools.util;

class ProgressBar {
  final int complete;

  int current = 0;

  ProgressBar({this.complete: 100});

  void update(int progress) {
    if (progress == current) {
      return;
    }

    current = progress;

    if (current == 0) {
      stdout.write("");
    }

    var ratio = progress / complete;
    var percent = (ratio * 100).toInt();

    var digits = percent.toString().length;

    var w = stdout.terminalColumns - digits - 4;

    var count = (ratio * w).toInt();
    var before = "${percent}% [";
    var after = "]";

    var out = new StringBuffer(before);

    for (int x = 0; x < count -1; x++)
      out.write("=");

    out.write(">");

    for (int x = count; x < w; x++)
      out.write(" ");

    out.write(after);

    Console.overwriteLine(out.toString());
  }
}


/// Helper functions to manipulate string.
class StringFormatHelper {
  /// Capitalizes the first letter of a string.
  ///
  /// Throws an [ArgumentError] if string is null.
  static String capitalize(String string) {
    if (string == null) {
      throw ArgumentError("string: $string");
    }

    if (string.isEmpty) {
      return string;
    }

    return string[0].toUpperCase() + string.substring(1);
  }
}

Add function to mask a sensitive string.

/// Helper functions to manipulate string.
class StringFormatHelper {
  /// Capitalizes the first letter of a string.
  ///
  /// Throws an [ArgumentError] if string is null.
  static String capitalize(String string) {
    if (string == null) {
      throw ArgumentError("string: $string");
    }

    if (string.isEmpty) {
      return string;
    }

    return string[0].toUpperCase() + string.substring(1);
  }

  /// Replaces all but the last 2 letters of [string]
  /// with the same number of `*`.
  static String maskSensitiveInfo(String string) {
    final int maskLength = string.length - 2;
    String maskString = '';

    for (int i = maskLength; i > 0; i--) {
      maskString += '*';
    }

    return string.replaceRange(0, maskLength, maskString);
  }
}


import 'dart:io';
import 'dart:json' as JSON;

main() {
  var port = int.parse(Platform.environment['PORT']);
  HttpServer.bind('0.0.0.0', port).then((HttpServer server) {
    print('Server started on port: ${port}');
    server.listen((HttpRequest request) {
      var resp = JSON.stringify({
        'Dart on Heroku': true,
        'Buildpack URL': 'https://github.com/igrigorik/heroku-buildpack-dart',
        'Environment': Platform.environment}
      );
      request.response..headers.set(HttpHeaders.CONTENT_TYPE, 'application/json')
                      ..write(resp)
                      ..close();
    });
  });
}

Test the full continuous build chain (Drone.io + Heroku)

import 'dart:io';
import 'dart:json' as JSON;

main() {
  var port = int.parse(Platform.environment['PORT']);
  HttpServer.bind('0.0.0.0', port).then((HttpServer server) {
    print('Server started on port: ${port}');
    server.listen((HttpRequest request) {
      var resp = JSON.stringify({
        'Name': 'Eric Taix',
        'Environment': Platform.environment}
      );
      request.response..headers.set(HttpHeaders.CONTENT_TYPE, 'application/json')
                      ..write(resp)
                      ..close();
    });
  });
}


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

import '../../../../core/package_information/package_information.dart';
import '../../../../core/widgets/list_tile_group.dart';
import 'settings_list_tile.dart';

class MoreGroup extends StatelessWidget {
  const MoreGroup({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListTileGroup(
      heading: 'More',
      settingsListTiles: [
        SettingsListTile(
          leading: const FaIcon(FontAwesomeIcons.userSecret),
          title: 'OneSignal Data Privacy',
          onTap: () {},
        ),
        SettingsListTile(
          leading: const FaIcon(FontAwesomeIcons.clipboardList),
          title: 'Changelog',
          onTap: () {
            Navigator.of(context).pushNamed('/changelog');
          },
        ),
        SettingsListTile(
          leading: const FaIcon(FontAwesomeIcons.globe),
          title: 'Help Translate',
          onTap: () {
            Navigator.of(context).pushNamed('/help_translate');
          },
        ),
        SettingsListTile(
          leading: const FaIcon(FontAwesomeIcons.infoCircle),
          title: 'About',
          onTap: () async {
            showAboutDialog(
              context: context,
              applicationIcon: SizedBox(
                height: 50,
                child: Image.asset('assets/logos/logo.png'),
              ),
              applicationName: 'Tautulli Remote',
              applicationVersion: await PackageInformationImpl().version,
              applicationLegalese:
                  'Licensed under the GNU General Public License v3.0',
            );
          },
        ),
      ],
    );
  }
}

Change icon for OneSignal Data Privacy.

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

import '../../../../core/package_information/package_information.dart';
import '../../../../core/widgets/list_tile_group.dart';
import 'settings_list_tile.dart';

class MoreGroup extends StatelessWidget {
  const MoreGroup({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListTileGroup(
      heading: 'More',
      settingsListTiles: [
        SettingsListTile(
          leading: const FaIcon(FontAwesomeIcons.shieldAlt),
          title: 'OneSignal Data Privacy',
          onTap: () {},
        ),
        SettingsListTile(
          leading: const FaIcon(FontAwesomeIcons.clipboardList),
          title: 'Changelog',
          onTap: () {
            Navigator.of(context).pushNamed('/changelog');
          },
        ),
        SettingsListTile(
          leading: const FaIcon(FontAwesomeIcons.globe),
          title: 'Help Translate',
          onTap: () {
            Navigator.of(context).pushNamed('/help_translate');
          },
        ),
        SettingsListTile(
          leading: const FaIcon(FontAwesomeIcons.infoCircle),
          title: 'About',
          onTap: () async {
            showAboutDialog(
              context: context,
              applicationIcon: SizedBox(
                height: 50,
                child: Image.asset('assets/logos/logo.png'),
              ),
              applicationName: 'Tautulli Remote',
              applicationVersion: await PackageInformationImpl().version,
              applicationLegalese:
                  'Licensed under the GNU General Public License v3.0',
            );
          },
        ),
      ],
    );
  }
}


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

import '../../../../translations/locale_keys.g.dart';
import '../../data/datasource/changelog_data_source.dart';
import '../widgets/changelog_item.dart';

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

  static const routeName = '/changelog';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).backgroundColor,
      appBar: AppBar(
        title: const Text(LocaleKeys.changelog_page_title).tr(),
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.only(top: 8),
          child: Column(
            children: changelog['data'].map<Widget>((release) {
              return ChangelogItem(
                release: release,
              );
            }).toList(),
          ),
        ),
      ),
    );
  }
}

Add donate button to Changelog.

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

import '../../../../translations/locale_keys.g.dart';
import '../../../donate/presentation/pages/donate_page.dart';
import '../../data/datasource/changelog_data_source.dart';
import '../widgets/changelog_item.dart';

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

  static const routeName = '/changelog';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).backgroundColor,
      appBar: AppBar(
        title: const Text(LocaleKeys.changelog_page_title).tr(),
        actions: [
          TextButton.icon(
            onPressed: () {
              Navigator.of(context).pushNamed(DonatePage.routeName);
            },
            icon: const FaIcon(
              FontAwesomeIcons.solidHeart,
              color: Colors.red,
              size: 18,
            ),
            label: Text(
              LocaleKeys.donate_page_title.tr(),
            ),
          ),
        ],
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.only(top: 8),
          child: Column(
            children: changelog['data'].map<Widget>((release) {
              return ChangelogItem(
                release: release,
              );
            }).toList(),
          ),
        ),
      ),
    );
  }
}


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

library pub_tests;

import 'package:scheduled_test/scheduled_test.dart';

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

main() {
  initConfig();

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

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

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

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

library pub_tests;

import 'package:scheduled_test/scheduled_test.dart';

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

main() {
  initConfig();

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

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


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

library byte_stream;

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

import 'utils.dart';

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

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

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

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

Use the dart:async Stream API thoroughly in Pub.

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

library byte_stream;

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

import 'utils.dart';

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

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

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

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

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


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

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

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

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

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

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

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

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

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

Support setting <base href> even when set dynamically

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

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

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

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

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

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

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

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

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

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

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


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

import 'component_factory.dart' show ComponentFactory;

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

Drop <T> type in typeToFactory.

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

import 'component_factory.dart' show ComponentFactory;

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


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

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

Test current situation with mirror

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

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


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

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

import 'dart:html';

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

Use unittest to avoid timeouts on Dartium.

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

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

import 'dart:html';

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

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


import 'package:force/force_serverside.dart';

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

  fs.setupConsoleLog();

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

  fs.start();
}

Set build path as target

import 'package:force/force_serverside.dart';

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

  fs.setupConsoleLog();

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

  fs.start();
}


import 'dart:typed_data';

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

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

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

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

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

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

Add non-ascii ArchiveFile name to test

import 'dart:typed_data';

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

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

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

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

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

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

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


part of alpha.async;

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

  var elements = [];

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

  return completer.future;
}

Add an Asynchronous Function Execution

part of alpha.async;

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

  var elements = [];

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

  return completer.future;
}

typedef dynamic AsynchronousFunction();

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


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

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

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

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

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

Load questions as objects from Aqueduct to Angular.

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

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

  AppComponent() {
    loadData();
  }

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

Migrate VM tests to Web

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

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

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

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

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

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

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

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


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

import '../../framework/fn.dart';
import '../../framework/components/button.dart';

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

Add a basic popup menu widget

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

import '../../framework/fn.dart';
import '../../framework/components/button.dart';
import '../../framework/components/popup_menu.dart';
import '../../framework/components/popup_menu_item.dart';

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

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


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

import 'package:petitparser/petitparser.dart';

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

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

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

Use the expression builder in the example.

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

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

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

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


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

Add test for Class initialisation.

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

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


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

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

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

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

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

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

  factory A() = B;
}

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

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

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

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


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

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

class HtmlContextIntegrationTest = IntegrationTest with HtmlContext;

main() {
  MockRunner runner;

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

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

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

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

Clean up context test given new async test mocking

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

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

class HtmlContextIntegrationTest = IntegrationTest with HtmlContext;

main() {
  MockRunner runner;

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

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

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


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

/// The colorful library.
library colorful;

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

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

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

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

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

class SoftPalette extends ColorPalette {

}

Remove keyword this from constructor

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

/// The colorful library.
library colorful;

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

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

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

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

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

class SoftPalette extends ColorPalette {

}


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

import "package:protobuf/protobuf.dart";

// @import@

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

};

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

};

Make generated Dart type registry more useful

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

import "package:protobuf/protobuf.dart";

// @import@

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

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

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

class _KnownTypesPart {

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

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


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

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

Send method changed to add in WebSocket

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

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


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

class PrivateFactoryResolutionTest {

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

main() {
  PrivateFactoryResolutionNegativeTest.testMain();
}

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

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

class PrivateFactoryResolutionNegativeTest {

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

main() {
  PrivateFactoryResolutionNegativeTest.testMain();
}


import 'dart:async';

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

import 'processor.dart';

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

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

  StylesheetCompiler(this._flags);

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

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

Use trailing commas for DSLs, and make something const.

import 'dart:async';

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

import 'processor.dart';

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

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

  const StylesheetCompiler(this._flags);

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

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


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

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

void main () {

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

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

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

}

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

Refactor customer merge click handler to be its own method

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

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

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

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

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

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

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


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

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

library http_request_data_reader;

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

class HTTPRequestDataReader implements LocaleDataReader {

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

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

Add a timeout on HttpRequestDataReader

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

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

library http_request_data_reader;

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

class HTTPRequestDataReader implements LocaleDataReader {

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

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

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

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

    return completer.future;
  }
}


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

library toml.example.string;

import 'package:toml/toml.dart';

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

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

Use new `decoder` library in examples.

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

library toml.example.string;

import 'package:toml/decoder.dart';

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

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


library sprites;

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

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

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

library sprites;

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

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


part of monadart;

class ResourceRequest {

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

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

  ResourceRequest(HttpRequest req) : request = req {

  }

}

Fix to ResourceRequest, cleaned up init

part of monadart;

class ResourceRequest {

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

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

  ResourceRequest(this.request) {

  }

}


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

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

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

Sort packages before listing them.

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

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

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


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

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

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

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

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

  final generatePermutations = makeBoolSetting('generatePermutations');

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

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

Introduce default locale setting for permutations transformer

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

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

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

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

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

  final generatePermutations = makeBoolSetting('generatePermutations');

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

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


part of streamy.runtime;

final _observableJsonCodec = new JsonCodec.withReviver(_observableReviver);

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

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

Remove unnecessary observable wrapping logic

part of streamy.runtime;

final _observableJsonCodec = new JsonCodec.withReviver(_observableReviver);

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

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


library sample_api;

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

import 'package:rpc/rpc.dart';

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

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

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

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

Add hello api method without async

library sample_api;

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

import 'package:rpc/rpc.dart';

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

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

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

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

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

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


library parser_tests;

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

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

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

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

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

Add Test for Message IRC Parser

library parser_tests;

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

typedef dynamic InputChecker<T>(T value);

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

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

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

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

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

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

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

        return true;
      }
    };

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


import 'dart:async';

import 'dart_doc_syncer.dart' as syncer;

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

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

Use ssh for github repositories.

import 'dart:async';

import 'dart_doc_syncer.dart' as syncer;

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

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


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

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

  final NoticesModel notice;

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

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

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

Add description to Notices banner

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

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

  final NoticesModel notice;

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

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

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


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

/// The colorful library.
library colorful;

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

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

Add getter methods for r, g, b;

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

/// The colorful library.
library colorful;

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

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

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


library storageservice;

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

final String STORAGE_KEY = 'ddays';

List tasklist = [];

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

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

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

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

Use tasklist global in loadFromStorage function.

library storageservice;

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

final String STORAGE_KEY = 'ddays';

List tasklist = [];

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

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

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

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


library textmarker;

import 'dart:html';

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

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

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

Use initialised start and endpositions.

library textmarker;

import 'dart:html';

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

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

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


library test_dump_render_tree;

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

void main() {
  testRun();
}

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

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

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

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

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

  expect(future, completes);
}

Update unit test configuration setting.

library test_dump_render_tree;

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

void main() {
  testRun();
}

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

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

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

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

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

  expect(future, completes);
}


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

import 'package:angular/angular.dart';
import 'package:angular_components/model/ui/display_name.dart';
import 'package:angular_components/model/ui/has_renderer.dart';

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

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

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

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

import 'package:angular/angular.dart';
import 'package:angular_components/model/ui/display_name.dart';
import 'package:angular_components/model/ui/has_renderer.dart';

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

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


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

import 'build_utils.dart';

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

    DateTime currentValue;

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

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

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

  });
}

Test year selection for date picker

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

import 'build_utils.dart';

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

    DateTime currentValue;

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

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

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


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

import "package:expect/expect.dart";

var cyclicStatic = cyclicStatic + 1;

cyclicInitialization() {
  return cyclicStatic;
}

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

Make cyclic error init more complicated to avoid static warnings.

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

import "package:expect/expect.dart";

class A {
  get foo => cyclicStatic;
}

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

cyclicInitialization() {
  return cyclicStatic;
}

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


part of discord;

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

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

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

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

Support for discord's latest feature

part of discord;

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

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

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

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

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

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

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

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


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

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

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

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

Remove dependency on dart:mirrors from Streamy runtime.

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

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

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

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


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

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

library engine.utilities.general;

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

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

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

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

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

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

Correct or pause previous TimeCounters.

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

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

library engine.utilities.general;

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

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

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

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

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

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


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

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

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

Fix expected and actual ordering

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

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

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


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

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

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

main() {
  groupSep = ' | ';

  defineTests();
}

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

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

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

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

main() {
  groupSep = ' | ';

  defineTests();
}


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

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

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

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

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

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

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

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

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

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

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

Test that isInQuery writes inner tables

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

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

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

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

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

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

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

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

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

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

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

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


import 'package:flutter/material.dart';

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

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

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

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

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

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

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

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

import 'package:flutter/material.dart';

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

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

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

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

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

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

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