import 'package:flutter/material.dart';

import '../../../../core/widgets/bullet_item.dart';

class ServerSetupInstructions extends StatelessWidget {
  final bool showWarning;
  final double fontSize;

  const ServerSetupInstructions({
    Key key,
    this.showWarning = true,
    this.fontSize = 14,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        if (showWarning)
          const Padding(
            padding: EdgeInsets.only(bottom: 10),
            child: Text(
              'This app is not registered to a Tautulli server.',
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
          ),
        Text(
          'To register with a Tautulli server:',
          style: TextStyle(fontSize: fontSize),
        ),
        const SizedBox(height: 4),
        BulletItem(
          'Open the Tautulli web interface on another device',
          fontSize: fontSize,
        ),
        const SizedBox(height: 4),
        BulletItem(
          'Navigate to Settings > Tautulli Remote App',
          fontSize: fontSize,
        ),
        const SizedBox(height: 4),
        BulletItem(
          'Select \'Register a new device\'',
          fontSize: fontSize,
        ),
        const SizedBox(height: 4),
        BulletItem(
          'Use the button below to register with the server',
          fontSize: fontSize,
        ),
      ],
    );
  }
}

import 'package:flutter/material.dart';

import '../../../../core/widgets/text_list.dart';

class ServerSetupInstructions extends StatelessWidget {
  final bool showWarning;
  final double fontSize;

  const ServerSetupInstructions({
    Key key,
    this.showWarning = true,
    this.fontSize = 14,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        if (showWarning)
          const Padding(
            padding: EdgeInsets.only(bottom: 10),
            child: Text(
              'This app is not registered to a Tautulli server.',
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
          ),
        Text(
          'To register with a Tautulli server:',
          style: TextStyle(fontSize: fontSize),
        ),
        const SizedBox(height: 4),
        const TextList(
          numberedList: true,
          textItems: [
            'Open the Tautulli web interface on another device.',
            'Navigate to Settings > Tautulli Remote App.',
            'Select "Register a new device".',
            'Use the button below to register with the server.'
          ],
          fontSize: 16,
        ),
      ],
    );
  }
}

Update setup instructions to use TextList widget.


import "dart:html";

void init(String script, {void onReady()}) {
  var stopwatch = new Stopwatch();

  if (onReady != null) {
    document.onReadyStateChange.listen((event) {
      if (document.readyState == ReadyState.COMPLETE) {
        stopwatch.stop();
        print("Document Finished Loading in ${stopwatch.elapsedMilliseconds}ms");
        onReady();
      }
    });
  }

  document.querySelector("#view-source").onClick.listen((_) {
    var popup = window.open("view_source.html", "View Source");

    var fetched = false;
    var ready = false;

    String code;

    window.addEventListener("message", (event) {
      if (event.data['command'] == "ready") {
        ready = true;
        if (fetched) {
          popup.postMessage({
            "command": "code",
            "code": code
          }, window.location.href);
        }
      }
    });

    HttpRequest.getString(script).then((c) {
      code = c;
      fetched = true;
      if (ready) {
        popup.postMessage({
          "command": "code",
          "code": code
        }, window.location.href);
      }
    });
  });
}

Map<String, String> get queryString {
  var url = window.location.href;
  if (url.contains("?")) {
    return Uri.splitQueryString(url.substring(url.indexOf('?') + 1));
  } else {
    return {};
  }
}

import "dart:html";

void init(String script, {void onReady()}) {
  var stopwatch = new Stopwatch();

  if (onReady != null) {
    document.onReadyStateChange.listen((event) {
      if (document.readyState == ReadyState.COMPLETE) {
        stopwatch.stop();
        print("Document Finished Loading in ${stopwatch.elapsedMilliseconds}ms");
        onReady();
      }
    });
  }

  document.querySelector("#view-source").onClick.listen((_) {
    var popup = window.open("view_source.html", "View Source");
    String code;

    var fetched = false;
    var ready = false;

    void sendCode() {
      popup.postMessage({
        "command": "code",
        "code": code
      }, window.location.href);
    }

    window.addEventListener("message", (event) {
      if (event.data['command'] == "ready") {
        ready = true;
        if (fetched) {
          sendCode();
        }
      }
    });

    HttpRequest.getString(script).then((c) {
      code = c;
      fetched = true;
      if (ready) {
        sendCode();
      }
    });
  });
}

Map<String, String> get queryString => Uri.parse(window.location.href).queryParameters;

Tweak Query String Stuff for Demos

Tweak Query String Stuff for Demos


import 'dart:html';
import '../DiffMatchPatch.dart';

// Compile with:
// dart2js --out=Speedtest.dart.js Speedtest.dart

void launch(Event e) {
  HtmlElement input1 = document.getElementById('text1');
  HtmlElement input2 = document.getElementById('text2');
  String text1 = input1.text;
  String text2 = input2.text;

  DiffMatchPatch dmp = new DiffMatchPatch();
  dmp.Diff_Timeout = 0.0;

  // No warmup loop since it risks triggering an 'unresponsive script' dialog.
  DateTime date_start = new DateTime.now();
  List<Diff> d = dmp.diff_main(text1, text2, false);
  DateTime date_end = new DateTime.now();

  var ds = dmp.diff_prettyHtml(d);
  document.getElementById('outputdiv').setInnerHtml(
      '$ds<BR>Time: ${date_end.difference(date_start)} (h:mm:ss.mmm)',
      validator: new TrustedNodeValidator());
}

void main() {
  document.getElementById('launch').addEventListener('click', launch);
  document.getElementById('outputdiv').setInnerHtml('');
}

/// A NodeValidator which allows any contents.
/// The default validator strips 'style' attributes.
class TrustedNodeValidator implements NodeValidator {
  bool allowsElement(Element element) => true;
  bool allowsAttribute(Element element, String attributeName, String value)
      => true;
}

import 'dart:html';
import '../DiffMatchPatch.dart';

// Compile with:
// dart2js -O4 --out=Speedtest.dart.js Speedtest.dart

void launch(Event e) {
  HtmlElement input1 = document.getElementById('text1');
  HtmlElement input2 = document.getElementById('text2');
  String text1 = input1.text;
  String text2 = input2.text;

  DiffMatchPatch dmp = new DiffMatchPatch();
  dmp.Diff_Timeout = 0.0;

  // No warmup loop since it risks triggering an 'unresponsive script' dialog.
  DateTime date_start = new DateTime.now();
  List<Diff> d = dmp.diff_main(text1, text2, false);
  DateTime date_end = new DateTime.now();

  var ds = dmp.diff_prettyHtml(d);
  document.getElementById('outputdiv').setInnerHtml(
      '$ds<BR>Time: ${date_end.difference(date_start)} (h:mm:ss.mmm)',
      validator: new TrustedNodeValidator());
}

void main() {
  document.getElementById('launch').addEventListener('click', launch);
  document.getElementById('outputdiv').setInnerHtml('');
}

/// A NodeValidator which allows any contents.
/// The default validator strips 'style' attributes.
class TrustedNodeValidator implements NodeValidator {
  bool allowsElement(Element element) => true;
  bool allowsAttribute(Element element, String attributeName, String value)
      => true;
}

Add -O4 flag that changes speedtest from 31 seconds to 0.9 seconds.


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

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 fold(<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 `UTF8`.
  Future<String> bytesToString([Encoding encoding=UTF8]) =>
      toBytes().then((bytes) => encoding.decode(bytes));

  Stream<String> toStringStream([Encoding encoding=UTF8]) =>
    transform(encoding.decoder);
}

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

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() {
    return fold(new BytesBuilder(), (builder, chunk) => builder..add(chunk))
      .then((builder) => builder.takeBytes());
  }

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

  Stream<String> toStringStream([Encoding encoding=UTF8]) =>
    transform(encoding.decoder);
}

Use BytesBuilder in pkg:http, when accumulating binary data.

This should speed up the library significant.

BUG=
R=sgjesse@google.com

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

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


sub(x, y) => x - y;
add(x, y) => x + y;
div(x, y) => x / y;
mod(x, y) => x % y;
mul(x, y) => x * y;
not(x) => !x;

rpc_proxy(name, arguments) {

}

sub(x, y) => x - y;
add(x, y) => x + y;
div(x, y) => x / y;
mod(x, y) => x % y;
mul(x, y) => x * y;
not(x) => !x;
lt(x, y) => x < y;
gt(x, y) => x > y;
lteq(x, y) => x <= y;
gteq(x, y) => x >= y;
eq(x, y) => x == y;

rpc_proxy(name, arguments) {

}

Add conditional intrinsics to exec

Add conditional intrinsics to exec


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

part of Parts_test_lib;

foo() { return null; }
int bar(int x, int y) { return x + y ; }
List list(int iParam) { return new List.filled(iParam, 0); }
_privateFunc() { return 0; }

typedef String func<B extends bool, S extends String>(B t, [S sParam]);

get value { return _value; }
set value(value) { _value = value; }
var _value;

final int i = -100;
final bool b = false;
final String s = "string";
final List l = const [0,1,2,3];
final Map m = const {'a': 1, 'b': 2};
final String e = "One"  "Two";
final _private = 'private';

class A {
  A() {}
  foo() { return "a.foo()"; }
  var bar = "a.bar";
  static final FOO = "A.FOO";
  get value { return _value; }
  set value(val) { _value = val; }

  var _value;
}

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

part of Parts_test_lib;

foo() { return null; }
int bar(int x, int y) { return x + y ; }
List list(int iParam) { return new List.filled(iParam, 0); }
_privateFunc() { return 0; }

typedef String func<B extends bool, S extends String>(B t, [S sParam]);

get value { return _value; }
set value(value) { _value = value; }
var _value;

final int i = -100;
final bool b = false;
final String s = "string";
final List<int> l = const [0, 1, 2, 3];
final Map<String, int> m = const {'a': 1, 'b': 2};
final String e = "One"  "Two";
final _private = 'private';

class A {
  A() {}
  foo() { return "a.foo()"; }
  var bar = "a.bar";
  static final FOO = "A.FOO";
  get value { return _value; }
  set value(val) { _value = val; }

  var _value;
}

Test library corrected according to the Dart SDK Issue 42393.


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

import '../../../../core/widgets/list_tile_group.dart';
import '../../../../core/widgets/page_body.dart';
import '../../../../translations/locale_keys.g.dart';
import '../widgets/onesignal_data_privacy_list_tile.dart';
import '../widgets/onesignal_data_privacy_text.dart';

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

  static const routeName = '/onesignal_privacy';

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

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(LocaleKeys.onesignal_data_privacy_title).tr(),
      ),
      body: PageBody(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: const [
              OnesignalDataPrivacyText(),
              Gap(8),
              ListTileGroup(
                listTiles: [
                  OneSignalDataPrivacyListTile(),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

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

import '../../../../core/widgets/list_tile_group.dart';
import '../../../../core/widgets/page_body.dart';
import '../../../../translations/locale_keys.g.dart';
import '../widgets/onesignal_data_privacy_list_tile.dart';
import '../widgets/onesignal_data_privacy_text.dart';

class OneSignalDataPrivacyPage extends StatelessWidget {
  final bool showToggle;

  const OneSignalDataPrivacyPage({
    Key? key,
    this.showToggle = true,
  }) : super(key: key);

  static const routeName = '/onesignal_privacy';

  @override
  Widget build(BuildContext context) {
    return OneSignalDataPrivacyView(showToggle: showToggle);
  }
}

class OneSignalDataPrivacyView extends StatelessWidget {
  final bool showToggle;

  const OneSignalDataPrivacyView({
    Key? key,
    required this.showToggle,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(LocaleKeys.onesignal_data_privacy_title).tr(),
      ),
      body: PageBody(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const OnesignalDataPrivacyText(),
              if (showToggle) const Gap(8),
              if (showToggle)
                const ListTileGroup(
                  listTiles: [
                    OneSignalDataPrivacyListTile(),
                  ],
                ),
            ],
          ),
        ),
      ),
    );
  }
}

Allow OneSignal toggle to be hidden.

Allow OneSignal toggle to be hidden.


library distributed_dart;
import 'dart:io';
import 'dart:async';
import 'dart:isolate';
import 'dart:json';
import 'dart:typeddata';

part 'src/dart_import/util/characters.dart';
//part 'src/dart_import/dart_code.dart';
part 'src/dart_import/scanner.dart';

part 'src/network/network.dart';

// logging mechanism instad of print

/**
 * Set to true for enabling debug output from the distributed_dart library.
 * Default value is false.
 */
bool logging = false;

_log(var msg) => logging ? stdout.write("DIST_DART, log: ${msg}\n") : "";
_err(var msg) => logging ? stderr.write("DIST_DART, err: ${msg}\n") : "";

library distributed_dart;
import 'dart:io';
import 'dart:async';
import 'dart:isolate';
import 'dart:json';
import 'dart:typeddata';

part 'src/dart_import/util/characters.dart';
//part 'src/dart_import/dart_code.dart';
part 'src/dart_import/scanner.dart';

part 'src/network/network.dart';

// logging mechanism instad of print

/**
 * Set to true for enabling debug output from the distributed_dart library.
 * Default value is false.
 */
bool logging = false;

_log(var msg) => logging ? stdout.writeln("DIST_DART, log: ${msg}") : "";
_err(var msg) => logging ? stderr.writeln("DIST_DART, err: ${msg}") : "";

Use writeln instead of manual newline insert.


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

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

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


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

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

Rearrange arguments in DelegatingComponent constructor


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

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

Fix for MatchState acting weird

Fix for MatchState acting weird


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

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

Make the Progress Bar auto-resize.

Make the Progress Bar auto-resize.


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

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

Add function to mask a sensitive string.


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

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

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


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

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

Change icon for OneSignal Data Privacy.

Change icon for OneSignal Data Privacy.


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

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

Add donate button to Changelog.

Add donate button to Changelog.


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

library pub_tests;

import 'package:scheduled_test/scheduled_test.dart';

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

main() {
  initConfig();

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

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

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

library pub_tests;

import 'package:scheduled_test/scheduled_test.dart';

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

main() {
  initConfig();

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

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

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

R=ajohnsen@google.com

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

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


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

library byte_stream;

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

import 'utils.dart';

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

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

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

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

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

library byte_stream;

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

import 'utils.dart';

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

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

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

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

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

Use the dart:async Stream API thoroughly in Pub.

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Support setting <base href> even when set dynamically


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

import 'component_factory.dart' show ComponentFactory;

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

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

import 'component_factory.dart' show ComponentFactory;

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

Drop <T> type in typeToFactory.

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

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

PiperOrigin-RevId: 190963426


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

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

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

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

Test current situation with mirror

Test current situation with mirror


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

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

import 'dart:html';

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

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

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

import 'dart:html';

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

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

Use unittest to avoid timeouts on Dartium.

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

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


import 'package:force/force_serverside.dart';

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

  fs.setupConsoleLog();

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

  fs.start();
}

import 'package:force/force_serverside.dart';

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

  fs.setupConsoleLog();

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

  fs.start();
}

Set build path as target

Set build path as target


import 'dart:typed_data';

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

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

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

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

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

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

import 'dart:typed_data';

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

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

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

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

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

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

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

Add non-ascii ArchiveFile name to test

Add non-ascii ArchiveFile name to test


part of alpha.async;

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

  var elements = [];

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

  return completer.future;
}

typedef dynamic AsynchronousFunction();

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

Add an Asynchronous Function Execution

Add an Asynchronous Function Execution


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

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

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

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

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

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

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

  AppComponent() {
    loadData();
  }

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

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

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

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

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

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

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

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

Load questions as objects from Aqueduct to Angular.


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Migrate VM tests to Web

Migrate VM tests to Web

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

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

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


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

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

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

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

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

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

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

Add a basic popup menu widget

Add a basic popup menu widget

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

R=eseidel@chromium.org

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


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

import 'package:petitparser/petitparser.dart';

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

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

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

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

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

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

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

Use the expression builder in the example.


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

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

Add test for Class initialisation.

Add test for Class initialisation.


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

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

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

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

  factory A() = B;
}

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

class C = Object with A;

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

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

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

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

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

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

  factory A() = B;
}

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

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

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

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

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

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


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

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

class HtmlContextIntegrationTest = IntegrationTest with HtmlContext;

main() {
  MockRunner runner;

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

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

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

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

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

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

class HtmlContextIntegrationTest = IntegrationTest with HtmlContext;

main() {
  MockRunner runner;

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

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

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

Clean up context test given new async test mocking


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

/// The colorful library.
library colorful;

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

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

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

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

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

class SoftPalette extends ColorPalette {

}

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

/// The colorful library.
library colorful;

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

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

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

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

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

class SoftPalette extends ColorPalette {

}

Remove keyword this from constructor

Remove keyword this from constructor


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

import "package:protobuf/protobuf.dart";

// @import@

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

};

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

};

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

import "package:protobuf/protobuf.dart";

// @import@

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

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

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

class _KnownTypesPart {

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

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

Make generated Dart type registry more useful


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

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

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

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

Send method changed to add in WebSocket

Send method changed to add in WebSocket


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

class PrivateFactoryResolutionTest {

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

main() {
  PrivateFactoryResolutionNegativeTest.testMain();
}

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

class PrivateFactoryResolutionNegativeTest {

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

main() {
  PrivateFactoryResolutionNegativeTest.testMain();
}

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

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

R=floitsch@google.com
BUG=
TEST=

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

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


import 'dart:async';

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

import 'processor.dart';

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

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

  StylesheetCompiler(this._flags);

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

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

import 'dart:async';

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

import 'processor.dart';

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

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

  const StylesheetCompiler(this._flags);

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

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

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

PiperOrigin-RevId: 177529991


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

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

void main () {

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

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

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

}

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

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

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

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

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

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

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

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

Refactor customer merge click handler to be its own method


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

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

library http_request_data_reader;

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

class HTTPRequestDataReader implements LocaleDataReader {

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

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

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

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

library http_request_data_reader;

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

class HTTPRequestDataReader implements LocaleDataReader {

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

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

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

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

    return completer.future;
  }
}

Add a timeout on HttpRequestDataReader

Add a timeout on HttpRequestDataReader

BUG=
R=efortuna@google.com

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

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


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

library toml.example.string;

import 'package:toml/toml.dart';

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

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

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

library toml.example.string;

import 'package:toml/decoder.dart';

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

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

Use new `decoder` library in examples.

Use new `decoder` library in examples.


library sprites;

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

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

library sprites;

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

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

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

TBR=viktorl@google.com

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


part of monadart;

class ResourceRequest {

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

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

  ResourceRequest(HttpRequest req) : request = req {

  }

}

part of monadart;

class ResourceRequest {

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

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

  ResourceRequest(this.request) {

  }

}

Fix to ResourceRequest, cleaned up init

Fix to ResourceRequest, cleaned up init


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

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

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

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

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

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

Sort packages before listing them.

Sort packages before listing them.

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

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


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

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

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

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

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

  final generatePermutations = makeBoolSetting('generatePermutations');

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

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

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

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

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

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

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

  final generatePermutations = makeBoolSetting('generatePermutations');

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

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

Introduce default locale setting for permutations transformer


part of streamy.runtime;

final _observableJsonCodec = new JsonCodec.withReviver(_observableReviver);

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

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

part of streamy.runtime;

final _observableJsonCodec = new JsonCodec.withReviver(_observableReviver);

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

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

Remove unnecessary observable wrapping logic


library sample_api;

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

import 'package:rpc/rpc.dart';

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

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

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

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

library sample_api;

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

import 'package:rpc/rpc.dart';

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

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

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

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

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

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

Add hello api method without async

Add hello api method without async


library parser_tests;

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

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

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

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

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

library parser_tests;

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

typedef dynamic InputChecker<T>(T value);

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

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

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

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

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

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

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

        return true;
      }
    };

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

Add Test for Message IRC Parser

Add Test for Message IRC Parser


import 'dart:async';

import 'dart_doc_syncer.dart' as syncer;

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

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

import 'dart:async';

import 'dart_doc_syncer.dart' as syncer;

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

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

Use ssh for github repositories.

Use ssh for github repositories.


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

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

  final NoticesModel notice;

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

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

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

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

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

  final NoticesModel notice;

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

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

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

Add description to Notices banner

Add description to Notices banner


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

/// The colorful library.
library colorful;

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

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

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

/// The colorful library.
library colorful;

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

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

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

Add getter methods for r, g, b;

Add getter methods for r, g, b;


library storageservice;

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

final String STORAGE_KEY = 'ddays';

List tasklist = [];

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

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

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

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

library storageservice;

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

final String STORAGE_KEY = 'ddays';

List tasklist = [];

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

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

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

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

Use tasklist global in loadFromStorage function.