问:
Flutter DropDown button for account settings
Want to design a custom drop down button for account settings with logout option.
How to change drop down list background color?
How to customize drop down list?

```<code> DropdownButton(
          hint: ButtonText(
            buttonText: "Select a option",
            textColor: ThemeColors.grey8,
            buttonFontSize: 20.0,
          ),
          value: _selectedOption,
          onChanged: (value) {
            setState(() {
              _selectedOption = value;
            });
          },
          items: _options.map((option) {
            return DropdownMenuItem(
              child: ButtonText(
                buttonText: option,
                buttonFontSize: 16.0,
                textColor: ThemeColors.grey8,
              ),
              value: option,
            );
          }).toList(),
</code>```

i want design a custom drop down button with a account dashboard.

答:
I had a similar situation. I needed to implement a dropdown dialog. I used the DropdownButton sources and modified them.

My widget:

```<code>import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

const double _hintWidgetHeight = 34;
const double _hintWidgetWidth = 140;

class MyHintWidget extends StatefulWidget {
  const MyHintWidget({
    Key key,
    @required this.title,
    @required this.style,
    @required this.child,
  }) : super(key: key);

  final String title;
  final TextStyle style;
  final Widget child;

  @override
  _MyHintState createState() => _MyHintState();
}

class _MyHintState extends State<MyHintWidget> with WidgetsBindingObserver {
  static const EdgeInsets _hintItemPadding = EdgeInsets.symmetric(horizontal: 16.0);
  _HintRoute route;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _removeRoute();
    super.dispose();
  }

  @override
  void didChangeMetrics() {
    _removeRoute();
  }

  void _removeRoute() {
    route?._dismiss();
    route = null;
  }

  void _handleTap() {
    final RenderBox itemBox = context.findRenderObject() as RenderBox;
    final Rect itemRect = itemBox.localToGlobal(Offset.zero) & itemBox.size;
    final TextDirection textDirection = Directionality.of(context);
    route = _HintRoute(
      title: widget.title,
      style: widget.style,
      buttonRect: _hintItemPadding.resolve(textDirection).inflateRect(itemRect),
      padding: _hintItemPadding.resolve(textDirection),
      theme: ThemeData(
        brightness: Brightness.light,
      ),
      barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
    );
    Navigator.push(context, route).then<void>((_) {
      route = null;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Semantics(
      button: true,
      child: GestureDetector(
        onTap: _handleTap,
        behavior: HitTestBehavior.opaque,
        child: widget.child,
      ),
    );
  }
}

class _HintRoute extends PopupRoute<void> {
  _HintRoute({
    @required this.title,
    @required this.style,
    this.padding,
    this.buttonRect,
    this.theme,
    this.barrierLabel,
  });

  final String title;
  final TextStyle style;
  final EdgeInsetsGeometry padding;
  final Rect buttonRect;
  final ThemeData theme;

  @override
  Duration get transitionDuration => const Duration(milliseconds: 300);

  @override
  bool get barrierDismissible => true;

  @override
  Color get barrierColor => null;

  @override
  final String barrierLabel;

  @override
  Widget buildPage(
    BuildContext context,
    Animation<double> animation,
    Animation<double> secondaryAnimation,
  ) {
    return LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) {
      return _HintRoutePage(
        title: title,
        style: style,
        route: this,
        constraints: constraints,
        padding: padding,
        buttonRect: buttonRect,
        theme: theme,
      );
    });
  }

  void _dismiss() => navigator?.removeRoute(this);
}

class _HintRoutePage extends StatelessWidget {
  const _HintRoutePage({
    Key key,
    @required this.title,
    @required this.style,
    this.route,
    this.constraints,
    this.padding,
    this.buttonRect,
    this.theme,
  }) : super(key: key);

  final String title;
  final TextStyle style;
  final _HintRoute route;
  final BoxConstraints constraints;
  final EdgeInsetsGeometry padding;
  final Rect buttonRect;
  final ThemeData theme;

  @override
  Widget build(BuildContext context) {
    assert(debugCheckHasDirectionality(context));
    final double availableHeight = constraints.maxHeight;
    final double maxHintHeight = availableHeight - 2.0 * _hintWidgetHeight;

    final double buttonTop = buttonRect.top;
    final double buttonBottom = math.min(buttonRect.bottom, availableHeight);

    final double topLimit = math.min(_hintWidgetHeight, buttonTop);
    final double bottomLimit = math.max(availableHeight - _hintWidgetHeight, buttonBottom);

    final double selectedItemOffset = _hintWidgetHeight + kMaterialListPadding.top;

    double hintTop =
        (buttonTop - selectedItemOffset) - (_hintWidgetHeight * 2 - buttonRect.height) / 3;
    final double preferredHintHeight = _hintWidgetHeight + kMaterialListPadding.vertical;

    final double hintHeight = math.min(maxHintHeight, preferredHintHeight);

    double hintBottom = hintTop + hintHeight;

    if (hintTop < topLimit) hintTop = math.min(buttonTop, topLimit);
    if (hintBottom > bottomLimit) {
      hintBottom = math.max(buttonBottom, bottomLimit);
      hintTop = hintBottom - hintHeight;
    }

    final TextDirection textDirection = Directionality.of(context);

    Widget hint = _HintWidget(
      title: title,
      style: style,
      route: route,
      padding: padding.resolve(textDirection),
    );

    if (theme != null) hint = Theme(data: theme, child: hint);

    return MediaQuery.removePadding(
      context: context,
      removeTop: true,
      removeBottom: true,
      removeLeft: true,
      removeRight: true,
      child: Builder(
        builder: (BuildContext context) {
          return CustomSingleChildLayout(
            delegate: _HintRouteLayout(
              buttonRect: buttonRect,
              hintTop: hintTop,
              hintHeight: hintHeight,
              textDirection: textDirection,
            ),
            child: hint,
          );
        },
      ),
    );
  }
}

class _HintRouteLayout extends SingleChildLayoutDelegate {
  _HintRouteLayout({
    @required this.buttonRect,
    @required this.hintTop,
    @required this.hintHeight,
    @required this.textDirection,
  });

  final Rect buttonRect;
  final double hintTop;
  final double hintHeight;
  final TextDirection textDirection;

  @override
  BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
    final double maxHeight = math.max(0.0, constraints.maxHeight - 2 * _hintWidgetHeight);
    const double width = _hintWidgetWidth;
    return BoxConstraints(
      minWidth: width,
      maxWidth: width,
      minHeight: 0.0,
      maxHeight: maxHeight,
    );
  }

  @override
  Offset getPositionForChild(Size size, Size childSize) {
    assert(() {
      final Rect container = Offset.zero & size;
      if (container.intersect(buttonRect) == buttonRect) {
        assert(hintTop >= 0.0);
        assert(hintTop + hintHeight <= size.height);
      }
      return true;
    }());
    assert(textDirection != null);
    double left;
    if (buttonRect.left > size.width - childSize.width / 1.1) {
      left = size.width - childSize.width;
    } else if (buttonRect.left < childSize.width / 5) {
      left = 0;
    } else {
      left = buttonRect.left - (buttonRect.right - buttonRect.left) / 3;
    }
    return Offset(left, hintTop);
  }

  @override
  bool shouldRelayout(_HintRouteLayout oldDelegate) {
    return buttonRect != oldDelegate.buttonRect ||
        hintTop != oldDelegate.hintTop ||
        hintHeight != oldDelegate.hintHeight ||
        textDirection != oldDelegate.textDirection;
  }
}

class _HintWidget extends StatefulWidget {
  const _HintWidget({
    Key key,
    @required this.title,
    @required this.style,
    this.padding,
    this.route,
  }) : super(key: key);

  final String title;
  final TextStyle style;
  final _HintRoute route;
  final EdgeInsets padding;

  @override
  _HintState createState() => _HintState();
}

class _HintState extends State<_HintWidget> {
  CurvedAnimation _fadeOpacity;
  CurvedAnimation _resize;

  @override
  void initState() {
    super.initState();
    _fadeOpacity = CurvedAnimation(
      parent: widget.route.animation,
      curve: const Interval(0.0, 0.25),
      reverseCurve: const Interval(0.75, 1.0),
    );
    _resize = CurvedAnimation(
      parent: widget.route.animation,
      curve: const Interval(0.25, 0.5),
      reverseCurve: const Threshold(0.0),
    );
  }

  @override
  Widget build(BuildContext context) {
    final MaterialLocalizations localizations = MaterialLocalizations.of(context);
    final _HintRoute route = widget.route;
    const double unit = 0.5 / 1.5;
    CurvedAnimation opacity;
    final double start = (0.5 + 1 * unit).clamp(0.0, 1.0) as double;
    final double end = (start + 1.5 * unit).clamp(0.0, 1.0) as double;
    opacity = CurvedAnimation(parent: route.animation, curve: Interval(start, end));

    return FadeTransition(
      opacity: _fadeOpacity,
      child: CustomPaint(
        painter: _HintPainter(
          color: Theme.of(context).canvasColor,
          elevation: 8,
          resize: _resize,
        ),
        child: Semantics(
          scopesRoute: true,
          namesRoute: true,
          explicitChildNodes: true,
          label: localizations.popupMenuLabel,
          child: Material(
            type: MaterialType.transparency,
            child: Padding(
              padding: kMaterialListPadding,
              child: FadeTransition(
                opacity: opacity,
                child: InkWell(
                  onTap: () => Navigator.pop(context),
                  child: Container(
                    padding: widget.padding,
                    child: Text(
                      widget.title,
                      style: widget.style,
                      textAlign: TextAlign.center,
                    ),
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

class _HintPainter extends CustomPainter {
  _HintPainter({
    this.color,
    this.elevation,
    this.resize,
  })  : _painter = BoxDecoration(
          color: color,
          borderRadius: BorderRadius.circular(6.0),
          boxShadow: kElevationToShadow[elevation],
        ).createBoxPainter(),
        super(repaint: resize);

  final Color color;
  final int elevation;
  final Animation<double> resize;
  final BoxPainter _painter;

  @override
  void paint(Canvas canvas, Size size) {
    final double selectedItemOffset = _hintWidgetHeight + kMaterialListPadding.top;
    final Tween<double> top = Tween<double>(
      begin: selectedItemOffset.clamp(0.0, size.height - _hintWidgetHeight) as double,
      end: 0.0,
    );
    final Tween<double> bottom = Tween<double>(
      begin: (top.begin + _hintWidgetHeight).clamp(_hintWidgetHeight, size.height) as double,
      end: size.height,
    );
    final Rect rect = Rect.fromLTRB(0.0, top.evaluate(resize), size.width, bottom.evaluate(resize));
    _painter.paint(canvas, rect.topLeft, ImageConfiguration(size: rect.size));
  }

  @override
  bool shouldRepaint(_HintPainter oldPainter) {
    return oldPainter.color != color ||
        oldPainter.elevation != elevation ||
        oldPainter.resize != resize;
  }
}
</code>```

So it is used:

```<code>return MyHintWidget(
  title: 'some text',
  style: //text style[![enter image description here][1]][1],
  child: //child,
);
</code>```

Result

Body:
Want to design a custom drop down button for account settings with logout option.
How to change drop down list background color?
How to customize drop down list?

 DropdownButton(
          hint: ButtonText(
            buttonText: "Select a option",
            textColor: ThemeColors.grey8,
            buttonFontSize: 20.0,
          ),
          value: _selectedOption,
          onChanged: (value) {
            setState(() {
              _selectedOption = value;
            });
          },
          items: _options.map((option) {
            return DropdownMenuItem(
              child: ButtonText(
                buttonText: option,
                buttonFontSize: 16.0,
                textColor: ThemeColors.grey8,
              ),
              value: option,
            );
          }).toList(),

i want design a custom drop down button with a account dashboard.

Body:
I had a similar situation. I needed to implement a dropdown dialog. I used the DropdownButton sources and modified them.

My widget:

import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

const double _hintWidgetHeight = 34;
const double _hintWidgetWidth = 140;

class MyHintWidget extends StatefulWidget {
  const MyHintWidget({
    Key key,
    @required this.title,
    @required this.style,
    @required this.child,
  }) : super(key: key);

  final String title;
  final TextStyle style;
  final Widget child;

  @override
  _MyHintState createState() => _MyHintState();
}

class _MyHintState extends State<MyHintWidget> with WidgetsBindingObserver {
  static const EdgeInsets _hintItemPadding = EdgeInsets.symmetric(horizontal: 16.0);
  _HintRoute route;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _removeRoute();
    super.dispose();
  }

  @override
  void didChangeMetrics() {
    _removeRoute();
  }

  void _removeRoute() {
    route?._dismiss();
    route = null;
  }

  void _handleTap() {
    final RenderBox itemBox = context.findRenderObject() as RenderBox;
    final Rect itemRect = itemBox.localToGlobal(Offset.zero) & itemBox.size;
    final TextDirection textDirection = Directionality.of(context);
    route = _HintRoute(
      title: widget.title,
      style: widget.style,
      buttonRect: _hintItemPadding.resolve(textDirection).inflateRect(itemRect),
      padding: _hintItemPadding.resolve(textDirection),
      theme: ThemeData(
        brightness: Brightness.light,
      ),
      barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
    );
    Navigator.push(context, route).then<void>((_) {
      route = null;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Semantics(
      button: true,
      child: GestureDetector(
        onTap: _handleTap,
        behavior: HitTestBehavior.opaque,
        child: widget.child,
      ),
    );
  }
}

class _HintRoute extends PopupRoute<void> {
  _HintRoute({
    @required this.title,
    @required this.style,
    this.padding,
    this.buttonRect,
    this.theme,
    this.barrierLabel,
  });

  final String title;
  final TextStyle style;
  final EdgeInsetsGeometry padding;
  final Rect buttonRect;
  final ThemeData theme;

  @override
  Duration get transitionDuration => const Duration(milliseconds: 300);

  @override
  bool get barrierDismissible => true;

  @override
  Color get barrierColor => null;

  @override
  final String barrierLabel;

  @override
  Widget buildPage(
    BuildContext context,
    Animation<double> animation,
    Animation<double> secondaryAnimation,
  ) {
    return LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) {
      return _HintRoutePage(
        title: title,
        style: style,
        route: this,
        constraints: constraints,
        padding: padding,
        buttonRect: buttonRect,
        theme: theme,
      );
    });
  }

  void _dismiss() => navigator?.removeRoute(this);
}

class _HintRoutePage extends StatelessWidget {
  const _HintRoutePage({
    Key key,
    @required this.title,
    @required this.style,
    this.route,
    this.constraints,
    this.padding,
    this.buttonRect,
    this.theme,
  }) : super(key: key);

  final String title;
  final TextStyle style;
  final _HintRoute route;
  final BoxConstraints constraints;
  final EdgeInsetsGeometry padding;
  final Rect buttonRect;
  final ThemeData theme;

  @override
  Widget build(BuildContext context) {
    assert(debugCheckHasDirectionality(context));
    final double availableHeight = constraints.maxHeight;
    final double maxHintHeight = availableHeight - 2.0 * _hintWidgetHeight;

    final double buttonTop = buttonRect.top;
    final double buttonBottom = math.min(buttonRect.bottom, availableHeight);

    final double topLimit = math.min(_hintWidgetHeight, buttonTop);
    final double bottomLimit = math.max(availableHeight - _hintWidgetHeight, buttonBottom);

    final double selectedItemOffset = _hintWidgetHeight + kMaterialListPadding.top;

    double hintTop =
        (buttonTop - selectedItemOffset) - (_hintWidgetHeight * 2 - buttonRect.height) / 3;
    final double preferredHintHeight = _hintWidgetHeight + kMaterialListPadding.vertical;

    final double hintHeight = math.min(maxHintHeight, preferredHintHeight);

    double hintBottom = hintTop + hintHeight;

    if (hintTop < topLimit) hintTop = math.min(buttonTop, topLimit);
    if (hintBottom > bottomLimit) {
      hintBottom = math.max(buttonBottom, bottomLimit);
      hintTop = hintBottom - hintHeight;
    }

    final TextDirection textDirection = Directionality.of(context);

    Widget hint = _HintWidget(
      title: title,
      style: style,
      route: route,
      padding: padding.resolve(textDirection),
    );

    if (theme != null) hint = Theme(data: theme, child: hint);

    return MediaQuery.removePadding(
      context: context,
      removeTop: true,
      removeBottom: true,
      removeLeft: true,
      removeRight: true,
      child: Builder(
        builder: (BuildContext context) {
          return CustomSingleChildLayout(
            delegate: _HintRouteLayout(
              buttonRect: buttonRect,
              hintTop: hintTop,
              hintHeight: hintHeight,
              textDirection: textDirection,
            ),
            child: hint,
          );
        },
      ),
    );
  }
}

class _HintRouteLayout extends SingleChildLayoutDelegate {
  _HintRouteLayout({
    @required this.buttonRect,
    @required this.hintTop,
    @required this.hintHeight,
    @required this.textDirection,
  });

  final Rect buttonRect;
  final double hintTop;
  final double hintHeight;
  final TextDirection textDirection;

  @override
  BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
    final double maxHeight = math.max(0.0, constraints.maxHeight - 2 * _hintWidgetHeight);
    const double width = _hintWidgetWidth;
    return BoxConstraints(
      minWidth: width,
      maxWidth: width,
      minHeight: 0.0,
      maxHeight: maxHeight,
    );
  }

  @override
  Offset getPositionForChild(Size size, Size childSize) {
    assert(() {
      final Rect container = Offset.zero & size;
      if (container.intersect(buttonRect) == buttonRect) {
        assert(hintTop >= 0.0);
        assert(hintTop + hintHeight <= size.height);
      }
      return true;
    }());
    assert(textDirection != null);
    double left;
    if (buttonRect.left > size.width - childSize.width / 1.1) {
      left = size.width - childSize.width;
    } else if (buttonRect.left < childSize.width / 5) {
      left = 0;
    } else {
      left = buttonRect.left - (buttonRect.right - buttonRect.left) / 3;
    }
    return Offset(left, hintTop);
  }

  @override
  bool shouldRelayout(_HintRouteLayout oldDelegate) {
    return buttonRect != oldDelegate.buttonRect ||
        hintTop != oldDelegate.hintTop ||
        hintHeight != oldDelegate.hintHeight ||
        textDirection != oldDelegate.textDirection;
  }
}

class _HintWidget extends StatefulWidget {
  const _HintWidget({
    Key key,
    @required this.title,
    @required this.style,
    this.padding,
    this.route,
  }) : super(key: key);

  final String title;
  final TextStyle style;
  final _HintRoute route;
  final EdgeInsets padding;

  @override
  _HintState createState() => _HintState();
}

class _HintState extends State<_HintWidget> {
  CurvedAnimation _fadeOpacity;
  CurvedAnimation _resize;

  @override
  void initState() {
    super.initState();
    _fadeOpacity = CurvedAnimation(
      parent: widget.route.animation,
      curve: const Interval(0.0, 0.25),
      reverseCurve: const Interval(0.75, 1.0),
    );
    _resize = CurvedAnimation(
      parent: widget.route.animation,
      curve: const Interval(0.25, 0.5),
      reverseCurve: const Threshold(0.0),
    );
  }

  @override
  Widget build(BuildContext context) {
    final MaterialLocalizations localizations = MaterialLocalizations.of(context);
    final _HintRoute route = widget.route;
    const double unit = 0.5 / 1.5;
    CurvedAnimation opacity;
    final double start = (0.5 + 1 * unit).clamp(0.0, 1.0) as double;
    final double end = (start + 1.5 * unit).clamp(0.0, 1.0) as double;
    opacity = CurvedAnimation(parent: route.animation, curve: Interval(start, end));

    return FadeTransition(
      opacity: _fadeOpacity,
      child: CustomPaint(
        painter: _HintPainter(
          color: Theme.of(context).canvasColor,
          elevation: 8,
          resize: _resize,
        ),
        child: Semantics(
          scopesRoute: true,
          namesRoute: true,
          explicitChildNodes: true,
          label: localizations.popupMenuLabel,
          child: Material(
            type: MaterialType.transparency,
            child: Padding(
              padding: kMaterialListPadding,
              child: FadeTransition(
                opacity: opacity,
                child: InkWell(
                  onTap: () => Navigator.pop(context),
                  child: Container(
                    padding: widget.padding,
                    child: Text(
                      widget.title,
                      style: widget.style,
                      textAlign: TextAlign.center,
                    ),
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

class _HintPainter extends CustomPainter {
  _HintPainter({
    this.color,
    this.elevation,
    this.resize,
  })  : _painter = BoxDecoration(
          color: color,
          borderRadius: BorderRadius.circular(6.0),
          boxShadow: kElevationToShadow[elevation],
        ).createBoxPainter(),
        super(repaint: resize);

  final Color color;
  final int elevation;
  final Animation<double> resize;
  final BoxPainter _painter;

  @override
  void paint(Canvas canvas, Size size) {
    final double selectedItemOffset = _hintWidgetHeight + kMaterialListPadding.top;
    final Tween<double> top = Tween<double>(
      begin: selectedItemOffset.clamp(0.0, size.height - _hintWidgetHeight) as double,
      end: 0.0,
    );
    final Tween<double> bottom = Tween<double>(
      begin: (top.begin + _hintWidgetHeight).clamp(_hintWidgetHeight, size.height) as double,
      end: size.height,
    );
    final Rect rect = Rect.fromLTRB(0.0, top.evaluate(resize), size.width, bottom.evaluate(resize));
    _painter.paint(canvas, rect.topLeft, ImageConfiguration(size: rect.size));
  }

  @override
  bool shouldRepaint(_HintPainter oldPainter) {
    return oldPainter.color != color ||
        oldPainter.elevation != elevation ||
        oldPainter.resize != resize;
  }
}

So it is used:

return MyHintWidget(
  title: 'some text',
  style: //text style[![enter image description here][1]][1],
  child: //child,
);

Result


来源: stackexchange

问:
Powershell command that only works properly for a few files
I have a bunch of files named 001.jpg, 002.jpg and so on. I'd like to rename them Gym Heroes - 001 (US).jpg, etc. I wrote this Powershell command:

```<code>dir | Rename-Item -NewName { "Gym Heroes - " + $_.name.Insert(3," (US)") }
</code>```

This works as expected when there are 35 or fewer pictures, but starting from 36 pictures, all the pictures are weirdly renamed (Gym Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - 016 (US).jpg) and I get the following error message for each file (not the exact error message since I translated it to English):

```<code>Rename-Item : Part of the access path is impossible to find.
At character Line:1 : 7
+ dir | Rename-Item -NewName { "Gym Heroes - " + $_.name.Insert(3," (US ...
+       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (D:\Downloads... - 062 (US).jpg:String) [Rename-Item], DirectoryNotFoundE
   xception
    + FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommande
</code>```

I don't understand at all why this is happening... I could rename my pictures 35 by 35 but I'd like to understand why my command doesn't work properly.

Thanks!

答:
You need to include your dir/gci command in parentheses to force it to evaulate first. Otherwise you can get some items that appear to be processed multiple times.

So...

```<code>(dir) | Rename-Item -NewName { "Gym Heroes - " + $_.name.Insert(3," (US)") }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a bunch of files named 001.jpg, 002.jpg and so on. I'd like to rename them Gym Heroes - 001 (US).jpg, etc. I wrote this Powershell command:

dir | Rename-Item -NewName { "Gym Heroes - " + $_.name.Insert(3," (US)") }

This works as expected when there are 35 or fewer pictures, but starting from 36 pictures, all the pictures are weirdly renamed (Gym Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - 016 (US).jpg) and I get the following error message for each file (not the exact error message since I translated it to English):

Rename-Item : Part of the access path is impossible to find.
At character Line:1 : 7
+ dir | Rename-Item -NewName { "Gym Heroes - " + $_.name.Insert(3," (US ...
+       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (D:\Downloads... - 062 (US).jpg:String) [Rename-Item], DirectoryNotFoundE
   xception
    + FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommande

I don't understand at all why this is happening... I could rename my pictures 35 by 35 but I'd like to understand why my command doesn't work properly.

Thanks!

Body:
You need to include your dir/gci command in parentheses to force it to evaulate first. Otherwise you can get some items that appear to be processed multiple times.

So...

(dir) | Rename-Item -NewName { "Gym Heroes - " + $_.name.Insert(3," (US)") }


问:
Javascript code to make animation react to sound file works in Edge but not in Chrome
I found this code from a YouTube tutorial produced by Adam Khoury from his Analyser Bars Animation HTML5 Audio API JavaScript Tutorial.  Where a music analyser graphic reacts to a sound file
It is from 2013. I have tried to get it to work by updating the code as far as I understand it. I have removed webkit and adjusted the syntax changing some letters to lowercase. It plays fine in the Edge browser but not in Chrome. Obviously, I have missed something, any help would be greatly appreciated.

HTML code:

```<code><!doctype html>
<html>
<head>

<link rel="stylesheet" type="text/css" href="css/style.css">
    <script src="js.js"></script>
<title>Untitled Document</title>
</head>
<body>

<div id="mp3_player">

    <div id="audio_box"></div>

    <canvas id="analyser_render"></canvas>
    </div>
 </body>
</html>
</code>```

CSS code:

```<code>body{
    background-color: #494545;
}
#mp3_player{
    width: 420px;
    height: 75px;
    background-color:#FAFAFA;
    margin-left: auto;
    margin-right: auto;
    margin-top: 300px;
    text-align: center;
}
audio{
    width: 400px;
    padding-top: 10px;
    }
#analyser_render{

    width: 400px;
    height: 20px;
    background-color: aliceblue;
    }
</code>```

Javascript Code:

```<code>var audio = new Audio();
audio.src = 'Piano_01.mp3';
audio.controls = true;
audio.loop = true;
audio.autoplay = false;
// Establish all variables that your Analyser will use
var canvas, ctx, source, context, analyser, fbc_array, bars, bar_x, bar_width, bar_height;
// Initialize the MP3 player after the page loads all of its HTML into the window
window.addEventListener("load", initMp3Player, false);
function initMp3Player(){
    document.getElementById('audio_box').appendChild(audio);
    context = new AudioContext(); // AudioContext object instance
    analyser = context.createAnalyser(); // AnalyserNode method
    canvas = document.getElementById('analyser_render');
    ctx = canvas.getContext('2d');
    // Re-route audio playback into the processing graph of the AudioContext
    source = context.createMediaElementSource(audio);
    source.connect(analyser);
    analyser.connect(context.destination);
    frameLooper();
}
// frameLooper() animates any style of graphics you wish to the audio frequency
// Looping at the default frame rate that the browser provides(approx. 60 FPS)
function frameLooper(){
    window.requestAnimationFrame(frameLooper);
    fbc_array = new Uint8Array(analyser.frequencyBinCount);
    analyser.getByteFrequencyData(fbc_array);
    ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
    ctx.fillStyle = '#006600'; // Color of the bars
    bars = 100;
    for (var i = 0; i < bars; i++) {
        bar_x = i * 3;
        bar_width = 2;
        bar_height = -(fbc_array[i] / 2);
        //  fillRect( x, y, width, height ) // Explanation of the parameters below
        ctx.fillRect(bar_x, canvas.height, bar_width, bar_height);
    }
}
</code>```

答:
In Chrome you're running into two issues here:

in the callback handler for the onload event you're creating a new AudioContext() which is not allowed because playback needs to be triggered by a user interaction like a mouse click

chrome prevents access to audio files from the local file system. If you look into the console you most likely spot an error like

Access to audio at ... from origin 'null' has been blocked by CORS
  policy

To workaround:

upload your files to a webserver or run from a local webserver.

instead of catching the onload event to set up your AudioContext, listen for the Audio objects playing event and do the initializaion in it's callback handler. This will make sure the AudioContext is created as soon as the audio started playing because the user clicked on the play button.

Here's an example (just click on 'Run code snippet'):

var audio = new Audio();
audio.crossOrigin = "anonymous";
audio.src = 'https://api.codetabs.com/v1/proxy?quest=http://www.hyperion-records.co.uk/audiotest/3%20Schubert%20String%20Quartet%20No%2014%20in%20D%20minor%20Death%20and%20the%20Maiden,%20D810%20-%20Movement%203%20Scherzo%20Allegro%20molto.MP3';
audio.controls = true;
audio.loop = true;
audio.autoplay = false;
audio.addEventListener("playing", start);
// Establish all variables that your Analyser will use
var canvas, ctx, source, context, analyser, fbc_array, bars, bar_x, bar_width, bar_height;
// Initialize the MP3 player after the page loads all of its HTML into the window
window.addEventListener("load", initMp3Player, false);

function initMp3Player() {
  document.getElementById('audio_box').appendChild(audio);
}
// frameLooper() animates any style of graphics you wish to the audio frequency
// Looping at the default frame rate that the browser provides(approx. 60 FPS)
function frameLooper() {
  window.requestAnimationFrame(frameLooper);
  fbc_array = new Uint8Array(analyser.frequencyBinCount);
  analyser.getByteFrequencyData(fbc_array);
  ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
  ctx.fillStyle = '#006600'; // Color of the bars
  bars = 100;
  for (var i = 0; i < bars; i++) {
    bar_x = i * 3;
    bar_width = 2;
    bar_height = -(fbc_array[i] / 2);
    //  fillRect( x, y, width, height ) // Explanation of the parameters below
    ctx.fillRect(bar_x, canvas.height, bar_width, bar_height);
  }
}

function start() {
  context = new AudioContext(); // AudioContext object instance
  analyser = context.createAnalyser(); // AnalyserNode method
  canvas = document.getElementById('analyser_render');
  ctx = canvas.getContext('2d');
  // Re-route audio playback into the processing graph of the AudioContext
  source = context.createMediaElementSource(audio);
  source.connect(analyser);
  analyser.connect(context.destination);
  frameLooper();
  audio.removeEventListener("playing", start);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-color: #494545;
}

#mp3_player {
  width: 420px;
  height: 75px;
  background-color: #FAFAFA;
  margin-left: auto;
  margin-right: auto;
  margin-top: 300px;
  text-align: center;
}

audio {
  width: 400px;
  padding-top: 10px;
}

#analyser_render {
  width: 400px;
  height: 20px;
  background-color: aliceblue;
}</code>```

    <canvas id="analyser_render"></canvas>

```

Body:
I found this code from a YouTube tutorial produced by Adam Khoury from his Analyser Bars Animation HTML5 Audio API JavaScript Tutorial.  Where a music analyser graphic reacts to a sound file
It is from 2013. I have tried to get it to work by updating the code as far as I understand it. I have removed webkit and adjusted the syntax changing some letters to lowercase. It plays fine in the Edge browser but not in Chrome. Obviously, I have missed something, any help would be greatly appreciated.

HTML code:

<!doctype html>

<link rel="stylesheet" type="text/css" href="css/style.css">

<title>Untitled Document</title>

    <canvas id="analyser_render"></canvas>

CSS code:

body{
    background-color: #494545;
}
#mp3_player{
    width: 420px;
    height: 75px;
    background-color:#FAFAFA;
    margin-left: auto;
    margin-right: auto;
    margin-top: 300px;
    text-align: center;
}
audio{
    width: 400px;
    padding-top: 10px;
    }
#analyser_render{

    width: 400px;
    height: 20px;
    background-color: aliceblue;
    }

Javascript Code:

var audio = new Audio();
audio.src = 'Piano_01.mp3';
audio.controls = true;
audio.loop = true;
audio.autoplay = false;
// Establish all variables that your Analyser will use
var canvas, ctx, source, context, analyser, fbc_array, bars, bar_x, bar_width, bar_height;
// Initialize the MP3 player after the page loads all of its HTML into the window
window.addEventListener("load", initMp3Player, false);
function initMp3Player(){
    document.getElementById('audio_box').appendChild(audio);
    context = new AudioContext(); // AudioContext object instance
    analyser = context.createAnalyser(); // AnalyserNode method
    canvas = document.getElementById('analyser_render');
    ctx = canvas.getContext('2d');
    // Re-route audio playback into the processing graph of the AudioContext
    source = context.createMediaElementSource(audio);
    source.connect(analyser);
    analyser.connect(context.destination);
    frameLooper();
}
// frameLooper() animates any style of graphics you wish to the audio frequency
// Looping at the default frame rate that the browser provides(approx. 60 FPS)
function frameLooper(){
    window.requestAnimationFrame(frameLooper);
    fbc_array = new Uint8Array(analyser.frequencyBinCount);
    analyser.getByteFrequencyData(fbc_array);
    ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
    ctx.fillStyle = '#006600'; // Color of the bars
    bars = 100;
    for (var i = 0; i < bars; i++) {
        bar_x = i * 3;
        bar_width = 2;
        bar_height = -(fbc_array[i] / 2);
        //  fillRect( x, y, width, height ) // Explanation of the parameters below
        ctx.fillRect(bar_x, canvas.height, bar_width, bar_height);
    }
}

Body:
In Chrome you're running into two issues here:

in the callback handler for the onload event you're creating a new AudioContext() which is not allowed because playback needs to be triggered by a user interaction like a mouse click

chrome prevents access to audio files from the local file system. If you look into the console you most likely spot an error like

Access to audio at ... from origin 'null' has been blocked by CORS
  policy

To workaround:

upload your files to a webserver or run from a local webserver.

instead of catching the onload event to set up your AudioContext, listen for the Audio objects playing event and do the initializaion in it's callback handler. This will make sure the AudioContext is created as soon as the audio started playing because the user clicked on the play button.

Here's an example (just click on 'Run code snippet'):

var audio = new Audio();
audio.crossOrigin = "anonymous";
audio.src = 'https://api.codetabs.com/v1/proxy?quest=http://www.hyperion-records.co.uk/audiotest/3%20Schubert%20String%20Quartet%20No%2014%20in%20D%20minor%20Death%20and%20the%20Maiden,%20D810%20-%20Movement%203%20Scherzo%20Allegro%20molto.MP3';
audio.controls = true;
audio.loop = true;
audio.autoplay = false;
audio.addEventListener("playing", start);
// Establish all variables that your Analyser will use
var canvas, ctx, source, context, analyser, fbc_array, bars, bar_x, bar_width, bar_height;
// Initialize the MP3 player after the page loads all of its HTML into the window
window.addEventListener("load", initMp3Player, false);

function initMp3Player() {
  document.getElementById('audio_box').appendChild(audio);
}
// frameLooper() animates any style of graphics you wish to the audio frequency
// Looping at the default frame rate that the browser provides(approx. 60 FPS)
function frameLooper() {
  window.requestAnimationFrame(frameLooper);
  fbc_array = new Uint8Array(analyser.frequencyBinCount);
  analyser.getByteFrequencyData(fbc_array);
  ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
  ctx.fillStyle = '#006600'; // Color of the bars
  bars = 100;
  for (var i = 0; i < bars; i++) {
    bar_x = i * 3;
    bar_width = 2;
    bar_height = -(fbc_array[i] / 2);
    //  fillRect( x, y, width, height ) // Explanation of the parameters below
    ctx.fillRect(bar_x, canvas.height, bar_width, bar_height);
  }
}

function start() {
  context = new AudioContext(); // AudioContext object instance
  analyser = context.createAnalyser(); // AnalyserNode method
  canvas = document.getElementById('analyser_render');
  ctx = canvas.getContext('2d');
  // Re-route audio playback into the processing graph of the AudioContext
  source = context.createMediaElementSource(audio);
  source.connect(analyser);
  analyser.connect(context.destination);
  frameLooper();
  audio.removeEventListener("playing", start);
}

body {
  background-color: #494545;
}

#mp3_player {
  width: 420px;
  height: 75px;
  background-color: #FAFAFA;
  margin-left: auto;
  margin-right: auto;
  margin-top: 300px;
  text-align: center;
}

audio {
  width: 400px;
  padding-top: 10px;
}

#analyser_render {
  width: 400px;
  height: 20px;
  background-color: aliceblue;
}

<body>

  <div id="mp3_player">

    <div id="audio_box"></div>

    <canvas id="analyser_render"></canvas>
  </div>
</body>


问:
MailApp.sendEmail sending email to myself when not set to in google apps script
```<code>MailApp.sendEmail({
to: " someemail@gmail.com , ",
subject: "New change for " + variable1+ " at " + variable2,
htmlBody: "Added: " + addedlist_new.toString() + "<br><br>" +
"Removed: " + removedlist_old.toString() + "<br><br>" +
" https://docs.google.com/spreadsheets/d/someurlhere ",
})
</code>```

When I have an email directed to a user other than myself, I find that I end up having the email that was sent to them, in my inbox. It shows it's sent to the user I entered in the "To" area, but it's in my inbox. Why does it place it in my Inbox instead of Sent Mail?

答: I had this problem and found that replacing Mailapp.sendEmail with Gmailapp.sendEmail worked.

ContentLicense: CC BY-SA 3.0

Body:
MailApp.sendEmail({
to: " someemail@gmail.com , ",
subject: "New change for " + variable1+ " at " + variable2,
htmlBody: "Added: " + addedlist_new.toString() + "

" +
"Removed: " + removedlist_old.toString() + "

" +
" https://docs.google.com/spreadsheets/d/someurlhere ",
})

When I have an email directed to a user other than myself, I find that I end up having the email that was sent to them, in my inbox. It shows it's sent to the user I entered in the "To" area, but it's in my inbox. Why does it place it in my Inbox instead of Sent Mail?


问:
How to use constructor injection in Mapstruct's mapper?
In some mapper classes, I need to use an autowired ObjectMapper to transform String to JsonNode or verse-vera. I can acheive my goal by using the field injection with @autowired. But it's not suitable for unit test so I'd like to try using the constructor injection.

My current working code with the field injection:

```<code>@Mapper(componentModel = "spring")
public class CustomMapper {
  @autowired
  ObjectMapper mapper;
}
</code>```

I try to convert it to the constructor injection so I can provide constructor argument in my unit test:

```<code>@Mapper(componentModel = "spring")
public class CustomMapper {
  ObjectMapper mapper;

  public CustomMapper(ObjectMapper mapper) {
    this.mapper = mapper;
  }
}
</code>```

But I get a Constructor in CustomMapper cannot be applied to the given type error during compilation.
How do I fix it? Or is there other better way to map String to JsonNode in Mapstruct?

答:
1)The MapStruct has good feature:

```<code>@Mapper(componentModel = "spring", uses ={ObjectMapper.class}, injectionStrategy = InjectionStrategy.CONSTRUCTOR)
</code>```

2)You could do it this way:

```<code>@Mapper(componentModel = "spring")
@RequiredArgsConstructor //lombok annotation, which authowire your field via constructor
public class CustomMapper {
  private final ObjectMapper mapper;
}
</code>```

But still you could do it via field.You stiil should mock it in tests in both cases. Just remember to use @InjectMocks

```<code>public CustomMapperTest {
   @InjectMocks
   private CustomMapper customMapper;
   @Mock
   private ObjectMapper objectMapper

   @BeforeEach
   void setUp() {
      customMapper= new CustomMapperImpl();
      MockitoAnnotations.initMocks(this);
      when(objectMapper.map()).thenReturn(object);
   }

   @Test
   void shouldMap() {
      Object toObject = customerMapper.map(fromObject);
      assertThat(toObject)
        .hasFieldWithValue("fieldName", fromObject.getField());
   }
}
</code>```

Body:
In some mapper classes, I need to use an autowired ObjectMapper to transform String to JsonNode or verse-vera. I can acheive my goal by using the field injection with @autowired. But it's not suitable for unit test so I'd like to try using the constructor injection.

My current working code with the field injection:

@Mapper(componentModel = "spring")
public class CustomMapper {
  @autowired
  ObjectMapper mapper;
}

I try to convert it to the constructor injection so I can provide constructor argument in my unit test:

@Mapper(componentModel = "spring")
public class CustomMapper {
  ObjectMapper mapper;

  public CustomMapper(ObjectMapper mapper) {
    this.mapper = mapper;
  }
}

But I get a Constructor in CustomMapper cannot be applied to the given type error during compilation.
How do I fix it? Or is there other better way to map String to JsonNode in Mapstruct?

Body:
1)The MapStruct has good feature:

@Mapper(componentModel = "spring", uses ={ObjectMapper.class}, injectionStrategy = InjectionStrategy.CONSTRUCTOR)

2)You could do it this way:

@Mapper(componentModel = "spring")
@RequiredArgsConstructor //lombok annotation, which authowire your field via constructor
public class CustomMapper {
  private final ObjectMapper mapper;
}

But still you could do it via field.You stiil should mock it in tests in both cases. Just remember to use @InjectMocks

public CustomMapperTest {
   @InjectMocks
   private CustomMapper customMapper;
   @Mock
   private ObjectMapper objectMapper

   @BeforeEach
   void setUp() {
      customMapper= new CustomMapperImpl();
      MockitoAnnotations.initMocks(this);
      when(objectMapper.map()).thenReturn(object);
   }

   @Test
   void shouldMap() {
      Object toObject = customerMapper.map(fromObject);
      assertThat(toObject)
        .hasFieldWithValue("fieldName", fromObject.getField());
   }
}


问:
Regular Expression to Replace xxx(zzz)xxx format in c#
I need a regular expression to replace xxx()xxx in this format xxx(zzz)xxx with nothing.

here is example:  Sara(56)Gorge => 56

答:
You can use the following regex:

```<code>@"\S+?\((\S+?)\)\S+"
</code>```

As follows:

```<code>var pattern = @"\S+?\((\S+?)\)\S+"
var replaced = Regex.Replace(text, pattern, "$1");
</code>```

Body:
You can use the following regex:

@"\S+?\((\S+?)\)\S+"

As follows:

var pattern = @"\S+?\((\S+?)\)\S+"
var replaced = Regex.Replace(text, pattern, "$1");


问:
Dynamic named field names
I want to create a JSON response where the field name of the parent object has a dynamic name.

It is better explained with an example.

Right now, my response looks like this:

```<code>{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}
</code>```

For that I created a struct -> populate it -> return it.

My struct looks like this:

```<code>type Placeholder struct {
    userId    int    `json:"userId"`
    id        int    `json:"id"`
    title     string `json:"title"`
    completed bool   `json:"completed"`
}
//...
res := Placeholder{
  userId: 1,
  id: 1,
  title: "delectus aut autem",
  completed: false,
}
</code>```

Now I want to use the userId as the field name. So I want to have this result:

```<code>{
  "1": {
     "id": 1,
     "title": "delectus aut autem",
     "completed": false
  }
}
</code>```

Is there any possibility to do this in Go?

答:
Simply change the datatype of res from Placeholder to map[int]Placeholder.

```<code>userId := 1
res := map[int]Placeholder{
    userId: {
        id:        1,
        title:     "delectus aut autem",
        completed: false,
    },
}
fmt.Printf("%v", res)
</code>```

Playground: https://play.golang.org/p/rCBl2r7fQTe

Title: Dynamic named field names

Body:
I want to create a JSON response where the field name of the parent object has a dynamic name.

It is better explained with an example.

Right now, my response looks like this:

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

For that I created a struct -> populate it -> return it.

My struct looks like this:

type Placeholder struct {
    userId    int    `json:"userId"`
    id        int    `json:"id"`
    title     string `json:"title"`
    completed bool   `json:"completed"`
}
//...
res := Placeholder{
  userId: 1,
  id: 1,
  title: "delectus aut autem",
  completed: false,
}

Now I want to use the userId as the field name. So I want to have this result:

{
  "1": {
     "id": 1,
     "title": "delectus aut autem",
     "completed": false
  }
}

Is there any possibility to do this in Go?

Body:
Simply change the datatype of res from Placeholder to map[int]Placeholder.

userId := 1
res := map[int]Placeholder{
    userId: {
        id:        1,
        title:     "delectus aut autem",
        completed: false,
    },
}
fmt.Printf("%v", res)

Playground: https://play.golang.org/p/rCBl2r7fQTe


问:
How do I change columns in the same order as in my order matrix, per row
I have a matrix where I stored the order of items of a questionnaire, where the first column contains the name of the item that is first shown, the second column has the second shown item, etc. Each row in this matrix represents a new questionnaire, with the same items but with the order randomized in a different order.

```<code>> order.matrix
     [,1]    [,2]    [,3]
[1,] "Anger" "Happy" "Sad"
[2,] "Happy" "Sad"   "Anger"
[3,] "Sad"   "Anger" "Happy"
</code>```

I have stored the responses on the items in a dataframe:

```<code>> df.responses
  Anger Happy Sad
1     1     2   3
2     3     2   0
3     9     2   1
</code>```

Now, I want to change the order of the responses in df.responses, such that they are analogue to the order of items in the order.matrix, for each row. (As a result, the column names of df.responses shouldn't be in the resulting df anymore.)
The result in this example should look like this:

```<code>> df.result
  V1 V2 V3
1  1  2  3
2  2  0  3
3  1  9  2
</code>```

How can/should I do this?

EDIT, due to comment: I want to replace the item names in order.matrix by its corresponding value in df.responses

答:
A base R option is to use mapply, i.e.,

```<code>df.result <- t(mapply(function(v,k) v[k],
                      data.frame(t(df.responses)),
                      data.frame(t(order.matrix)),
                      USE.NAMES = F
                      )
               )
</code>```

such that

```<code>> df.responses
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    2    0    3
[3,]    1    9    2
</code>```

Body:
I have a matrix where I stored the order of items of a questionnaire, where the first column contains the name of the item that is first shown, the second column has the second shown item, etc. Each row in this matrix represents a new questionnaire, with the same items but with the order randomized in a different order.

> order.matrix
     [,1]    [,2]    [,3]
[1,] "Anger" "Happy" "Sad"
[2,] "Happy" "Sad"   "Anger"
[3,] "Sad"   "Anger" "Happy"

I have stored the responses on the items in a dataframe:

> df.responses
  Anger Happy Sad
1     1     2   3
2     3     2   0
3     9     2   1

Now, I want to change the order of the responses in df.responses, such that they are analogue to the order of items in the order.matrix, for each row. (As a result, the column names of df.responses shouldn't be in the resulting df anymore.)
The result in this example should look like this:

> df.result
  V1 V2 V3
1  1  2  3
2  2  0  3
3  1  9  2

How can/should I do this?

EDIT, due to comment: I want to replace the item names in order.matrix by its corresponding value in df.responses

Body:
A base R option is to use mapply, i.e.,

df.result <- t(mapply(function(v,k) v[k],
                      data.frame(t(df.responses)),
                      data.frame(t(order.matrix)),
                      USE.NAMES = F
                      )
               )

such that

> df.responses
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    2    0    3
[3,]    1    9    2


问:
Insert multiple images randomly into different table cells using Javascript
I'm pretty new in Javascript/Jquery, currently still learning and so here I am seeking help. I would like to insert different images randomly (the location changes everytime i refresh the page) into table cells using Javascript/Jquery and not touching HTML/CSS.

I have tried using append to insert the images, however every image appears in all table cells which weren't what I wanted. I have also tried backgroundrepeat: no repeat but it doesn't work. It would be good if there's some simple coding that would work, so it will be easier for me to understand.

I can't use getElementById cause my separated js file can't detect the ID from the HTML file

HTML:

```<code><table id="Image">
<tr>
<td><div class="ImageHere" value=1></div></td>
<td><div class="ImageHere" value=2></div></td>
<td><div class="ImageHere" value=3></div></td>
<td><div class="ImageHere" value=4></div></td>
<td><div class="ImageHere" value=5></div></td>
</tr>
<tr>
<td><div class="ImageHere" value=6></div></td>
<td><div class="ImageHere" value=7></div></td>
<td><div class="ImageHere" value=8></div></td>
<td><div class="ImageHere" value=9></div></td>
<td><div class="ImageHere" value=10></div></td>
</tr>
</table>
</code>```

my jQuery best try:

```<code>$(document).ready(function(){
    $(".ImageHere").append("<img src='images/card.jpg' width='100%' height='100%' />" ) });
});
</code>```

答:
You can first define array of your images which need to be inserted , then make this array arrange values randomly , then using .forEach JS function Or .each JQuery Function to loop and insert these images into your table randomly

let's start with this code and read my comments on it to understand what i mean better

var images= ['image1.jpg','test.png','logo.png'] // array of your images
var randomArr = [] // new empty array which will have random values
for(var i= 0 ; i < images.length;i++){
 var item = images[Math.floor(Math.random() * images.length)]
  // this condition to prevent doublicate elements
 if(!randomArr.includes(item)){
  randomArr.push(item)
 }else{
  i = i - 1;
 }
}

// now we have new array with random images
// lets start to insert these images into table
$("table#Image .ImageHere").each(function(index, value){
  if(index > randomArr.length) {
    // check if elements more than array of images and set default image
    $(this).html("")
    }else{
    $(this).html("")
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<table id="Image">
<tr>
<td><div class="ImageHere" value=1>ddd</div></td>
<td><div class="ImageHere" value=2></div></td>
<td><div class="ImageHere" value=3></div></td>
<td><div class="ImageHere" value=4></div></td>
<td><div class="ImageHere" value=5></div></td>
</tr>
<tr>
<td><div class="ImageHere" value=6></div></td>
<td><div class="ImageHere" value=7></div></td>
<td><div class="ImageHere" value=8></div></td>
<td><div class="ImageHere" value=9></div></td>
<td><div class="ImageHere" value=10></div></td>
</tr>
</table></code>```

Body:
I'm pretty new in Javascript/Jquery, currently still learning and so here I am seeking help. I would like to insert different images randomly (the location changes everytime i refresh the page) into table cells using Javascript/Jquery and not touching HTML/CSS.

I have tried using append to insert the images, however every image appears in all table cells which weren't what I wanted. I have also tried backgroundrepeat: no repeat but it doesn't work. It would be good if there's some simple coding that would work, so it will be easier for me to understand.

I can't use getElementById cause my separated js file can't detect the ID from the HTML file

HTML:

my jQuery best try:

$(document).ready(function(){
    $(".ImageHere").append("" ) });
});

Body:
You can first define array of your images which need to be inserted , then make this array arrange values randomly , then using .forEach JS function Or .each JQuery Function to loop and insert these images into your table randomly

let's start with this code and read my comments on it to understand what i mean better

var images= ['image1.jpg','test.png','logo.png'] // array of your images
var randomArr = [] // new empty array which will have random values
for(var i= 0 ; i < images.length;i++){
 var item = images[Math.floor(Math.random() * images.length)]
  // this condition to prevent doublicate elements
 if(!randomArr.includes(item)){
  randomArr.push(item)
 }else{
  i = i - 1;
 }
}

// now we have new array with random images
// lets start to insert these images into table
$("table#Image .ImageHere").each(function(index, value){
  if(index > randomArr.length) {
    // check if elements more than array of images and set default image
    $(this).html("<img src='default.jpg' />")
    }else{
    $(this).html("<img src='"+randomArr[index]+"' />")
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<table id="Image">
<tr>
<td><div class="ImageHere" value=1>ddd</div></td>
<td><div class="ImageHere" value=2></div></td>
<td><div class="ImageHere" value=3></div></td>
<td><div class="ImageHere" value=4></div></td>
<td><div class="ImageHere" value=5></div></td>
</tr>
<tr>
<td><div class="ImageHere" value=6></div></td>
<td><div class="ImageHere" value=7></div></td>
<td><div class="ImageHere" value=8></div></td>
<td><div class="ImageHere" value=9></div></td>
<td><div class="ImageHere" value=10></div></td>
</tr>
</table>


问:
Python Flask script auto-closes when run as .pyw file (workaround included)

Problem

I've created a basic python script, using flask to render an HTML page. On Windows 10, the script works perfectly as a *.py file, but when run as a *.pyw file, the page is not rendered.

In Task Manager, instances of python are opened and closed within seconds after running the script as *.pyw.

Code

```<code>from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def main():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True, host="0.0.0.0", port=80)
</code>```

Workaround

Run the *.py version with the following lines added to the code:

```<code>import ctypes
...
...
...
if __name__ == '__main__':
  cytypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), 0)
  app.run(debug=True, host="0.0.0.0", port=80)
</code>```

Code above hides the console, and starts the flask app successfully.

However, I am still interested in an explanation as to why the *.pyw method won't work, if anyone has an idea.

答: .pyw-files would ran on pythonw.exe rather than python.exe. The difference is, that pythonw.exe does not run in a console by default and runs asynchronous. This would mean that flask starts and runs in the background untill everything else terminates. Since you to not have anything else in your application, the programm ends directly.

Body:
Problem

I've created a basic python script, using flask to render an HTML page. On Windows 10, the script works perfectly as a *.py file, but when run as a *.pyw file, the page is not rendered.

In Task Manager, instances of python are opened and closed within seconds after running the script as *.pyw.

Code

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def main():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True, host="0.0.0.0", port=80)

Workaround

Run the *.py version with the following lines added to the code:

import ctypes
...
...
...
if __name__ == '__main__':
  cytypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), 0)
  app.run(debug=True, host="0.0.0.0", port=80)

Code above hides the console, and starts the flask app successfully.

However, I am still interested in an explanation as to why the *.pyw method won't work, if anyone has an idea.


问:
Export bitfield to an array
I've declared this bit field. What I am trying to do is to get the whole value of the bitfield in binary and convert it into an array so I can use the index and address every '1' value.

```<code>union{
    struct shape{
        uint8_t p0 : 1;
        uint8_t p1 : 1;
        uint8_t p2 : 1;
        uint8_t p3 : 1;
        uint8_t p4 : 1;
        uint8_t p5 : 1;
        uint8_t p6 : 1;
        uint8_t p7 : 1;
    };
    uint8_t row;
}rows[8*2+4];
</code>```

what I am trying to do is to export the bitfield to have it an array like uint8_t tab[8] = {0,1,1,0,0,1,0,1};

Is that even possible? Any tips?
Thanks in advance

答:
If you are, in fact, starting from a uint8_t, then you don't need or want to fiddle about with bit-fields...

...assuming (a) Little-Endian and (b) that you can write an unaligned uint64_t:

```<code>void explode_byte(uint8_t r[8], uint8_t b)
{
  uint64_t x ;

  x  = b ;
  x |= x << (32 - 4) ;
  x |= x << (16 - 2) ;
  x |= x << ( 8 - 1) ;

  *(uint64_t*)r = x & (uint64_t)0x0101010101010101 ;
}
</code>```

See "Hacker's Delight" by Henry S. Warren :-)

But, if you are starting with the bit-fields, then you have a quite different problem: you really cannot make any assumptions about how bit fields are stored -- all you can do is read/write individual fields.  So you have no choice but to copy each bit-field to its respective byte... as given in other answers.

Title: Export bitfield to an array

Body:
I've declared this bit field. What I am trying to do is to get the whole value of the bitfield in binary and convert it into an array so I can use the index and address every '1' value.

union{
    struct shape{
        uint8_t p0 : 1;
        uint8_t p1 : 1;
        uint8_t p2 : 1;
        uint8_t p3 : 1;
        uint8_t p4 : 1;
        uint8_t p5 : 1;
        uint8_t p6 : 1;
        uint8_t p7 : 1;
    };
    uint8_t row;
}rows[8*2+4];

what I am trying to do is to export the bitfield to have it an array like uint8_t tab[8] = {0,1,1,0,0,1,0,1};

Is that even possible? Any tips?
Thanks in advance

Body:
If you are, in fact, starting from a uint8_t, then you don't need or want to fiddle about with bit-fields...

...assuming (a) Little-Endian and (b) that you can write an unaligned uint64_t:

void explode_byte(uint8_t r[8], uint8_t b)
{
  uint64_t x ;

  x  = b ;
  x |= x << (32 - 4) ;
  x |= x << (16 - 2) ;
  x |= x << ( 8 - 1) ;

  *(uint64_t*)r = x & (uint64_t)0x0101010101010101 ;
}

See "Hacker's Delight" by Henry S. Warren :-)

But, if you are starting with the bit-fields, then you have a quite different problem: you really cannot make any assumptions about how bit fields are stored -- all you can do is read/write individual fields.  So you have no choice but to copy each bit-field to its respective byte... as given in other answers.


问:
Spring Scoped Prototype bean instances are equals
I created two beans, @Signleton beanA that has @Prototybe beanB as a dependency.
To make sure that every time beanA is called beanB is initialized again I annotaed beanB with

```<code>Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE, proxyMode = ScopedProxyMode.TARGET_CLASS)
</code>```

To make sure that everything is working fine, I made a test that verifies that if beanB is recived two times, there're two different instances of it:

```<code>@Test()
void testBean() throws IllegalAccessException {

    Field beanBField = ReflectionUtils.findField(BeanA.class, "beanB");
    ReflectionUtils.makeAccessible(beanBField);

    BeanA beanA1 = applicationContext.getBean(BeanA.class);
    System.out.println(beanA1); // my.package.BeanA@4b41e4dd
    BeanB beanB1 = (PMToJupiterMapper) beanBField.get(beanA1);
    System.out.println(beanB1); // my.package.BeanB@42463763

    BeanA beanA2 = applicationContext.getBean(BeanA.class);
    System.out.println(beanA2); // my.package.BeanA@4b41e4dd
    BeanB beanB2 = (PMToJupiterMapper) beanBField.get(beanA2);
    System.out.println(beanB2); // my.package.BeanB@59f63e24

    assertEquals(beanA1, beanA2); // Is OK as expected
    System.out.println(beanB1.equals(beanB2)); // WHY IS TRUE?
    System.out.println(beanB1 == beanB2);// WHY IS TRUE?
}
</code>```

beanA instances are the same, as expected and have the same hash.
But why in this case despite beanB hashes are different, equals and == between two instance of a bean still return true?

答:
i think they must be equals spring beans are singletons

here's a definition

The singleton scope:the Spring IoC container creates exactly one instance of the object defined by that bean definition. This single instance is stored in a cache of such singleton beans, and all subsequent requests and references for that named bean return the cached object.

The prototype scope
the Spring IoC container creates a new bean instance of the object every time a request for that specific bean is made. As a rule, use the prototype scope for all state-full beans and the singleton scope for stateless beans.

Body:
I created two beans, @Signleton beanA that has @Prototybe beanB as a dependency.
To make sure that every time beanA is called beanB is initialized again I annotaed beanB with

Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE, proxyMode = ScopedProxyMode.TARGET_CLASS)

To make sure that everything is working fine, I made a test that verifies that if beanB is recived two times, there're two different instances of it:

@Test()
void testBean() throws IllegalAccessException {

    Field beanBField = ReflectionUtils.findField(BeanA.class, "beanB");
    ReflectionUtils.makeAccessible(beanBField);

    BeanA beanA1 = applicationContext.getBean(BeanA.class);
    System.out.println(beanA1); // my.package.BeanA@4b41e4dd
    BeanB beanB1 = (PMToJupiterMapper) beanBField.get(beanA1);
    System.out.println(beanB1); // my.package.BeanB@42463763

    BeanA beanA2 = applicationContext.getBean(BeanA.class);
    System.out.println(beanA2); // my.package.BeanA@4b41e4dd
    BeanB beanB2 = (PMToJupiterMapper) beanBField.get(beanA2);
    System.out.println(beanB2); // my.package.BeanB@59f63e24

    assertEquals(beanA1, beanA2); // Is OK as expected
    System.out.println(beanB1.equals(beanB2)); // WHY IS TRUE?
    System.out.println(beanB1 == beanB2);// WHY IS TRUE?
}

beanA instances are the same, as expected and have the same hash.
But why in this case despite beanB hashes are different, equals and == between two instance of a bean still return true?


问:
upload files via iPad
One of our users just notified us that our web application works very well through Safari on the iPad (or whatever the default browser is -- I assume Safari).  The only thing that doesn't work is the file upload part.

Our web application enables our users to attach files in various parts of the system.

I was thinking about this.  The iPhone takes pictures, but doesn't really give me the ability to upload them via a standard web interface (where you click a button, choose a file, upload the file, etc).

Is this even possible?  Or is the only way to upload files from an iPhone/iPad via a custom app written for the device?

Is there a way to upload a file on an iPad via the web browser?

答: There are some replacement web browsers you can get from the app store that allow you to upload.  You use them instead of Safari.  One example is iCab Mobile.</p>

ContentLicense: CC BY-SA 2.5

Title: upload files via iPad


问:
DLL load failed: The specific module could not be found (VSCode, Numpy)
Error occurs upon import numpy as np; command works fine when typed directly in terminal, but fails when ran via Code Runner. My steps to reproduce below.

Output of import sys; print(sys.version) is 3.7.5 (default, Oct 31 2019, 15:18:51) [MSC v.1916 64 bit (AMD64)]. VSCode shows it's running the expected Python interpreter: Python 3.7.5 64-bit ('vsc': conda) at bottom-left pane (see clip). -- Brief video demo.

For a complete list of enabled extensions and contents of settings.json, see relevant Git.

What is the problem, and how to fix?

Env info: Windows 10 x64, Anaconda 10/19 (virtual env), VSCode 1.41.1

Steps to reproduce:

```<code>conda create --name vsc
conda activate vsc
conda install python==3.7.5
conda install numpy
# in VSCode: import numpy as np, etc
</code>```

Full traceback:

Traceback (most recent call last):
  File "D:\Anaconda\envs\vsc\lib\site-packages\numpy\core\__init__.py", line 17, in <module>
    from . import multiarray
  File "D:\Anaconda\envs\vsc\lib\site-packages\numpy\core\multiarray.py", line 14, in <module>
    from . import overrides
  File "D:\Anaconda\envs\vsc\lib\site-packages\numpy\core\overrides.py", line 7, in <module>
    from numpy.core._multiarray_umath import (
ImportError: DLL load failed: The specified module could not be found.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:\Desktop\School\Python\vscode\HelloWorld\app.py", line 1, in <module>
    import numpy as np
  File "D:\Anaconda\envs\vsc\lib\site-packages\numpy\__init__.py", line 142, in <module>
    from . import core
  File "D:\Anaconda\envs\vsc\lib\site-packages\numpy\core\__init__.py", line 47, in <module>
    raise ImportError(msg)
ImportError:
```

<hr>

<p><strong>EDIT</strong>: added the following to <code>settings.json</code> per James's suggestion:</p>

```"terminal.integrated.shell.windows": "C:\\Windows\\System32\\cmd.exe",
"terminal.integrated.shellArgs.windows": ["/K", "D:\\Anaconda\\Scripts\\activate.bat D:\\Anaconda"],
"python.condaPath": "D:\\Anaconda\\Scripts\\conda.exe"
```

答:
I had the same problem. In my case Anaconda3 and VS Code were installed separately. Here are the steps that worked for me to fix the problem:

Completely uninstall VS Code including any user settings/cache and start menu entries

Re-install VS Code from Anaconda Navigator

Launch Anaconda Prompt and activate whichever environment I want to use through conda activate myenv

Launch VS Code from Anaconda Prompt by typing code

It will find the numpy package path in your environment now.

Body:
Error occurs upon import numpy as np; command works fine when typed directly in terminal, but fails when ran via Code Runner. My steps to reproduce below.

Output of import sys; print(sys.version) is 3.7.5 (default, Oct 31 2019, 15:18:51) [MSC v.1916 64 bit (AMD64)]. VSCode shows it's running the expected Python interpreter: Python 3.7.5 64-bit ('vsc': conda) at bottom-left pane (see clip). -- Brief video demo.

For a complete list of enabled extensions and contents of settings.json, see relevant Git.

What is the problem, and how to fix?

Env info: Windows 10 x64, Anaconda 10/19 (virtual env), VSCode 1.41.1

Steps to reproduce:

conda create --name vsc
conda activate vsc
conda install python==3.7.5
conda install numpy
# in VSCode: import numpy as np, etc

Full traceback:

Traceback (most recent call last):
  File "D:\Anaconda\envs\vsc\lib\site-packages\numpy\core\__init__.py", line 17, in <module>
    from . import multiarray
  File "D:\Anaconda\envs\vsc\lib\site-packages\numpy\core\multiarray.py", line 14, in <module>
    from . import overrides
  File "D:\Anaconda\envs\vsc\lib\site-packages\numpy\core\overrides.py", line 7, in <module>
    from numpy.core._multiarray_umath import (
ImportError: DLL load failed: The specified module could not be found.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:\Desktop\School\Python\vscode\HelloWorld\app.py", line 1, in <module>
    import numpy as np
  File "D:\Anaconda\envs\vsc\lib\site-packages\numpy\__init__.py", line 142, in <module>
    from . import core
  File "D:\Anaconda\envs\vsc\lib\site-packages\numpy\core\__init__.py", line 47, in <module>
    raise ImportError(msg)
ImportError:

EDIT: added the following to settings.json per James's suggestion:

"terminal.integrated.shell.windows": "C:\\Windows\\System32\\cmd.exe",
"terminal.integrated.shellArgs.windows": ["/K", "D:\\Anaconda\\Scripts\\activate.bat D:\\Anaconda"],
"python.condaPath": "D:\\Anaconda\\Scripts\\conda.exe"


问:
Creating an update trigger that uses data from 2 tables
Okay, so I have made the changes that i know how to make but I am still stuck at how to bring the accessory table in. For those first time here, I'm trying to create a trigger that checks that prices are appropriately changed. However, one of the columns I need comes from another table and I'm not quite sure how to declare that variable. This is my current attempt.

The ACCESSORY table is a child of the PRODUCT table being connected with ProductCode and has only 1 other column called Class which stands for classification. The trigger i created is currently for the PRODUCT table as that is where all the prices are recorded

```<code>CREATE TRIGGER PriceCheck1
ON PRODUCT
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
DECLARE @ProductCode        AS  Char(6),
        @ProductName        AS  VarChar(50),
        @StockLevel         AS  Int,
        @OldPrice           AS  float, @NewPrice AS float,
        @ProductType        AS  VarChar(9)
        --@Class                AS VarChar(20)
/*SELECT i.ProductCode, i.ProductName, i.ProductStockLevel, i.ProductPrice, i.ProductType, a.Class
INTO #TempTable
FROM inserted i JOIN ACCESSORY a ON i.ProductCode = a.ProductCode*/

SELECT  @ProductCode = ProductCode, @ProductName = ProductName,
        @StockLevel = ProductStockLevel, @NewPrice = ProductPrice,
        @ProductType = ProductType --@Class = Class
FROM    inserted;--FROM    #TempTable

SELECT  @ProductCode = ProductCode, @ProductName = ProductName,
        @StockLevel = ProductStockLevel, @OldPrice = ProductPrice,
        @ProductType = ProductType
FROM    deleted;

IF UPDATE(ProductPrice)
BEGIN
    IF (@ProductType = 'Food Item' AND @NewPrice > 200)
    BEGIN
        RAISERROR('The price of food item cannot exceed $200.', 16, 1)
        ROLLBACK TRANSACTION
    END
    ELSE IF (@ProductType = 'Accessory' AND @NewPrice < 50)--AND @Class = 'Bed and Bedding'
    BEGIN
        RAISERROR('The price of any accessory with a classification that includes the word bed cannot be less than $50.', 16, 1)
        ROLLBACK TRANSACTION
    END
    ELSE
        print 'Price of Product Code ' + @ProductCode + ' has been changed from $' + Cast(@OldPrice AS nVarChar(10)) + ' to $' + Cast(@NewPrice AS nVarChar(10)) + '.'
END
END
</code>```

The Areas that i commented out are the codes i tried. The trigger works fine without the commented out areas but now when i tried to bring the accessory table in, the trigger doesn't even fire when i update the table.

答:
Go back. Start over! This is the wrong general approach. First, stop blindly applying a pattern. Using  to create a temp table and then referencing that temp table serves no useful purpose here.

Next, you assume a single row is affected. That is a very common mistake and has been discussed many, many times. Go learn from past discussions - something you should be doing for every question or problem you might have.

When you consider that multiple rows can be affected, you will realize that your attempt to provide a "beautiful" error message is impossible. So just don't do that. In fact, don't attempt that regardless of the number of rows. The client application should render the error as needed to the user. Let it choose the words and language and format any needed values according to the user's preferences.

Next, you are developing lazy coding habits. This will only create more work over time. Your second-to-last statement inserts a row into Product. ALWAYS use a column list in an insert statement.

Next, returning to that next-to-last statement. Why are you inserting a row into the table on which this trigger is defined. That is most likely an error. Maybe you intended to update the updated rows? Maybe you actually have a separate audit table? Questions like these are best answered by including a MCVE.

Next, let's look at one of your statements. You have:

```<code>SELECT @ProductCode = 'Code', @ProductName = 'Name',
    @ProductStockLevel = 'Stock Level', @OldPrice = 'Price',
    @ProductType = 'Type'
    FROM #TempTable
</code>```

What do you think this does? It appears you tried to assign values to a number of variables - values that should come from a row in the table. But does it? Nope - it simply assigns (or tries to - this will generate runtime errors) the literals you have used.

So finally something that might work. I say "might" because you may change your direction when you see this in action. Below is a best guess (with pseudo code) that looks for just one of the problem conditions. It can be expanded by adding logic to the case expression. I leave that to you.

```<code>if exists (select * from inserted as ins
   inner join deleted as del
      on ins.<ID columns?> = del.<ID columns?>
   inner join dbo.ACCESSORY as acc
      on ins.ProductCode  = acc.ProductCode
   where (case when acc.Type = 'Food Item' and ins.price > 200 then 1 else 0 end) = 1)
begin
    throw error
end;
</code>```

Notice that I joined the inserted and deleted tables. Your logic does actually need it but I included it simply to show how it is done - for example, if you wanted to restrict the "size" of the change. If you don't need to refer to the prior values for each row it can be removed. If you actually needed to update some "audit" column in the Product table for every changed value, you would use the same join logic to populate this column.

One final comment. You have:

```<code>RAISERROR ('The price of any accessory with a classification that includes the word bed cannot be less than $50.')
</code>```

Your error messages should not lie or mislead. That message does not accurately describe the logic you tried to use.

Body:
Okay, so I have made the changes that i know how to make but I am still stuck at how to bring the accessory table in. For those first time here, I'm trying to create a trigger that checks that prices are appropriately changed. However, one of the columns I need comes from another table and I'm not quite sure how to declare that variable. This is my current attempt.

The ACCESSORY table is a child of the PRODUCT table being connected with ProductCode and has only 1 other column called Class which stands for classification. The trigger i created is currently for the PRODUCT table as that is where all the prices are recorded

CREATE TRIGGER PriceCheck1
ON PRODUCT
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
DECLARE @ProductCode        AS  Char(6),
        @ProductName        AS  VarChar(50),
        @StockLevel         AS  Int,
        @OldPrice           AS  float, @NewPrice AS float,
        @ProductType        AS  VarChar(9)
        --@Class                AS VarChar(20)
/*SELECT i.ProductCode, i.ProductName, i.ProductStockLevel, i.ProductPrice, i.ProductType, a.Class
INTO #TempTable
FROM inserted i JOIN ACCESSORY a ON i.ProductCode = a.ProductCode*/

SELECT  @ProductCode = ProductCode, @ProductName = ProductName,
        @StockLevel = ProductStockLevel, @NewPrice = ProductPrice,
        @ProductType = ProductType --@Class = Class
FROM    inserted;--FROM    #TempTable

SELECT  @ProductCode = ProductCode, @ProductName = ProductName,
        @StockLevel = ProductStockLevel, @OldPrice = ProductPrice,
        @ProductType = ProductType
FROM    deleted;

IF UPDATE(ProductPrice)
BEGIN
    IF (@ProductType = 'Food Item' AND @NewPrice > 200)
    BEGIN
        RAISERROR('The price of food item cannot exceed $200.', 16, 1)
        ROLLBACK TRANSACTION
    END
    ELSE IF (@ProductType = 'Accessory' AND @NewPrice < 50)--AND @Class = 'Bed and Bedding'
    BEGIN
        RAISERROR('The price of any accessory with a classification that includes the word bed cannot be less than $50.', 16, 1)
        ROLLBACK TRANSACTION
    END
    ELSE
        print 'Price of Product Code ' + @ProductCode + ' has been changed from $' + Cast(@OldPrice AS nVarChar(10)) + ' to $' + Cast(@NewPrice AS nVarChar(10)) + '.'
END
END

The Areas that i commented out are the codes i tried. The trigger works fine without the commented out areas but now when i tried to bring the accessory table in, the trigger doesn't even fire when i update the table.

Body:
Go back. Start over! This is the wrong general approach. First, stop blindly applying a pattern. Using  to create a temp table and then referencing that temp table serves no useful purpose here.

Next, you assume a single row is affected. That is a very common mistake and has been discussed many, many times. Go learn from past discussions - something you should be doing for every question or problem you might have.

When you consider that multiple rows can be affected, you will realize that your attempt to provide a "beautiful" error message is impossible. So just don't do that. In fact, don't attempt that regardless of the number of rows. The client application should render the error as needed to the user. Let it choose the words and language and format any needed values according to the user's preferences.

Next, you are developing lazy coding habits. This will only create more work over time. Your second-to-last statement inserts a row into Product. ALWAYS use a column list in an insert statement.

Next, returning to that next-to-last statement. Why are you inserting a row into the table on which this trigger is defined. That is most likely an error. Maybe you intended to update the updated rows? Maybe you actually have a separate audit table? Questions like these are best answered by including a MCVE.

Next, let's look at one of your statements. You have:

SELECT @ProductCode = 'Code', @ProductName = 'Name',
    @ProductStockLevel = 'Stock Level', @OldPrice = 'Price',
    @ProductType = 'Type'
    FROM #TempTable

What do you think this does? It appears you tried to assign values to a number of variables - values that should come from a row in the table. But does it? Nope - it simply assigns (or tries to - this will generate runtime errors) the literals you have used.

So finally something that might work. I say "might" because you may change your direction when you see this in action. Below is a best guess (with pseudo code) that looks for just one of the problem conditions. It can be expanded by adding logic to the case expression. I leave that to you.

if exists (select * from inserted as ins
   inner join deleted as del
      on ins.<ID columns?> = del.<ID columns?>
   inner join dbo.ACCESSORY as acc
      on ins.ProductCode  = acc.ProductCode
   where (case when acc.Type = 'Food Item' and ins.price > 200 then 1 else 0 end) = 1)
begin
    throw error
end;

Notice that I joined the inserted and deleted tables. Your logic does actually need it but I included it simply to show how it is done - for example, if you wanted to restrict the "size" of the change. If you don't need to refer to the prior values for each row it can be removed. If you actually needed to update some "audit" column in the Product table for every changed value, you would use the same join logic to populate this column.

One final comment. You have:

RAISERROR ('The price of any accessory with a classification that includes the word bed cannot be less than $50.')

Your error messages should not lie or mislead. That message does not accurately describe the logic you tried to use.


问:
Maven Antrun: How to enable skipped task?
I have a maven-project where "need" to start a program with antrun (the need isn't reflected by the example below). By default antrun should be disabled as the example shows.

```<code><execution>
  <id>default-cli</id>
  <phase>test</phase>
  <configuration>
  <skip>true</skip>
  <tasks>
    <delete dir="target/dependencies" />
    <copy todir="target/dependencies" flatten="true">
  </tasks>
</execution>

</code>```

But in some of the automated environments we would like to enable it again. So I expected

```<code>mvn test -Dmaven.antrun.skip=false
</code>```

to do the trick but that maven.antrun.skip only seems to work to disable the task and not to enable it again. The log just says "Skipping Antrun execution".

I also tried to run the task with

```<code>mvn antrun:run@default-cli
</code>```

but the message stays the same.

So, how to disable antrun as default to be able to run it ad-hoc when needed?

Java8, Maven3.6, Antrun1.8

答:
Define your own property in properties like

<properties>
   <skip-default-cli>true</skip-default-cli>
</properties
```

Then, inside the execution, set <skip>${skip-default-cli}</skip>.

On command line, you add -Dskip-default-cli=false to activate the run.

Body:
I have a maven-project where "need" to start a program with antrun (the need isn't reflected by the example below). By default antrun should be disabled as the example shows.

<execution>
  <id>default-cli</id>
  <phase>test</phase>
  <configuration>
  <skip>true</skip>
  <tasks>
    <delete dir="target/dependencies" />
    <copy todir="target/dependencies" flatten="true">
  </tasks>
</execution>

But in some of the automated environments we would like to enable it again. So I expected

mvn test -Dmaven.antrun.skip=false

to do the trick but that maven.antrun.skip only seems to work to disable the task and not to enable it again. The log just says "Skipping Antrun execution".

I also tried to run the task with

mvn antrun:run@default-cli

but the message stays the same.

So, how to disable antrun as default to be able to run it ad-hoc when needed?

Java8, Maven3.6, Antrun1.8

Body:
Define your own property in properties like

<properties>
   <skip-default-cli>true</skip-default-cli>
</properties

Then, inside the execution, set <skip>${skip-default-cli}</skip>.

On command line, you add -Dskip-default-cli=false to activate the run.


问:
Google API Vision with google cloud storage
I know it's possible to use Google API vision to find similar images on the web.
My goal is to find similar images based on my database of images.
I don't want similar images on the web.

Is it possible?

If yes, can you guide me with some links or some advices?

Thanks!

答:
You can upload your images to google cloud and do the job.
You have 2 choices: Google product search or AutoML. With product search you can compare an image with a set of images of products. You will find product form image.
You can also use AutoMl, upload some images and train them. You can predict images with AutoMl API in this case. </p>


问:
IS there a gui designer for wxwidgets in linux with Eclipse?
I want to build a GUI application using C++ and wxWidgets.
The problem is that I can not find an IDE with GUI (Form Designer) to use. I hope if eclipse has some thing like the QT designer.

any solutions ???

答: The wxsmith plugin for Code::Blocks is worth checking out.  It would mean switching IDEs, but C::B is cross-platform just like Eclipse.</p>


问:
countdown from 200 to 0 in multiples of x. X is a value input by the user (python)
I wanted to make a program that counts down from 200 to 0 in multiples of "x". "x" is a number that the user inputs. For example, if the user inputs "5", I want the program to print a list that begins with 200,195,190,185,180... and ends with 0. This is the code I have written so far:

```<code>rows = int(input('What number? '))
i = 1
for i in range(200,-1,rows):
 print (200- i * rows)
i = i + 1
</code>```

Right now it's telling me that "for i in range" can only have one argument, but when I make the argument 0, it doesn't run. When I make the argument 200, the program subtracts "x" from two hundred 200 times. How can I get the program to stop the list at 0?

答:
What you need to do is negate rows like this:</p>

```<code>rows = int(input('What number? '))

for i in range(200, -1, -rows):
    print(i)
</code>```

Body:
I wanted to make a program that counts down from 200 to 0 in multiples of "x". "x" is a number that the user inputs. For example, if the user inputs "5", I want the program to print a list that begins with 200,195,190,185,180... and ends with 0. This is the code I have written so far:

rows = int(input('What number? '))
i = 1
for i in range(200,-1,rows):
 print (200- i * rows)
i = i + 1

Right now it's telling me that "for i in range" can only have one argument, but when I make the argument 0, it doesn't run. When I make the argument 200, the program subtracts "x" from two hundred 200 times. How can I get the program to stop the list at 0?

Body:
What you need to do is negate rows like this:

rows = int(input('What number? '))

for i in range(200, -1, -rows):
    print(i)


问:
Linq Query to Sum into new list
I want to create a 2nd list from 1st list to show the sum with descending order.</p>

```<code>1st list :
     ID               Value
    1                  20
    2                  40
    3                  10

2nd List:
 ID               Value
1                  70
2                  50
3                  10
</code>```

答:
```<code>  var list1 = new [] { new { id = 1, Value = 20 },  new { id = 2, Value = 40 }, new { id = 3, Value = 10 } }.ToList();

        var list2 = list1.
                        Select(x => new { x.id,
                                          Value = list1.Where(y => y.id >= x.id).Sum(z => z.Value) }).
                        OrderByDescending(x=>x.Value).ToList();
</code>```

Title: Linq Query to Sum into new list

Body:
I want to create a 2nd list from 1st list to show the sum with descending order.

1st list :
     ID               Value
    1                  20
    2                  40
    3                  10

2nd List:
 ID               Value
1                  70
2                  50
3                  10


问:
Can anyone suggest a faster method for creaing this array?
I am creating this array for my shader and this step is very slow as it constitutes a nested for loop. Currently this methos takes approx 1 sec to create this. Can anyone suggest any faster method for creating this array.</p>

```<code>import numpy as np

elems = []
b = 23503
a = 24

for i in range(0, a - 1):
    for j in range(0, b - 1):
        elems += [j + b * i, j + b * i + 1, j + b * (i + 1)]
        elems += [j + b * (i + 1), j + b * (i + 1) + 1, j + b * i + 1]

elems = np.array(elems, dtype=np.int32)
</code>```

答:
You can use meshgrid to cover the i and j iterations and then to an outer add to get the inner shading. Using ravel in the end to get a 1D array.

```<code>inner = np.array([0, 1, b, b, b+1, 1], dtype="int32")
j, i = np.meshgrid(np.arange(b-1), np.arange(a-1))
elems = np.add.outer((j+b*i), inner).ravel()
</code>```

or with a one-liner:

```<code>elems = ([0, 1, b, b, b+1, 1]+np.arange(b-1)[:, None]+b*np.arange(a-1)[:,None, None]).ravel()
</code>```

Finishes in <6ms on my computer

```<code>In [9]: %timeit ([0, 1, b, b, b+1, 1]+np.arange(b-1)[:,None]+b*np.arange(a-1)[:
   ...: ,None, None]).ravel()
5.23 ms ± 112 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [10]: %timeit create_shader_array(a, b)
29.8 ms ± 176 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
</code>```

Body:
I am creating this array for my shader and this step is very slow as it constitutes a nested for loop. Currently this methos takes approx 1 sec to create this. Can anyone suggest any faster method for creating this array.

import numpy as np

elems = []
b = 23503
a = 24

for i in range(0, a - 1):
    for j in range(0, b - 1):
        elems += [j + b * i, j + b * i + 1, j + b * (i + 1)]
        elems += [j + b * (i + 1), j + b * (i + 1) + 1, j + b * i + 1]

elems = np.array(elems, dtype=np.int32)

Body:
You can use meshgrid to cover the i and j iterations and then to an outer add to get the inner shading. Using ravel in the end to get a 1D array.

inner = np.array([0, 1, b, b, b+1, 1], dtype="int32")
j, i = np.meshgrid(np.arange(b-1), np.arange(a-1))
elems = np.add.outer((j+b*i), inner).ravel()

or with a one-liner:

elems = ([0, 1, b, b, b+1, 1]+np.arange(b-1)[:, None]+b*np.arange(a-1)[:,None, None]).ravel()

Finishes in <6ms on my computer

In [9]: %timeit ([0, 1, b, b, b+1, 1]+np.arange(b-1)[:,None]+b*np.arange(a-1)[:
   ...: ,None, None]).ravel()
5.23 ms ± 112 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [10]: %timeit create_shader_array(a, b)
29.8 ms ± 176 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)


问:
Deleting large continuous blocks of lines separated by empty lines
I have a large dataset, composed of text in the following form. </p>

```<code>Vil [SENT]2 [POS]AUX [NUM]4 [DEP]aux O
du [SENT]2 [POS]PRON [NUM]4 [DEP]nsubj O
gerne [SENT]2 [POS]ADV [NUM]4 [DEP]advmod O
arbejde [SENT]2 [POS]VERB [NUM]0 [DEP]root O
med [SENT]2 [POS]ADP [NUM]9 [DEP]case O
et [SENT]2 [POS]DET [NUM]9 [DEP]det O
globalt [SENT]2 [POS]ADV [NUM]8 [DEP]advmod O
anerkendt [SENT]2 [POS]VERB [NUM]9 [DEP]amod O
brand [SENT]2 [POS]NOUN [NUM]4 [DEP]obl O
? [SENT]2 [POS]PUNCT [NUM]4 [DEP]punct O
XXX. [SENT]3 [POS]ADP [NUM]2 [DEP]case O
XXX [SENT]3 [POS]PROPN [NUM]0 [DEP]root O
XXX [SENT]3 [POS]NOUN [NUM]2 [DEP]flat O
, [SENT]3 [POS]PUNCT [NUM]2 [DEP]punct O
XXX [SENT]3 [POS]PROPN [NUM]2 [DEP]flat O
. [SENT]3 [POS]PUNCT [NUM]2 [DEP]punct O

Deltidsjob [SENT]4 [POS]NOUN [NUM]0 [DEP]root O
i [SENT]4 [POS]ADP [NUM]3 [DEP]case O
XXX [SENT]4 [POS]PROPN [NUM]1 [DEP]nmod O
XXX [SENT]4 [POS]NOUN [NUM]1 [DEP]nmod O
XXX [SENT]4 [POS]ADJ [NUM]6 [DEP]amod O
XXX [SENT]4 [POS]PROPN [NUM]1 [DEP]nmod O
. [SENT]4 [POS]PUNCT [NUM]1 [DEP]punct O
</code>```

<p>I am using python and would like to delete "line blocks" that are longer than a certain threshold. That is, the length from one empty line to the next crosses the threshold. I thought about iterating over lines, keeping a count and keeping track with a while loop, but can anyone come up with a more elegant solution? </p>

答:
I would do this in two steps, first you find the position of the empty lines, then extracting blocks that are smaller than you threshold:

```<code>cleaned_lines = []
empty_lines = [i for i, line in enumerate(lines) if not line.strip()]
for start, end in zip(empty_lines[:-1], empty_lines[1:]):
    if end-start < THRESHOLD:
        cleaned_lines.extend(lines[start + 1:end])
</code>```

I assume that your file starts and end with an empty line a delimiter for a block, but if that is not the case it is as easy as adding -1 at the beginning of empty_lines and len(lines) at the end.

Body:
I have a large dataset, composed of text in the following form.

Vil [SENT]2 [POS]AUX [NUM]4 [DEP]aux O
du [SENT]2 [POS]PRON [NUM]4 [DEP]nsubj O
gerne [SENT]2 [POS]ADV [NUM]4 [DEP]advmod O
arbejde [SENT]2 [POS]VERB [NUM]0 [DEP]root O
med [SENT]2 [POS]ADP [NUM]9 [DEP]case O
et [SENT]2 [POS]DET [NUM]9 [DEP]det O
globalt [SENT]2 [POS]ADV [NUM]8 [DEP]advmod O
anerkendt [SENT]2 [POS]VERB [NUM]9 [DEP]amod O
brand [SENT]2 [POS]NOUN [NUM]4 [DEP]obl O
? [SENT]2 [POS]PUNCT [NUM]4 [DEP]punct O
XXX. [SENT]3 [POS]ADP [NUM]2 [DEP]case O
XXX [SENT]3 [POS]PROPN [NUM]0 [DEP]root O
XXX [SENT]3 [POS]NOUN [NUM]2 [DEP]flat O
, [SENT]3 [POS]PUNCT [NUM]2 [DEP]punct O
XXX [SENT]3 [POS]PROPN [NUM]2 [DEP]flat O
. [SENT]3 [POS]PUNCT [NUM]2 [DEP]punct O

Deltidsjob [SENT]4 [POS]NOUN [NUM]0 [DEP]root O
i [SENT]4 [POS]ADP [NUM]3 [DEP]case O
XXX [SENT]4 [POS]PROPN [NUM]1 [DEP]nmod O
XXX [SENT]4 [POS]NOUN [NUM]1 [DEP]nmod O
XXX [SENT]4 [POS]ADJ [NUM]6 [DEP]amod O
XXX [SENT]4 [POS]PROPN [NUM]1 [DEP]nmod O
. [SENT]4 [POS]PUNCT [NUM]1 [DEP]punct O

I am using python and would like to delete "line blocks" that are longer than a certain threshold. That is, the length from one empty line to the next crosses the threshold. I thought about iterating over lines, keeping a count and keeping track with a while loop, but can anyone come up with a more elegant solution?

Body:
I would do this in two steps, first you find the position of the empty lines, then extracting blocks that are smaller than you threshold:

cleaned_lines = []
empty_lines = [i for i, line in enumerate(lines) if not line.strip()]
for start, end in zip(empty_lines[:-1], empty_lines[1:]):
    if end-start < THRESHOLD:
        cleaned_lines.extend(lines[start + 1:end])

I assume that your file starts and end with an empty line a delimiter for a block, but if that is not the case it is as easy as adding -1 at the beginning of empty_lines and len(lines) at the end.


问:
How to send commands to putty
I'm writing a simple executable in C that needs to open a putty session and send commands to it, then close putty.  I can open/close the putty session (i'm not that bad) but i'm not too sure on how to send putty the commands.

Any ideas??

答: Have you looked at the source for QuickPutty?  It's LGPL licensed.</p>

OwnerDisplayName: Abigail Adams

Title: How to send commands to putty

OwnerDisplayName: Alnitak


问:
angular multidimensional array assignment
Working with Angular 5.

What I am trying to do is to assign in array a multidimensional array.

What is working with PHP?

```<code>$arM = array();
$arM["20/02/2020"][1] = ["name"=> 'my name', "id"=> 1];
</code>```

the output of this is:

```<code>Array
(
    [20/02/2020] => Array
        (
            [1] => Array
                (
                    [name] => my name
                    [id] => 1
                )

        )

)
</code>```

In angular when I am doing this is not working. Example:

```<code>let data:any = [];
data["20/02/2020"][1] = myArray;
</code>```

How can I achieve the same result of PHP's?

答:
Like this maybe?

let data = {}; // Object (with keys), not array
data["20/02/2020"] = { name : "my name", id : 1 };

console.log(data);```

Body:
Working with Angular 5.

What I am trying to do is to assign in array a multidimensional array.

What is working with PHP?

$arM = array();
$arM["20/02/2020"][1] = ["name"=> 'my name', "id"=> 1];

the output of this is:

Array
(
    [20/02/2020] => Array
        (
            [1] => Array
                (
                    [name] => my name
                    [id] => 1
                )

        )

)

In angular when I am doing this is not working. Example:

let data:any = [];
data["20/02/2020"][1] = myArray;

How can I achieve the same result of PHP's?


问:
Warning: mysqli_connect(): (HY000/1049): Unknown database in mac terminal only
in mac i want to create cronjob but when i run the php file with database i am getting error in terminal.

```<code>Warning: mysqli_connect(): (HY000/1049): Unknown database
</code>```

And In the browser run perfect.

答:
For me, the problem was the "Port number" (on Step 3 of OpenCart 3.0.3.2 installation) which was set as 3306 but in MySQL, it was showing as 3308 so I just changed the same and all went good.

enter image description here

Body:
in mac i want to create cronjob but when i run the php file with database i am getting error in terminal.

Warning: mysqli_connect(): (HY000/1049): Unknown database

And In the browser run perfect.


问:
How to create a namespace first?
I have a custom chart, that should first create a namespace before install dependencies.<br>
How to force Helm first to create namespace before install dependencies? </p>

答:
If you are using a custom chart, if you put a namespace template in there, it will apply that one first.

If you are using a third party chart, you can pull it in as a dependency to a one file chart that creates the namespace.

If you don't need anything special, I believe helm install -n MYNAMESPACE mychart will create a default namespace for you (but not sure, and the behavior may have changed anyway)

Title: How to create a namespace first?

Body:
I have a custom chart, that should first create a namespace before install dependencies.

How to force Helm first to create namespace before install dependencies?