library sample_api;

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

import 'package:rpc/rpc.dart';

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

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

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

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

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

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

library 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: 'hello1/{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: 'hello2/{name}')
  Future<StringResponse> helloAsync(String name) async {
    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: 'hello3/{name}')
  Future<StringResponse> helloAsyncWithCompleter(String name) {
    var completer = new Completer();

    if (names.contains(name)) {
      completer.complete(new StringResponse('Hello, $name'));
    } else {
      throw new RpcError(HttpStatus.NOT_FOUND, 'Name not found', '$name doesn\'t exists');
    }

    return completer.future;
  }

  @ApiMethod(method: 'GET', path: 'hello4/{name}')
  Future<StringResponse> helloAsyncWithCompleterAndDelay(String name) async {
    var completer = new Completer();

    new Future.delayed(const Duration(seconds: 1), () {
      if (names.contains(name)) {
        completer.complete(new StringResponse('Hello, $name'));
      } else {
        completer.completeError(new RpcError(HttpStatus.NOT_FOUND, 'Name not found', '$name doesn\'t exists'));
      }
    });

    return completer.future;
  }
}

Add hello api method with completer and delay


import 'dart:io';
import 'dart:convert';
import 'package:source_maps/source_maps.dart';

main(List<String> args) {
  if (args.length < 2) {
    print('usage: read.dart <source-map-file> <name>');
    exit(1);
  }
  var sourcemapFile = new File.fromUri(Uri.base.resolve(args[0]));
  if (!sourcemapFile.existsSync()) {
    print('no source-map-file in ${args[0]}');
    exit(1);
  }
  var name = args[1];
  var json = jsonDecode(sourcemapFile.readAsStringSync());
  SingleMapping mapping = parseJson(json);
  var extensions = json['x_org_dartlang_dart2js'];
  if (extensions == null) {
    print('source-map file has no dart2js extensions');
    exit(1);
  }
  var minifiedNames = extensions['minified_names'];
  if (minifiedNames == null) {
    print('source-map file has no minified names in the dart2js extensions');
    exit(1);
  }
  var gid = minifiedNames['global'][name];
  if (gid != null) print('$name => ${mapping.names[gid]} (a global name)');
  var iid = minifiedNames['instance'][name];
  if (iid != null) print('$name => ${mapping.names[iid]} (an instance name)');
  if (gid == null && iid == null) print('Name \'$name\' not found.');
}

import 'dart:io';
import 'dart:convert';
import 'package:source_maps/source_maps.dart';
import 'package:dart2js_tools/src/dart2js_mapping.dart';

main(List<String> args) {
  if (args.length < 2) {
    print('usage: read.dart <source-map-file> <name>');
    exit(1);
  }
  var name = args[1];

  var sourcemapFile = new File.fromUri(Uri.base.resolve(args[0]));
  if (!sourcemapFile.existsSync()) {
    print('Error: no such file: $sourcemapFile');
    exit(1);
  }
  var json = jsonDecode(sourcemapFile.readAsStringSync());
  Dart2jsMapping mapping = Dart2jsMapping(parseJson(json), json);
  var global = mapping.globalNames[name];
  if (global != null) print('$name => $global (a global name)');
  var instance = mapping.instanceNames[name];
  if (instance != null) print('$name => $instance (an instance name)');
  if (global == null && instance == null) print('Name \'$name\' not found.');
}

Update lookup-name tool to use the dart2js_mapping implementation.

Note: the current implementation broke when we changed the encoding.
Change-Id: I48d9e5fedad3f3be85fc1e73dd5dd091bb7278b0
Reviewed-on: https://dart-review.googlesource.com/c/84881
Commit-Queue: Sigmund Cherem <beaea8fd7d2a56555046ba4f362c8a93e3938576@google.com>
Commit-Queue: Stephen Adams <60cb5b73b7e0cb7dcda53302da4fab6ecfc7fa8b@google.com>
Auto-Submit: Sigmund Cherem <beaea8fd7d2a56555046ba4f362c8a93e3938576@google.com>
Reviewed-by: Stephen Adams <60cb5b73b7e0cb7dcda53302da4fab6ecfc7fa8b@google.com>


import 'dart:io' as io;
import 'package:flutter_tools/src/device.dart';
import 'package:flutter_tools/src/doctor.dart';
import 'package:flutter_tools/src/base/context.dart';
import 'package:flutter_tools/src/base/logger.dart';

// import 'package:flutter_tools/src/commands/run.dart';
// import 'package:flutter_tools/src/commands/install.dart';

import '../lib/run_command.dart';

main(List<String> args) async {

  // Initialize globals.
  context[Logger] = new StdoutLogger();
  context[DeviceManager] = new DeviceManager();
  Doctor.initGlobal();

  // DeviceManager dm = context[DeviceManager];
  // var devices = await dm.getDevices();

  // print(devices);

  // print ("Devices enum complete");

  print ("About to create Run");

  RunCommand runCmd = new RunCommand();
  runCmd.run();

// InstallCommand installCommand = new InstallCommand();
// installCommand.run();
  //
  // RunCommand runCommand = new RunCommand();
  // runCommand.argResults = new
  // runCommand.argResults['hot'] = true;
  // runCommand.run();

}

import 'dart:io' as io;
import 'package:flutter_tools/src/android/android_sdk.dart';
import 'package:flutter_tools/src/device.dart';
import 'package:flutter_tools/src/doctor.dart';
import 'package:flutter_tools/src/base/context.dart';
import 'package:flutter_tools/src/base/logger.dart';

// import 'package:flutter_tools/src/commands/run.dart';
// import 'package:flutter_tools/src/commands/install.dart';

import '../lib/run_command.dart';

main(List<String> args) async {

  // Initialize globals.
  context[Logger] = new StdoutLogger();
  context[DeviceManager] = new DeviceManager();
  Doctor.initGlobal();

  context[AndroidSdk] = AndroidSdk.locateAndroidSdk();

  // DeviceManager dm = context[DeviceManager];
  // var devices = await dm.getDevices();

  // print(devices);

  // print ("Devices enum complete");

  print ("About to create Run");

  RunCommand runCmd = new RunCommand();
  runCmd.run();

// InstallCommand installCommand = new InstallCommand();
// installCommand.run();
  //
  // RunCommand runCommand = new RunCommand();
  // runCommand.argResults = new
  // runCommand.argResults['hot'] = true;
  // runCommand.run();

}

Add Android SDK to the context

Add Android SDK to the context


part of eventsourcing;

QueryHandler csvExtractor(
    QueryHandler sub, String array, String field, List<String> columns) {
  final String columnSeperator = "\\|";
  final String rowSeperator = "\\\$";

  return (Map<String, dynamic> data, QueriableConnection db) async {
    final Map result = await sub(new Map.from(data), db);

    final List arr = result[array];
    for (Map o in arr) {
      if (o.containsKey(field)) {
        final String x = o[field];
        final List<String> rows = x.split(rowSeperator);
        final List newField = [];

        for (int j = 0; j < rows.length; j++) {
          final Map newRow = {};
          final List<String> y = rows[j].split(columnSeperator);
          for (int k = 0; k < columns.length; k++) newRow[columns[k]] = y[k];
          newField.add(newRow);
        }
        o[field] = newField;
      }
    }

    return result;
  };
}

part of eventsourcing;

QueryHandler csvExtractor(
    QueryHandler sub, String array, String field, List<String> columns) {
  final String columnSeperator = "|";
  final String rowSeperator = "\$";

  return (Map<String, dynamic> data, QueriableConnection db) async {
    final Map result = await sub(new Map.from(data), db);

    final List arr = result[array];
    for (Map o in arr) {
      if (o.containsKey(field) && o[field] != null) {
        final String x = o[field];
        final List<String> rows = x.split(rowSeperator);
        final List newField = [];

        for (int j = 0; j < rows.length; j++) {
          final Map newRow = {};
          final List<String> y = rows[j].split(columnSeperator);
          for (int k = 0; k < columns.length; k++) newRow[columns[k]] = y[k];
          newField.add(newRow);
        }
        o[field] = newField;
      }
    }

    return result;
  };
}

Fix escaping of CSV parts

Fix escaping of CSV parts


import 'package:device_info_plus/device_info_plus.dart';

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

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

class DeviceInfoImpl implements DeviceInfo {
  final DeviceInfoPlugin deviceInfoPlugin;

  DeviceInfoImpl(this.deviceInfoPlugin);

  @override
  Future<String> get model async {
    final androidInfo = await deviceInfoPlugin.androidInfo;
    return androidInfo.model;
  }

  @override
  Future<String> get uniqueId async {
    final androidInfo = await deviceInfoPlugin.androidInfo;
    return androidInfo.androidId;
  }
}

import 'package:device_info_plus/device_info_plus.dart';
import 'dart:io' show Platform;

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

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

class DeviceInfoImpl implements DeviceInfo {
  final DeviceInfoPlugin deviceInfoPlugin;

  DeviceInfoImpl(this.deviceInfoPlugin);

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

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

Add iOS support in device info check.

Add iOS support in device info check.


// 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.
//
// Test that type tests are not misoptimized.
// VMOptions=--optimization-counter-threshold=1000 --optimization-filter=IsAnInt

main() {
  train();
  if (IsAnInt("This is not an int")) throw "oops";
}

// Prime the IC with things that are and are not ints.
void train() {
  for (int i = 0; i < 10000; i++) {
    IsAnInt(42); // Smi - always goes first in the generated code.
    IsAnInt(1 << 62); // Mint on 64 bit platforms.
    IsAnInt(1 << 62);
    IsAnInt(4200000000000000000000000000000000000); // BigInt
    IsAnInt(4200000000000000000000000000000000000);
    // This one that is not an int goes last in the IC because it is called
    // less frequently.
    IsAnInt(4.2);
  }
}

bool IsAnInt(f) => f is int;

// 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.
//
// Test that type tests are not misoptimized.
// VMOptions=--optimization-counter-threshold=1000 --optimization-filter=IsAnInt

main() {
  train();
  if (IsAnInt("This is not an int")) throw "oops";
}

// Prime the IC with things that are and are not ints.
void train() {
  int sum = 0;
  for (int i = 0; i < 10000; i++) {
    IsAnInt(42); // Smi - always goes first in the generated code.
    IsAnInt(1 << 62); // Mint on 64 bit platforms.
    IsAnInt(1 << 62);
    IsAnInt(4200000000000000000000000000000000000); // BigInt
    IsAnInt(4200000000000000000000000000000000000);
    // This one that is not an int goes last in the IC because it is called
    // less frequently.
    IsAnInt(4.2);
  }
}

int IsAnInt(Foo f) => f is int;

Revert "Fix misoptimization of 'is' test"

R=johnniwinther@google.com
BUG=

This reverts commits fc693153d1c79e8303abe05697a1d8458b0fef62
and b7797ac45fe6d58d5dae6c4db3094afb1dfaa4bc, code review at
https://codereview.chromium.org/2904543002.  Revert is due to
an AOT failure.
Review-Url: https://codereview.chromium.org/2908153002 .


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

class PlaceholderSnapSheetExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Placeholder example'),
      ),
      body: SnappingSheet(
          child: Placeholder(
            color: Colors.red,
          ),
          sheetBelow: SnappingSheetContent(
              child: Placeholder(
                color: Colors.blue,
              ),
              heightBehavior: SnappingSheetHeight.fixed(expandOnSnapPositionOverflow: false)),
          grabbing: Container(
            color: Colors.white.withOpacity(0.0),
            child: Placeholder(
              color: Colors.green,
            ),
          ),
          sheetAbove: SnappingSheetContent(
            child: Placeholder(
              color: Colors.purple,
            ),
            heightBehavior: SnappingSheetHeight.fixed(expandOnSnapPositionOverflow: false),
          )),
    );
  }
}

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

class PlaceholderSnapSheetExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Placeholder example'),
      ),
      body: SnappingSheet(
          child: Placeholder(
            color: Colors.red,
          ),
          sheetBelow: SnappingSheetContent(
              child: Placeholder(
                color: Colors.blue,
              ),
              heightBehavior: SnappingSheetHeight.fit()),
          grabbing: Container(
            color: Colors.white.withOpacity(0.0),
            child: Placeholder(
              color: Colors.green,
            ),
          ),
          sheetAbove: SnappingSheetContent(
            child: Placeholder(
              color: Colors.purple,
            ),
            heightBehavior: SnappingSheetHeight.fit(),
          )),
    );
  }
}

Revert placeholder example to use hight fit again


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

abstract class Timer {
  /**
   * Creates a new timer. The [callback] callback is invoked after
   * [milliSeconds] milliseconds.
   */
  factory Timer(int milliSeconds, void callback(Timer timer)) {
    if (_TimerFactory._factory == null) {
      throw new UnsupportedOperationException("Timer interface not supported.");
    }
    return _TimerFactory._factory(milliSeconds, callback, false);
  }

  /**
   * Creates a new repeating timer. The [callback] is invoked every
   * [milliSeconds] millisecond until cancelled.
   */
  factory Timer.repeating(int milliSeconds, void callback(Timer timer)) {
    if (_TimerFactory._factory == null) {
      throw new UnsupportedOperationException("Timer interface not supported.");
    }
    return _TimerFactory._factory(milliSeconds, callback, true);
  }

  /**
   * Cancels the timer.
   */
  void cancel();
}

// TODO(ajohnsen): Patch timer once we have support for patching named
//                 factory constructors in the VM.

typedef Timer _TimerFactoryClosure(int milliSeconds,
                                   void callback(Timer timer),
                                   bool repeating);

class _TimerFactory {
  static _TimerFactoryClosure _factory;
}

void _setTimerFactoryClosure(_TimerFactoryClosure closure) {
  _TimerFactory._factory = closure;
}

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

abstract class Timer {
  /**
   * Creates a new timer. The [callback] callback is invoked after
   * [milliSeconds] milliseconds.
   */
  factory Timer(int milliSeconds, void callback(Timer timer)) {
    if (_TimerFactory._factory == null) {
      throw new UnsupportedOperationException("Timer interface not supported.");
    }
    return _TimerFactory._factory(milliSeconds, callback, false);
  }

  /**
   * Creates a new repeating timer. The [callback] is invoked every
   * [milliSeconds] millisecond until cancelled.
   */
  factory Timer.repeating(int milliSeconds, void callback(Timer timer)) {
    if (_TimerFactory._factory == null) {
      throw new UnsupportedOperationException("Timer interface not supported.");
    }
    return _TimerFactory._factory(milliSeconds, callback, true);
  }

  /**
   * Cancels the timer.
   */
  void cancel();
}

// TODO(ajohnsen): Patch timer once we have support for patching named
//                 factory constructors in the VM.

typedef Timer _TimerFactoryClosure(int milliSeconds,
                                   void callback(Timer timer),
                                   bool repeating);

class _TimerFactory {
  static _TimerFactoryClosure _factory;
}

// TODO(ahe): Warning: this is NOT called by Dartium. Instead, it sets
// [_TimerFactory._factory] directly.
void _setTimerFactoryClosure(_TimerFactoryClosure closure) {
  _TimerFactory._factory = closure;
}

Add warning for future maintainers of Timer.

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

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


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

import 'dart:io';
import 'dart:isolate';

const SPAWN_PACKAGE_ROOT = "otherPackageRoot";

void main([args, port]) {
  if (port != null) {
    testPackageRoot(args);
    return;
  }
  var p = new ReceivePort();
  Isolate.spawnUri(Platform.script,
                   [p.sendPort, Platform.packageRoot],
                   {},
                   packageRoot: SPAWN_PACKAGE_ROOT);
  p.listen((msg) {
    p.close();
  });
}

void testPackageRoot(args) {
  var parentPackageRoot = args[1];
  if (parentPackageRoot == Platform.packageRoot) {
    throw "Got parent package root";
  }
  if (Platform.packageRoot != SPAWN_PACKAGE_ROOT) {
    throw "Wrong package root";
  }
  args[0].send(null);
}

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

import 'dart:io';
import 'dart:isolate';

final SPAWN_PACKAGE_ROOT = Uri.parse("otherPackageRoot");

void main([args, port]) {
  if (port != null) {
    testPackageRoot(args);
    return;
  }
  var p = new ReceivePort();
  Isolate.spawnUri(Platform.script,
                   [p.sendPort, Platform.packageRoot],
                   {},
                   packageRoot: SPAWN_PACKAGE_ROOT);
  p.listen((msg) {
    p.close();
  });
}

void testPackageRoot(args) {
  var parentPackageRoot = args[1];
  if (parentPackageRoot == Platform.packageRoot) {
    throw "Got parent package root";
  }
  if (Uri.parse(Platform.packageRoot) != SPAWN_PACKAGE_ROOT) {
    throw "Wrong package root";
  }
  args[0].send(null);
}

Fix test in checked mode.

Fix test in checked mode.

BUG=

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

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


@TestOn('windows')

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

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

void main() {
  test('Volume management API', () {
    final volumeNamePtr =
        allocate<Uint16>(count: MAX_PATH).cast<Utf16>().cast<Utf16>();

    final hFindVolume = FindFirstVolume(volumeNamePtr, MAX_PATH);
    expect(hFindVolume, isNot(INVALID_HANDLE_VALUE));

    final volume = volumeNamePtr.unpackString(MAX_PATH);

    expect(volume, startsWith('\\\\?\\'));

    free(volumeNamePtr);
  });

  test('Power management API', () {
    final powerStatus = SYSTEM_POWER_STATUS.allocate();

    final result = GetSystemPowerStatus(powerStatus.addressOf);

    // Sanity check results against some API provided ranges
    final validBatteryPercentages = [for (var i = 0; i <= 100; i += 1) i]
      ..add(255); // [0..100, 255]

    expect(result, isNonZero);
    expect(powerStatus.ACLineStatus, isIn([0, 1, 255]));
    expect(powerStatus.SystemStatusFlag, isIn([0, 1]));
    expect(powerStatus.BatteryLifePercent, isIn(validBatteryPercentages));

    free(powerStatus.addressOf);
  });
}

@TestOn('windows')

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

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

void main() {
  test('Volume management API', () {
    final volumeNamePtr =
        allocate<Uint16>(count: MAX_PATH).cast<Utf16>().cast<Utf16>();

    final hFindVolume = FindFirstVolume(volumeNamePtr, MAX_PATH);
    expect(hFindVolume, isNot(INVALID_HANDLE_VALUE));

    final volume = volumeNamePtr.unpackString(MAX_PATH);

    expect(volume, startsWith(r'\\?\'));

    free(volumeNamePtr);
  });

  test('Power management API', () {
    final powerStatus = SYSTEM_POWER_STATUS.allocate();

    final result = GetSystemPowerStatus(powerStatus.addressOf);

    // Sanity check results against some API provided ranges
    final validBatteryPercentages = [for (var i = 0; i <= 100; i += 1) i]
      ..add(255); // [0..100, 255]

    expect(result, isNonZero);
    expect(powerStatus.ACLineStatus, isIn([0, 1, 255]));
    expect(powerStatus.SystemStatusFlag, isIn([0, 1]));
    expect(powerStatus.BatteryLifePercent, isIn(validBatteryPercentages));

    free(powerStatus.addressOf);
  });
}

Use raw string for legibility

Use raw string for legibility


// Copyright (c) 2014, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
//
// Test write barrier verification mode.
// VMOptions=--verified_mem --verify_before_gc --verify_after_gc --old_gen_growth_rate=1

var a = [];

void main() {
  for (int i = 0; i < 12; ++i) {
    a.add(new List(12345));
  }
  for (int i = 0; i < 1234; ++i) {
    a[0] = new List(100000);
  }
}

// Copyright (c) 2014, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
//
// Test write barrier verification mode.
// VMOptions=--verify_before_gc --verify_after_gc --old_gen_growth_rate=1

var a = [];

void main() {
  for (int i = 0; i < 12; ++i) {
    a.add(new List(12345));
  }
  for (int i = 0; i < 1234; ++i) {
    a[0] = new List(100000);
  }
}

Remove verified-mem option from test as it is being deprecated.

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


import 'package:ddays/storageservice.dart';
import 'package:test/test.dart';
import 'dart:html';
import 'dart:convert';

void initStorage() {
  window.localStorage[STORAGE_KEY] = JSON.encode([]);
}

void main() {
  test('

Add initstorage function for tests

Add initstorage function for tests


library pin;

import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'dart:io';
import 'dart:mirrors';

import 'package:crypto/crypto.dart';
import 'package:http/http.dart' as LibHttp;
import 'package:path/path.dart' as LibPath;
import 'package:logging/logging.dart';

import 'package:oauth2/oauth2.dart' as OAuth2;
import 'package:google_oauth2_client/google_oauth2_console.dart' as GoogleOAuth;
import 'package:google_drive_v2_api/drive_v2_api_console.dart' as GoogleDrive;
import 'package:google_drive_v2_api/drive_v2_api_client.dart' as GoogleDriveClient show File, FileList;

part 'google/oauth.dart';
part 'google/drive.dart';

part 'utility/logger.dart';
part 'utility/serializer.dart';
part 'utility/time.dart';
part 'utility/utility.dart';

library pin;

import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'dart:io';
import 'dart:mirrors';

import 'package:crypto/crypto.dart';
import 'package:http/http.dart' as LibHttp;
import 'package:path/path.dart' as LibPath;
import 'package:logging/logging.dart';

import 'package:oauth2/oauth2.dart' as OAuth2;
import 'package:google_oauth2_client/google_oauth2_console.dart' as GoogleOAuth;
import 'package:google_drive_v2_api/drive_v2_api_console.dart' as GoogleDrive;
import 'package:google_drive_v2_api/drive_v2_api_client.dart' as GoogleDriveClient show File, FileList;

part 'google/oauth.dart';
part 'google/drive.dart';

part 'utility/logger.dart';
part 'utility/serializable.dart';
part 'utility/time.dart';
part 'utility/utility.dart';

Fix part code file name.

Fix part code file name.


part of app;

/**
 * Notification resource.
 */
@Injectable()
class NotificationsResource {
  final Api _api;

  NotificationsResource(this._api);

  /**
   * Returns all (or unread only) notifications for actually logged in user.
   */
  Future<List<Notification>> readAll([bool unreadOnly = false]) {
    var params = unreadOnly
      ? {'unread': unreadOnly}
      : {};
    return _api.get('notifications', params: params).then((HttpResponse response) {
      var notifications = response.data.map((data) {
        return new Notification(data['id'], DateTime.parse(data['created']), data['read'], data['text'], data['target']);
      });
      return new Future.value(notifications);
    });
  }

  /**
   * Marks all notifications as read.
   */
  Future updateAll(bool read) {
    return _api.put('notifications', data: {'read' : read}).then((_) {
      return new Future.value();
    });
  }
}

part of app;

/**
 * Notification resource.
 */
@Injectable()
class NotificationsResource {
  final Api _api;

  NotificationsResource(this._api);

  /**
   * Returns all (or unread only) notifications for currently logged user.
   */
  Future<List<Notification>> readAll([bool unreadOnly = false]) {
    var params = unreadOnly
      ? {'unread': unreadOnly}
      : {};
    return _api.get('notifications', params: params).then((HttpResponse response) {
      var notifications = response.data.map((data) {
        return new Notification(data['id'], DateTime.parse(data['created']), data['read'], data['text'], data['target']);
      });
      return new Future.value(notifications);
    });
  }

  /**
   * Marks all notifications as read.
   */
  Future updateAll(bool read) {
    return _api.put('notifications', data: {'read' : read}).then((_) {
      return new Future.value();
    });
  }

  /**
   * Marks given notification as read.
   */
  Future update(Notification notification, bool read) {
    return _api.put('notifications/' + notification.id.toString(), data: {'read' : read}).then((_) {
      return new Future.value();
    });
  }
}

Add update method for single notification


part of xml;

/// Enum of the different XML Node types.
class XmlNodeType {

  static const ELEMENT = const XmlNodeType._('ELEMENT');
  static const ATTRIBUTE = const XmlNodeType._('ATTRIBUTE');
  static const TEXT = const XmlNodeType._('TEXT');
  static const CDATA = const XmlNodeType._('CDATA');
  static const PROCESSING = const XmlNodeType._('PROCESSING');
  static const COMMENT = const XmlNodeType._('COMMENT');
  static const DOCUMENT = const XmlNodeType._('DOCUMENT');
  static const DOCUMENT_FRAGMENT = const XmlNodeType._('DOCUMENT_FRAGMENT');
  static const DOCUMENT_TYPE = const XmlNodeType._('DOCUMENT_TYPE');

  final String _type;

  const XmlNodeType._(this._type);

  @override
  String toString() => 'XmlNodeType.$_type';

}

part of xml;

/// Enum of the different XML Node types.
enum XmlNodeType {
  ELEMENT,
  ATTRIBUTE,
  TEXT,
  CDATA,
  PROCESSING,
  COMMENT,
  DOCUMENT,
  DOCUMENT_FRAGMENT,
  DOCUMENT_TYPE
}

Make the XmlNodeType an enum

Make the XmlNodeType an enum


#library('Collection View for My Comic Book Collection');

#import('https://raw.github.com/eee-c/hipster-mvc/master/HipsterView.dart');

class Comics extends HipsterView {
  Comics([collection, el]):
    super(collection:collection, el:el);

  post_initialize() {
    _subscribeEvents();
    _attachUiHandlers();
  }

  _subscribeEvents() {
    if (collection == null) return;

    collection.on.load.add((event) { render(); });
    collection.on.insert.add((event) { render(); });
  }

  render() {
    el.innerHTML = template(collection);
  }

  template(list) {
    // This is silly, but [].forEach is broke
    if (list.length == 0) return '';

    var html = '';
    list.forEach((comic) {
      html += _singleComicBookTemplate(comic);
    });
    return html;
  }

  _singleComicBookTemplate(comic) {
    return """

        ${comic['title']}
        (${comic['author']})
        [delete]

    """;
  }

  _attachUiHandlers() {
    attachHandler(el, 'click .delete', (event) {
      print("[delete] ${event.target.parent.id}");
      collection[event.target.parent.id].
        delete().
        then((_) {
          event.target.parent.remove();
        });
    });
  }

}

#library('Collection View for My Comic Book Collection');

#import('https://raw.github.com/eee-c/hipster-mvc/master/HipsterView.dart');

class Comics extends HipsterView {
  Comics([collection, el]):
    super(collection:collection, el:el);

  post_initialize() {
    _subscribeEvents();
    _attachUiHandlers();
  }

  _subscribeEvents() {
    if (collection == null) return;

    collection.on.load.add((event) { render(); });
    collection.on.insert.add((event) { render(); });
  }

  render() {
    el.innerHTML = template(collection);
  }

  template(list) {
    // This is silly, but [].forEach is broke
    if (list.length == 0) return '';

    var html = '';
    list.forEach((comic) {
      html = html.concat(
        _singleComicBookTemplate(comic)
      );
    });
    return html;
  }

  _singleComicBookTemplate(comic) {
    return """

        ${comic['title']}
        (${comic['author']})
        [delete]

    """;
  }

  _attachUiHandlers() {
    attachHandler(el, 'click .delete', (event) {
      print("[delete] ${event.target.parent.id}");
      collection[event.target.parent.id].
        delete().
        then((_) {
          event.target.parent.remove();
        });
    });
  }

}

Update for new concat syntax

Update for new concat syntax


import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:qr/qr.dart';

import 'qr_painter.dart';

class QrImage extends StatelessWidget {
  QrImage({
    @required String data,
    this.size,
    this.padding = const EdgeInsets.all(10.0),
    this.backgroundColor,
    Color foregroundColor = const Color(0xFF000000),
    int version = 4,
    int errorCorrectionLevel = QrErrorCorrectLevel.L,
    this.onError,
  }) : _painter = new QrPainter(data, foregroundColor, version, errorCorrectionLevel, onError: onError);

  final QrPainter _painter;
  final Color backgroundColor;
  final EdgeInsets padding;
  final double size;
  final QrError onError;

  @override
  Widget build(BuildContext context) {
    return new Container(
      width: size,
      height: size,
      color: backgroundColor,
      child: new Padding(
        padding: this.padding,
        child: new CustomPaint(
          painter: _painter,
        ),
      ),
    );
  }
}

import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:qr/qr.dart';

import 'qr_painter.dart';

class QrImage extends StatelessWidget {
  QrImage({
    @required String data,
    this.size,
    this.padding = const EdgeInsets.all(10.0),
    this.backgroundColor,
    Color foregroundColor = const Color(0xFF000000),
    int version = 4,
    int errorCorrectionLevel = QrErrorCorrectLevel.L,
    this.onError,
  }) : _painter = new QrPainter(data, foregroundColor, version, errorCorrectionLevel, onError: onError);

  final QrPainter _painter;
  final Color backgroundColor;
  final EdgeInsets padding;
  final double size;
  final QrError onError;

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        double widgetSize = size ?? constraints.biggest.shortestSide;
        return new Container(
          width: widgetSize,
          height: widgetSize,
          color: backgroundColor,
          child: new Padding(
            padding: this.padding,
            child: new CustomPaint(
              painter: _painter,
            ),
          ),
        );
      },
    );
  }
}

Add automatic widget size determination when no size property is provided.


library storageservice;

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

final String STORAGE_KEY = 'ddays';

// add an item to a given List, then save
// this list in localStorage with the key 'STORAGE_KEY'.
void saveToStorage(storedlist, item) {
  storedlist.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() {
  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();
}

Add reference to global tasklist.

Add reference to global tasklist.


import 'package:flutter/material.dart';

class BulletItem extends StatelessWidget {
  final String text;

  const BulletItem(this.text, {Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
        padding: const EdgeInsets.only(
          left: 10,
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text('•'),
            const SizedBox(width: 4),
            Expanded(
              child: Text(text),
            ),
          ],
        ));
  }
}

import 'package:flutter/material.dart';

class BulletItem extends StatelessWidget {
  final String text;
  final double fontSize;

  const BulletItem(
    this.text, {
    Key key,
    this.fontSize = 14,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
        padding: const EdgeInsets.only(
          left: 10,
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '•',
              style: TextStyle(fontSize: fontSize),
            ),
            const SizedBox(width: 4),
            Expanded(
              child: Text(
                text,
                style: TextStyle(fontSize: fontSize),
              ),
            ),
          ],
        ));
  }
}

Allow font size for BulletItem.

Allow font size for BulletItem.


import 'dart:io';
import "controllers/HomeController.dart";
import "controllers/ApiController.dart";

typedef bool Handler(HttpRequest request);

void main() {

  String connectionStringRedis = "127.0.0.1:6379/0";

  HttpServer.bind(InternetAddress.ANY_IP_V4, 80).then((HttpServer server) {

    foobar breaking the build on purpose!!

    var routeTable = new Map<String, Handler>();
    var homeController = new HomeController();
    var apiController = new ApiController(connectionStringRedis);

    routeTable["/"] = homeController.Index;
    routeTable["/pingdom"] = homeController.Pingdom;
    routeTable["/api/users"] = apiController.Users;
    routeTable["/api/polls"] = apiController.Polls;
    routeTable["/api/votes"] = apiController.Votes;

    server.listen((HttpRequest request) {

      var now = new DateTime.now();
      var path = request.uri.path;
      print("$now: $path");

      var routeFound = false;
      routeTable.keys.forEach((String pattern)
      {
        if ((!routeFound) && (path == pattern)) // TODO check patterns with placeholders
        {
          routeFound = routeTable[pattern](request);
        }
      });

      if (!routeFound) {
        request.response.statusCode = 404;
        request.response.write("404 not found");
        request.response.close();
      }
    });

  var now = new DateTime.now();
  print("$now: listing....");
  });

}

import 'dart:io';
import "controllers/HomeController.dart";
import "controllers/ApiController.dart";

typedef bool Handler(HttpRequest request);

void main() {

  String connectionStringRedis = "127.0.0.1:6379/0";

  HttpServer.bind(InternetAddress.ANY_IP_V4, 80).then((HttpServer server) {

    var routeTable = new Map<String, Handler>();
    var homeController = new HomeController();
    var apiController = new ApiController(connectionStringRedis);

    routeTable["/"] = homeController.Index;
    routeTable["/pingdom"] = homeController.Pingdom;
    routeTable["/api/users"] = apiController.Users;
    routeTable["/api/polls"] = apiController.Polls;
    routeTable["/api/votes"] = apiController.Votes;

    server.listen((HttpRequest request) {

      var now = new DateTime.now();
      var path = request.uri.path;
      print("$now: $path");

      var routeFound = false;
      routeTable.keys.forEach((String pattern)
      {
        if ((!routeFound) && (path == pattern)) // TODO check patterns with placeholders
        {
          routeFound = routeTable[pattern](request);
        }
      });

      if (!routeFound) {
        request.response.statusCode = 404;
        request.response.write("404 not found");
        request.response.close();
      }
    });

  var now = new DateTime.now();
  print("$now: listing....");
  });

}

Revert "breaking the build on purpose"

Revert "breaking the build on purpose"

This reverts commit b294e5ffb1fd96119a6f5c0b139a3639e4b8a29e.


library polymorphic.grind;

import "dart:io";

import "package:grinder/grinder.dart";
import "package:yaml/yaml.dart";

void main(List<String> args) {
  task("clean", defaultClean);
  task("package", package);
  task("build", null, ["clean", "package"]);
  task("test", test);
  task("ci", null, ["test", "build"]);

  startGrinder(args);
}

test(GrinderContext context) {
  runDartScript(context, "test/all.dart");
}

package(GrinderContext context) {
  ensureOutDirectory();
  var pubspec = loadYaml(new File("pubspec.yaml").readAsStringSync());
  var version = pubspec["version"];

  var args = [
    "--enable-experimental-mirrors",
    "--categories=Server",
    "--output-type=dart",
    "bin/polymorphic.dart",
    "-o",
    "build/out/PolymorphicBot.dart",
    "-m",
    "-Dcompiled=true",
    "-Dversion=${version}"
  ];

  return runProcessAsync(context, "dart2js", arguments: args).then((_) {
    new FileSet.fromDir(getDir("build/out"), pattern: "*.deps").files.forEach((file) {
      deleteEntity(file);
    });
  });
}

ensureOutDirectory() {
  var dir = getDir("build/out");

  if (!dir.existsSync()) {
    dir.createSync(recursive: true);
  }
}

library polymorphic.grind;

import "dart:io";

import "package:grinder/grinder.dart";
import "package:yaml/yaml.dart";

void main(List<String> args) {
  task("clean", defaultClean);
  task("package", package);
  task("build", null, ["clean", "package"]);
  task("test", test);
  task("ci", null, ["test", "build"]);

  startGrinder(args);
}

test(GrinderContext context) {
  runDartScript(context, "test/all.dart");
}

package(GrinderContext context) {
  ensureOutDirectory();
  var pubspec = loadYaml(new File("pubspec.yaml").readAsStringSync());
  var version = pubspec["version"];

  var args = [
    "--enable-experimental-mirrors",
    "--categories=Server",
    "--output-type=dart",
    "bin/polymorphic.dart",
    "-o",
    "build/out/PolymorphicBot.dart",
    "-m",
    "-Dcompiled=true",
    "-Dversion=${version}",
    "--trust-type-annotations",
    "--trust-primitives"
  ];

  return runProcessAsync(context, "dart2js", arguments: args).then((_) {
    new FileSet.fromDir(getDir("build/out"), pattern: "*.deps").files.forEach((file) {
      deleteEntity(file);
    });
  });
}

ensureOutDirectory() {
  var dir = getDir("build/out");

  if (!dir.existsSync()) {
    dir.createSync(recursive: true);
  }
}

Use some dart2js flags to improve compiled output.


part of quiz;

// RequestSunk is one of the base classes in the Aqueduct pipeline
class QuizRequestSink extends RequestSink {
  // Configuration loaded by Dart library safe_config also from Stable|Kernel
  static String ConfigurationKey = "QuizRequestSink.Configuration";
  final Logger log = new Logger('QuizRequestSink');

  QuizRequestSink(Map<String, dynamic> options) : super(options) {
    var dataModel = new ManagedDataModel.fromPackageContainingType(QuizRequestSink);

    var config = options[ConfigurationKey];
    var db = config.database;
    var persistentStore = new PostgreSQLPersistentStore.fromConnectionInfo(db.username, db.password, db.host, db.port, db.databaseName);

    logger.onRecord.listen((rec) => print("${rec.level.name}: ${rec.time}: ${rec.message}"));

    context = new ManagedContext(dataModel, persistentStore);
  }

  ManagedContext context;

  @override
  void setupRouter(Router router) {
    router
      .route("/api/questions/[:index(\\d+)]")
      .generate(() => new QuestionController());

    // Catch-all for static files
    router
      .route("/*")
      .generate(() => new StaticFilesController());
    Response.addEncoder(io.ContentType.parse("application/javascript"), (j) => j.toString());
  }
}

// QuizConfiguration reads and validates the DB configuration from a YAML file
// See https://pub.dartlang.org/packages/safe_config for documentation of ConfigurationItem
class QuizConfiguration extends ConfigurationItem {
  QuizConfiguration(String fileName) : super.fromFile(fileName);

  DatabaseConnectionConfiguration database;
}

part of quiz;

// RequestSunk is one of the base classes in the Aqueduct pipeline
class QuizRequestSink extends RequestSink {
  // Configuration loaded by Dart library safe_config also from Stable|Kernel
  static String ConfigurationKey = "QuizRequestSink.Configuration";
  final Logger log = new Logger('QuizRequestSink');

  QuizRequestSink(Map<String, dynamic> options) : super(options) {
    var dataModel = new ManagedDataModel.fromCurrentMirrorSystem();

    var config = options[ConfigurationKey];
    var db = config.database;
    var persistentStore = new PostgreSQLPersistentStore.fromConnectionInfo(db.username, db.password, db.host, db.port, db.databaseName);

    logger.onRecord.listen((rec) => print("${rec.level.name}: ${rec.time}: ${rec.message}"));

    context = new ManagedContext(dataModel, persistentStore);
  }

  ManagedContext context;

  @override
  void setupRouter(Router router) {
    router
      .route("/api/questions/[:index(\\d+)]")
      .generate(() => new QuestionController());

    // Catch-all for static files
    router
      .route("/*")
      .generate(() => new StaticFilesController());
    Response.addEncoder(io.ContentType.parse("application/javascript"), (j) => j.toString());
  }
}

// QuizConfiguration reads and validates the DB configuration from a YAML file
// See https://pub.dartlang.org/packages/safe_config for documentation of ConfigurationItem
class QuizConfiguration extends ConfigurationItem {
  QuizConfiguration(String fileName) : super.fromFile(fileName);

  DatabaseConnectionConfiguration database;
}

Replace deprecated ManagedDataModel.fromPackageContainingType() by ManagedDataModel.fromCurrentMirrorSystem().


library more.iterable.math;

import 'dart:collection' show IterableBase;

import 'package:more/src/iterable/fold.dart';

/// Returns an iterable over the fibonacci sequence starting with [f0] and
/// [f1]. The default sequence is indefinitely long and by default starts
/// with 0, 1, 1, 2, 3, 5, 8, 13, ...
Iterable<int> fibonacci([int f0 = 0, int f1 = 1]) {
  return fold([f0, f1], (args) => args[0] + args[1]);
}

/// Returns an iterable over the digits of the [number], in the optionally
/// given [base].
Iterable<int> digits(int number, [int base = 10]) {
  return DigitIterable(number.abs(), base);
}

class DigitIterable extends IterableBase<int> {
  final int number;
  final int base;

  DigitIterable(this.number, this.base);

  @override
  Iterator<int> get iterator => DigitIterator(number, base);
}

class DigitIterator extends Iterator<int> {
  int number;
  final int base;

  DigitIterator(this.number, this.base);

  @override
  int current;

  @override
  bool moveNext() {
    if (number == null) {
      current = null;
      return false;
    } else {
      current = number % base;
      number = number ~/ base;
      if (number == 0) {
        number = null;
      }
      return true;
    }
  }
}

library more.iterable.math;

import 'package:more/src/iterable/fold.dart';

/// Returns an iterable over the fibonacci sequence starting with [f0] and
/// [f1]. The default sequence is indefinitely long and by default starts
/// with 0, 1, 1, 2, 3, 5, 8, 13, ...
Iterable<int> fibonacci([int f0 = 0, int f1 = 1]) {
  return fold([f0, f1], (args) => args[0] + args[1]);
}

/// Returns an iterable over the digits of the [value], in the optionally
/// given [base].
Iterable<int> digits(int value, [int base = 10]) sync* {
  if (value == 0) {
    yield 0;
  } else {
    var number = value.abs();
    while (number != 0) {
      final next = number ~/ base;
      yield number - next * base;
      number = next;
    }
  }
}

Simplify the implementation of the digits iterable.


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

import 'package:test/test.dart';

import '../utils.dart';

void main() {
  group('help', help);
}

void help() {
  TestProject p;

  tearDown(() => p?.dispose());

  test('pub', () {
    p = project();
    var result = p.runSync('help', ['pub']);

    var pubHelpResult = p.runSync('pub', ['help']);
    expect(result.stdout, contains(pubHelpResult.stdout));
    expect(result.stderr, contains(pubHelpResult.stderr));
  });
}

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

import 'package:args/command_runner.dart';
import 'package:dartdev/dartdev.dart';
import 'package:test/test.dart';

import '../utils.dart';

void main() {
  group('help', help);
}

void help() {
  TestProject p;

  tearDown(() => p?.dispose());

  /// Commands not tested by the following loop.
  List<String> _commandsNotTested = <String>[
    'help', // `dart help help` is redundant
    'test' // TODO(jwren) not yet implemented, dartbug.com/41041
  ];
  DartdevRunner([]).commands.forEach((String commandKey, Command command) {
    if (!_commandsNotTested.contains(commandKey)) {
      test('(help $commandKey == $commandKey --help)', () {
        p = project();
        var result = p.runSync('help', [commandKey]);

        var verbHelpResult = p.runSync(commandKey, ['--help']);
        expect(result.stdout, contains(verbHelpResult.stdout));
        expect(result.stderr, contains(verbHelpResult.stderr));
      });
    }
  });

  test('(help pub == pub help)', () {
    p = project();
    var result = p.runSync('help', ['pub']);

    var pubHelpResult = p.runSync('pub', ['help']);
    expect(result.stdout, contains(pubHelpResult.stdout));
    expect(result.stderr, contains(pubHelpResult.stderr));
  });

  test('(--help flags also have -h abbr)', () {
    DartdevRunner([]).commands.forEach((String commandKey, Command command) {
      var helpOption = command.argParser.options['help'];
      // Some commands (like pub which use
      // "argParser = ArgParser.allowAnything()") may not have the help Option
      // accessible with the API used above:
      if (helpOption != null) {
        expect(helpOption.abbr, 'h', reason: '');
      }
    });
  });
}

Add some additional tests to test the commands that are currently passing the help <verb> == <verb> --help assertion.

Bug: https://github.com/dart-lang/sdk/issues/41041
Change-Id: I440c76fc84d0d222d8d996c622c711c31b13e948
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/140144
Reviewed-by: Devon Carew <e996497f4f2225f0ee7a9f4d1696ee710b488b66@google.com>
Commit-Queue: Jaime Wren <cd1ab83d11dd618c6b8cd01592020d0bd5183fdc@google.com>


part of 'user_history_bloc.dart';

abstract class UserHistoryEvent extends Equatable {
  const UserHistoryEvent();

  @override
  List<Object> get props => [];
}

class UserHistoryFetched extends UserHistoryEvent {
  final String tautulliId;
  final bool? grouping;
  final bool? includeActivity;
  final String? user;
  final int? userId;
  final int? ratingKey;
  final int? parentRatingKey;
  final int? grandparentRatingKey;
  final DateTime? startDate;
  final DateTime? before;
  final DateTime? after;
  final int? sectionId;
  final String? mediaType;
  final String? transcodeDecision;
  final String? guid;
  final String? orderColumn;
  final String? orderDir;
  final int? start;
  final int? length;
  final String? search;
  final bool freshFetch;
  final SettingsBloc settingsBloc;

  const UserHistoryFetched({
    required this.tautulliId,
    this.grouping,
    this.includeActivity,
    this.user,
    this.userId,
    this.ratingKey,
    this.parentRatingKey,
    this.grandparentRatingKey,
    this.startDate,
    this.before,
    this.after,
    this.sectionId,
    this.mediaType,
    this.transcodeDecision,
    this.guid,
    this.orderColumn,
    this.orderDir,
    this.start,
    this.length,
    this.search,
    this.freshFetch = false,
    required this.settingsBloc,
  });

  @override
  List<Object> get props => [tautulliId, freshFetch, settingsBloc];
}

part of 'user_history_bloc.dart';

abstract class UserHistoryEvent extends Equatable {
  const UserHistoryEvent();

  @override
  List<Object> get props => [];
}

class UserHistoryFetched extends UserHistoryEvent {
  final String tautulliId;
  final bool? grouping;
  final bool? includeActivity;
  final String? user;
  final int userId;
  final int? ratingKey;
  final int? parentRatingKey;
  final int? grandparentRatingKey;
  final DateTime? startDate;
  final DateTime? before;
  final DateTime? after;
  final int? sectionId;
  final String? mediaType;
  final String? transcodeDecision;
  final String? guid;
  final String? orderColumn;
  final String? orderDir;
  final int? start;
  final int? length;
  final String? search;
  final bool freshFetch;
  final SettingsBloc settingsBloc;

  const UserHistoryFetched({
    required this.tautulliId,
    this.grouping,
    this.includeActivity,
    this.user,
    required this.userId,
    this.ratingKey,
    this.parentRatingKey,
    this.grandparentRatingKey,
    this.startDate,
    this.before,
    this.after,
    this.sectionId,
    this.mediaType,
    this.transcodeDecision,
    this.guid,
    this.orderColumn,
    this.orderDir,
    this.start,
    this.length,
    this.search,
    this.freshFetch = false,
    required this.settingsBloc,
  });

  @override
  List<Object> get props => [tautulliId, freshFetch, settingsBloc];
}

Make userId required for UserHistoryFetched event.


library bootstrap_spec;

import '_specs.dart';

void main() {
  describe('bootstrap', () {
    BodyElement body = window.document.querySelector('body');

    it('should default to whole page', () {
      body.innerHtml = '
{{"works"}}
';
      ngBootstrap();
      expect(body.innerHtml).toEqual('
works
');
    });

    it('should compile starting at ng-app node', () {
      body.setInnerHtml(
          '
{{ignor me}}

',
          treeSanitizer: new NullTreeSanitizer());
      ngBootstrap();
      expect(body.text).toEqual('{{ignor me}}works');
    });

    it('should compile starting at ng-app node', () {
      body.setInnerHtml(
          '
{{ignor me}}

',
          treeSanitizer: new NullTreeSanitizer());
      ngBootstrap(element:body.querySelector('div[ng-bind]'));
      expect(body.text).toEqual('{{ignor me}}works');
    });
  });
}

library bootstrap_spec;

import '_specs.dart';

void main() {
  describe('bootstrap', () {
    setBody(String html) {
      var body = window.document.querySelector('body');
      body.setInnerHtml(html, treeSanitizer: new NullTreeSanitizer());
      return $(body);
    }

    it('should default to whole page', () {
      var body = setBody('
{{"works"}}
');
      ngBootstrap();
      expect($(body).html()).toEqual('
works
');
    });

    it('should compile starting at ng-app node', () {
      var body = setBody(
          '
{{ignor me}}

');
      ngBootstrap();
      expect(body.text()).toEqual('{{ignor me}}works');
    });

    it('should compile starting at ng-app node', () {
      var body = setBody(
          '
{{ignor me}}

');
      ngBootstrap(element:body.find('div[ng-bind]').first);
      expect(body.text()).toEqual('{{ignor me}}works');
    });
  });
}

Use JQuery in the bootstrap test

test(bootstrap): Use JQuery in the bootstrap test


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

import '../../../../core/widgets/list_tile_group.dart';
import '../pages/server_settings_page.dart';
import 'settings_list_tile.dart';

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

  @override
  Widget build(BuildContext context) {
    return ListTileGroup(
      heading: 'Servers',
      listTiles: [
        SettingsListTile(
          sensitive: true,
          leading: WebsafeSvg.asset(
            'assets/logos/logo_flat.svg',
            color: Theme.of(context).colorScheme.tertiary,
            height: 35,
          ),
          title: 'Server Name',
          subtitle: 'https://tautulli.domain.com',
          onTap: () => Navigator.of(context).push(
            MaterialPageRoute(
              builder: (context) => const ServerSettingsPage(),
            ),
          ),
        ),
      ],
    );
  }
}

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

import '../../../../core/widgets/list_tile_group.dart';
import '../bloc/settings_bloc.dart';
import '../pages/server_settings_page.dart';
import 'settings_list_tile.dart';

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

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<SettingsBloc, SettingsState>(
      builder: (context, state) {
        return ListTileGroup(
          heading: 'Servers',
          listTiles: state is SettingsSuccess
              ? state.serverList
                  .map(
                    (server) => SettingsListTile(
                      sensitive: true,
                      leading: WebsafeSvg.asset(
                        'assets/logos/logo_flat.svg',
                        color: Theme.of(context).colorScheme.tertiary,
                        height: 35,
                      ),
                      title: server.plexName,
                      subtitle: server.primaryActive!
                          ? server.primaryConnectionAddress
                          : server.secondaryConnectionAddress,
                      onTap: () => Navigator.of(context).push(
                        MaterialPageRoute(
                          builder: (context) => const ServerSettingsPage(),
                        ),
                      ),
                    ),
                  )
                  .toList()
              : [],
        );
      },
    );
  }
}

Build ListTiles from loaded servers.

Build ListTiles from loaded servers.


import 'package:ddays/list_tasks.dart';
import 'package:test/test.dart';
import 'dart:html';

void main() {
  test('sinlgeTaskElement returns a LIElement with correct p children', () {
  LIElement st = singleTaskElement('task1');
  expect(st.children[0].text, 'task1');
  expect(st.classes.contains('singletask'),true);
  expect(st.children[0].classes.contains('summarytext'),true);
  LIElement st2 = singleTaskElement('');
  expect(st2.children[0].text, '');
  expect(st2.children[0].classes.contains('summarytext'),true);
  });
  test('insertTask should prepend a singleTaskElement into #listtasks children.',() {
    insertTask('some task');
    var li = querySelector('#listtasks').children[0];
    expect(li.children[0].text, 'some task');
    insertTask('other task');
    var li2 = querySelector('#listtasks').children[0];
    expect(li2.children[0].text, 'other task');
  });
  test('inserted tasks should be retrievable by their classname "singletask"', () {
    insertTask('more tasks');
    var retrieved = querySelector('.singletask');
    expect(retrieved.children[0].text, 'more tasks');
  });
  test('3 singleTaskElements should have been inserted', () {
    expect(querySelectorAll('.singletask').length,3);
  });

}

import 'package:ddays/list_tasks.dart';
import 'package:test/test.dart';
import 'dart:html';

void main() {
  test('sinlgeTaskElement returns a LIElement with correct p children', () {
  LIElement st = singleTaskElement('task1');
  expect(st.children[0].text, 'task1');
  expect(st.classes.contains('singletask'),true);
  expect(st.children[0].classes.contains('summarytext'),true);
  LIElement st2 = singleTaskElement('');
  expect(st2.children[0].text, '');
  expect(st2.children[0].classes.contains('summarytext'),true);
  });
  test('insertTask should prepend a singleTaskElement into #listtasks children.',() {
    insertTask('some task');
    var li = querySelector('#listtasks').children[0];
    expect(li.children[0].text, 'some task');
    insertTask('other task');
    var li2 = querySelector('#listtasks').children[0];
    expect(li2.children[0].text, 'other task');
  });
  test('inserted tasks should be retrievable by their classname "singletask"', () {
    insertTask('more tasks');
    var retrieved = querySelector('.singletask');
    expect(retrieved.children[0].text, 'more tasks');
  });
  test('3 singleTaskElements should have been inserted', () {
    expect(querySelectorAll('.singletask').length,3);
  });
  test('editTaskElement returns a li element', () {
    var et = editTaskElement('t1');
    expect(et is LIElement, true);
  });

}

Check editTaskElement returns a LIElement.


part of dherkin_core;

class GherkinTable extends IterableBase {

  final String _SPACER = "\t\t  ";

  List<String> _columnNames = [];
  List<Map> _table = [];

  Iterator get iterator => _table.iterator;

  int get length => _table.length;

  bool get empty => _table.isEmpty;

  List<String> get names => _columnNames;

  void addRow(row) {
    if (_columnNames.isEmpty) {
      _columnNames.addAll(row);
    } else {
      _table.add(new Map.fromIterables(_columnNames, row));
    }
  }

  /**
   * Gherkin table
   */
  String gherkinRows() {
    var rows = [];

    if(!_table.isEmpty) {
      rows.add("$_SPACER|${_columnNames.join(" | ")}|");

      for(var row in _table) {
        rows.add("$_SPACER|${row.values.join(" | ")}|");
      }
    }

    return rows;
  }

  String toString() {
    return _table.toString();
  }
}

part of dherkin_core;

class GherkinTable extends IterableBase {

  final String _SPACER = "\t\t  ";

  List<String> _columnNames = [];
  List<Map> _table = [];

  Iterator get iterator => _table.iterator;

  int get length => _table.length;

  bool get empty => _table.isEmpty;

  List<String> get names => _columnNames;

  void addRow(row) {
    if (_columnNames.isEmpty) {
      _columnNames.addAll(row);
    } else {
      _table.add(new Map.fromIterables(_columnNames, row));
    }
  }

  /**
   * Gherkin table
   */
  List<String> gherkinRows() {
    var rows = [];

    if(!_table.isEmpty) {
      rows.add("$_SPACER|${_columnNames.join(" | ")}|");

      for(var row in _table) {
        rows.add("$_SPACER|${row.values.join(" | ")}|");
      }
    }

    return rows;
  }

  String toString() {
    return _table.toString();
  }
}

Fix crash in checked mode because of wrong output type.


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

import "package:expect/expect.dart";

class A {
  x(p1, p2) {
    print(p1 * p2);
    if (p1 * p2 == 12) return;
    x("3", "4");
  }
}

main() => Expect.throws(() => new A().x(1, 2),
                        (e) => e is NoSuchMethodError);

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

import "package:expect/expect.dart";

class A {
  x(p1, p2) {
    print(p1 * p2);
    if (p1 * p2 == 12) return;
    x("3", "4");
  }
}

main() {
  Expect.throws(() => new A().x(1, 2));
}

Change regression test now that String does have operator*.

It still doesn't work for string arguments, but that's a type/argument error.

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

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


library test.event_emitter;

import 'event_emitter_test.dart' as event_emitter_test;
import 'event_emitter_with_event_objects_test.dart' as event_objects_test;
import 'event_handlers_as_classes_test.dart' as event_handlers_test;
import 'package:test/test.dart';

void main () {
    group('[Event emitter]', event_emitter_test.main);
    group('[Event emitter with objects]', event_objects_test.main);
    group('[Event handlers as objects]', event_handlers_test.main);
}

library test.event_emitter;

import './event_emitter_test.dart' as event_emitter_test;
import './event_emitter_with_event_objects_test.dart' as event_objects_test;
import './event_handlers_as_classes_test.dart' as event_handlers_test;
import 'package:test/test.dart';

void main () {
    group('[Event emitter]', event_emitter_test.main);
    group('[Event emitter with objects]', event_objects_test.main);
    group('[Event handlers as objects]', event_handlers_test.main);
}

Change format of importing test packages


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


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.