问:
How do I access the files with git lsf attributes on them?
I came across some articles and SO threads about git lsf that should be used when dealing with large data files. That is great, however how do I pass the binary files initially? I can't get my head around

the .gitattribute file contains Content/** filter=lfs diff=lfs merge=lfs -text

I did:

```<code>```
git add .
git commit -m "initial commit"
git push origin master
```
</code>```

That took a while, it's 4GB of data in total, however when my friend cloned that repo, he only got 4MB of a repo size, how can he get the assets?

答:
however when my friend cloned that repo, he only got 4MB of a repo size, how can he get the assets?

That would be git lfs fetch

Examples:

```<code>git config lfs.fetchinclude "textures,images/foo*"
</code>```

This will only fetch objects referenced in paths in the textures folder, and files called foo* in the images folder

```<code>git config lfs.fetchinclude "*.jpg,*.png,*.tga"
</code>```

Only fetch JPG/PNG/TGA files, wherever they are in the repository.

git lfs fetch --all would get everything.

Body:
I came across some articles and SO threads about git lsf that should be used when dealing with large data files. That is great, however how do I pass the binary files initially? I can't get my head around

the .gitattribute file contains Content/** filter=lfs diff=lfs merge=lfs -text

I did:

```
git add .
git commit -m "initial commit"
git push origin master
```

That took a while, it's 4GB of data in total, however when my friend cloned that repo, he only got 4MB of a repo size, how can he get the assets?

Body:
however when my friend cloned that repo, he only got 4MB of a repo size, how can he get the assets?

That would be git lfs fetch

Examples:

git config lfs.fetchinclude "textures,images/foo*"

This will only fetch objects referenced in paths in the textures folder, and files called foo* in the images folder

git config lfs.fetchinclude "*.jpg,*.png,*.tga"

Only fetch JPG/PNG/TGA files, wherever they are in the repository.

git lfs fetch --all would get everything.


来源: stackexchange

问:
Bootstrap input-group-prepend/addon width adjustment
I'm having issues making prepend add-ons the same width. I'm using Font Awesome icons and the prepend is sized to each specific icon. I found another thread from about a year ago describing my exact problem, but there wasn't an answer.

Bootstrap4 make all input-group-addons same width

Here's a screenshot of my issue:

I tried using various CSS tweaks with no luck, including the one provided in that aforementioned thread.

Relevant HTML:

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>

      <input type="text" class="form-control" placeholder="Name">

      <input type="text" class="form-control" placeholder="Email">

      <input type="text" class="form-control" placeholder="Subject">

      <textarea class="form-control" id="exampleFormControlTextarea1" rows="3" placeholder="Message"></textarea>

```

答:
I think the easiest answer with this is css grid.

```<code>.wrapper
{
display:grid;
grid-template-rows: repeat(3,1fr) 2fr;
grid-template-columns: 15% 85%;
grid-row-gap:1rem
}
</code>```

Then assign icons to the first column and inputs to the second one.

Hope this answered your problem.

ContentLicense: CC BY-SA 4.0

Body:
I think the easiest answer with this is css grid.

.wrapper
{
display:grid;
grid-template-rows: repeat(3,1fr) 2fr;
grid-template-columns: 15% 85%;
grid-row-gap:1rem
}

Then assign icons to the first column and inputs to the second one.

Hope this answered your problem.


问:
Reset Flutter CustomScrollView on state change
I'm building a vertically scrolling calendar and I've implemented my days as multiple SliverLists so that I can init with a certain day focused while still having days in the past and future.

The problem is, when the focusDate changes via a state change in a parent, the list updates the dates correctly, but keeps its scroll position. For example, if I'm scrolled to the top of the list, then change the focusDate the days update, but I'm still at the top of the list.

I'm looking to completely replace the list (not just the days) when the focusDate changes. This happens when a date is picked from a date picker. Therefore, new data will need to be fetched anyway and a new CustomScrollView can be created and focused on the correct day.

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

import 'day.dart';

class DaysManager extends StatelessWidget {
  List<Day> days;

  DaysManager({DateTime focusDate}) {
    final DateTime startDate = focusDate.subtract(Duration(days: 30));
    days = List.generate(61, (int index) {
      return Day(
        date: startDate.add(Duration(days: index)),
      );
    });
  }

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

  CustomScrollView _buildScrollView() {
    final focusKey = ValueKey('focus');

    return CustomScrollView(
      center: focusKey,
      slivers: <Widget>[
        SliverList(
          delegate: SliverChildListDelegate(
            days.sublist(0, 31).reversed.toList(),
          ),
        ),
        SliverList(
          key: focusKey,
          delegate: SliverChildListDelegate(
            days.sublist(31, 32),
          ),
        ),
        SliverList(
          delegate: SliverChildListDelegate(
            days.sublist(32),
          ),
        ),
      ],
    );
  }
}
</code>```

答:
You can add a ScrollController to your CustomListView. And when you set your state use the controller to animate to the position that you just selected.

ScrollController has a method:

```<code>Future<Void> animateTo(
  double offset, {
  @required Duration duration,
  @required Curve curve,
})
</code>```

Where offset is the position you want to animate to.

Body:
I'm building a vertically scrolling calendar and I've implemented my days as multiple SliverLists so that I can init with a certain day focused while still having days in the past and future.

The problem is, when the focusDate changes via a state change in a parent, the list updates the dates correctly, but keeps its scroll position. For example, if I'm scrolled to the top of the list, then change the focusDate the days update, but I'm still at the top of the list.

I'm looking to completely replace the list (not just the days) when the focusDate changes. This happens when a date is picked from a date picker. Therefore, new data will need to be fetched anyway and a new CustomScrollView can be created and focused on the correct day.

import 'package:flutter/material.dart';

import 'day.dart';

class DaysManager extends StatelessWidget {
  List<Day> days;

  DaysManager({DateTime focusDate}) {
    final DateTime startDate = focusDate.subtract(Duration(days: 30));
    days = List.generate(61, (int index) {
      return Day(
        date: startDate.add(Duration(days: index)),
      );
    });
  }

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

  CustomScrollView _buildScrollView() {
    final focusKey = ValueKey('focus');

    return CustomScrollView(
      center: focusKey,
      slivers: <Widget>[
        SliverList(
          delegate: SliverChildListDelegate(
            days.sublist(0, 31).reversed.toList(),
          ),
        ),
        SliverList(
          key: focusKey,
          delegate: SliverChildListDelegate(
            days.sublist(31, 32),
          ),
        ),
        SliverList(
          delegate: SliverChildListDelegate(
            days.sublist(32),
          ),
        ),
      ],
    );
  }
}

Body:
You can add a ScrollController to your CustomListView. And when you set your state use the controller to animate to the position that you just selected.

ScrollController has a method:

Future<Void> animateTo(
  double offset, {
  @required Duration duration,
  @required Curve curve,
})

Where offset is the position you want to animate to.


问:
ARM Template - Validating parameters
I have created a simple JSON which creates a storage account. After I introduced a parameter of type object I am getting a validation error.

```<code>"parameters": {
  "storageAccountType": {
    "type": "string",
    "defaultValue": "Standard_LRS",
    "allowedValues": [
      "Standard_LRS",
      "Standard_GRS",
      "Standard_ZRS",
      "Premium_LRS"
    ],
    "metadata": {
      "description": "Storage Account type"
    }
  },
  "location": {
    "type": "string",
    "defaultValue": "Australia East",
    "metadata": {
      "description": "Location for all resources."
    }
  }, "objectToConvert": {
    "type": "object"

}
</code>```

Output from Octopus

```<code>{"storageAccountType":{"value":"Standard_LRS"},"location":{"value":"Australia East"},"objectToConvert":{"value":[{"a":"b"},{"c":"d"},{"c5":"d"},{"6a":"b"},{"cfg":"d"}]}}
</code>```

I am sure the problem has been introduced due to the parameter objectToConvert.

The value of objectToConvert is being passed from Octopus and is

Error

答: Problem solved after changing the data type from object to array</p>

Title: ARM Template - Validating parameters

Body:
I have created a simple JSON which creates a storage account. After I introduced a parameter of type object I am getting a validation error.

"parameters": {
  "storageAccountType": {
    "type": "string",
    "defaultValue": "Standard_LRS",
    "allowedValues": [
      "Standard_LRS",
      "Standard_GRS",
      "Standard_ZRS",
      "Premium_LRS"
    ],
    "metadata": {
      "description": "Storage Account type"
    }
  },
  "location": {
    "type": "string",
    "defaultValue": "Australia East",
    "metadata": {
      "description": "Location for all resources."
    }
  }, "objectToConvert": {
    "type": "object"

}

Output from Octopus

{"storageAccountType":{"value":"Standard_LRS"},"location":{"value":"Australia East"},"objectToConvert":{"value":[{"a":"b"},{"c":"d"},{"c5":"d"},{"6a":"b"},{"cfg":"d"}]}}

I am sure the problem has been introduced due to the parameter objectToConvert.

The value of objectToConvert is being passed from Octopus and is

Error


问:
(#100) "Subject should be a page account" error when trying to publish video to facebook page
I'm trying to make an application that able to publish video to a Facebook page. I obtain list of available pages via /me/account request and get correct response:

```<code>[{
  "access_token":"XXX",
  "category":"Music Video",
  "category_list":[{"id":"1207","name":"Music Video"}],
  "name":"My mighty musical page",
  "id":"XXX",
  "tasks":["ANALYZE","ADVERTISE","MODERATE","CREATE_CONTENT","MANAGE"]
}]
</code>```

after this I take the "id" value and send request to start live video, using the id value as page-id in the link:

{Request:  accessToken:
      {AccessToken token:ACCESS_TOKEN_REMOVED permissions:[manage_pages, publish_video, publish_pages, user_videos, public_profile,
  pages_show_list, publish_to_groups, groups_access_member_info,
  email]},
      graphPath: /XXX/live_videos,
      graphObject: null,
      httpMethod: POST,
      parameters: Bundle[{privacy={"value":"EVERYONE"}}]
      }

As a result I receive the following error:

{HttpStatus: 400, errorCode: 100, subErrorCode: -1, errorType:
  OAuthException, errorMessage: (#100) Subject should be a page account}
  /APP: [FacebookFramework] Attempt to start streaming to
  Facebook returned the error: code 100, message: (#100) Subject should
  be a page account
      {FacebookServiceException: httpResponseCode: 400, facebookErrorCode: 100, facebookErrorType: OAuthException, message:
  (#100) Subject should be a page account}

that actually describes nothing about what goes wrong. I have all required permissions. I am creator of the page and have admin rights. I have no idea where can I find this "correct id". Did I miss something important?

PS. Also I use similar code to post to a group and it works ok.

答:
Yes, you were right, the problem was that I did not pass correct token when tried to start streaming. Correct token is received with /me/account response. I created token the following way

```<code>        final AccessToken currentToken = getCurrentAccessToken();
        new AccessToken (
            "XXX", //custom token string here
            currentToken.getApplicationId(),
            currentToken.getUserId(),
            currentToken.getPermissions(),
            currentToken.getDeclinedPermissions(),
            null,
            null,
            null,
            null
        );
</code>```

and it works well with this new token

Body:
I'm trying to make an application that able to publish video to a Facebook page. I obtain list of available pages via /me/account request and get correct response:

[{
  "access_token":"XXX",
  "category":"Music Video",
  "category_list":[{"id":"1207","name":"Music Video"}],
  "name":"My mighty musical page",
  "id":"XXX",
  "tasks":["ANALYZE","ADVERTISE","MODERATE","CREATE_CONTENT","MANAGE"]
}]

after this I take the "id" value and send request to start live video, using the id value as page-id in the link:

{Request:  accessToken:
      {AccessToken token:ACCESS_TOKEN_REMOVED permissions:[manage_pages, publish_video, publish_pages, user_videos, public_profile,
  pages_show_list, publish_to_groups, groups_access_member_info,
  email]},
      graphPath: /XXX/live_videos,
      graphObject: null,
      httpMethod: POST,
      parameters: Bundle[{privacy={"value":"EVERYONE"}}]
      }

As a result I receive the following error:

{HttpStatus: 400, errorCode: 100, subErrorCode: -1, errorType:
  OAuthException, errorMessage: (#100) Subject should be a page account}
  /APP: [FacebookFramework] Attempt to start streaming to
  Facebook returned the error: code 100, message: (#100) Subject should
  be a page account
      {FacebookServiceException: httpResponseCode: 400, facebookErrorCode: 100, facebookErrorType: OAuthException, message:
  (#100) Subject should be a page account}

that actually describes nothing about what goes wrong. I have all required permissions. I am creator of the page and have admin rights. I have no idea where can I find this "correct id". Did I miss something important?

PS. Also I use similar code to post to a group and it works ok.

Body:
Yes, you were right, the problem was that I did not pass correct token when tried to start streaming. Correct token is received with /me/account response. I created token the following way

        final AccessToken currentToken = getCurrentAccessToken();
        new AccessToken (
            "XXX", //custom token string here
            currentToken.getApplicationId(),
            currentToken.getUserId(),
            currentToken.getPermissions(),
            currentToken.getDeclinedPermissions(),
            null,
            null,
            null,
            null
        );

and it works well with this new token


问:
SweetAlert Prompt issue in bootstrap modal
I have been trying for more than two days to run SweetAlert prompt in a modal bootstrap without success, the input is not accessible and I don't understand why. I need help please.

$("#openSWAL").click(function(){
 swal({
    title: "An input!",
    text: "Write something interesting:",
    type: "input",
    showCancelButton: true,
    closeOnConfirm: false,
    animation: "slide-from-top",
    inputPlaceholder: "Write something"
  },
       function(inputValue){
    if (inputValue === false) return false;

    if (inputValue === "") {
      swal.showInputError("You need to write something!");
      return false
    }

    swal("Nice!", "You wrote: " + inputValue, "success");
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css">

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Open modal
</button>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        Bla<br/>
    Bla<br/>
    Bla<br/>
    Bla<br/>
    Bla<br/>
    Bla<br/>
    Bla<br/>
    Bla<br/>
    Bla<br/>
    Bla<br/>
    Bla<br/>
    Bla<br/>
    Bla<br/>
    Bla<br/>
    Bla<br/>
    Bla<br/>
    Bla<br/>
    Bla<br/>

      </div>
      <div class="modal-footer">
        <button type="button" id="openSWAL" class="btn btn-warning">Open SweetAlert prompt</button>
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div></code>```

答:
Bootstrap modal has z-index=10001 in general. But Sweetalert modal has z-index=10000 or something less than bootstrap modal's z-index. So its always appear behind of bootstrap modal.

Give your SweetAlert modal higher z-index than bootstrap modal.
  Problem will be solved.

In my case, it works perfectly. I am using sweetalert: ^2.1.2

```<code>.swall-overlay {
    z-index: 100005;
}
.swal-modal {
    z-index: 99999;
}
</code>```

Please remember, don't try to change bootstrap modal z-index. Its a common scenario that Alert always appear on top of everything, even on top of modal. So, its a good practice changing sweetalert z-index.

ContentLicense: CC BY-SA 3.0

Body:
I have been trying for more than two days to run SweetAlert prompt in a modal bootstrap without success, the input is not accessible and I don't understand why. I need help please.

$("#openSWAL").click(function(){
 swal({
    title: "An input!",
    text: "Write something interesting:",
    type: "input",
    showCancelButton: true,
    closeOnConfirm: false,
    animation: "slide-from-top",
    inputPlaceholder: "Write something"
  },
       function(inputValue){
    if (inputValue === false) return false;

    if (inputValue === "") {
      swal.showInputError("You need to write something!");
      return false
    }

    swal("Nice!", "You wrote: " + inputValue, "success");
  });
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css">

<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Open modal
</button>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Modal title

        Bla

    Bla

    Bla

    Bla

    Bla

    Bla

    Bla

    Bla

    Bla

    Bla

    Bla

    Bla

    Bla

    Bla

    Bla

    Bla

    Bla

    Bla

        <button type="button" id="openSWAL" class="btn btn-warning">Open SweetAlert prompt</button>
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

Body:
Bootstrap modal has z-index=10001 in general. But Sweetalert modal has z-index=10000 or something less than bootstrap modal's z-index. So its always appear behind of bootstrap modal.

Give your SweetAlert modal higher z-index than bootstrap modal.
  Problem will be solved.

In my case, it works perfectly. I am using sweetalert: ^2.1.2

.swall-overlay {
    z-index: 100005;
}
.swal-modal {
    z-index: 99999;
}

Please remember, don't try to change bootstrap modal z-index. Its a common scenario that Alert always appear on top of everything, even on top of modal. So, its a good practice changing sweetalert z-index.


问:
How to Implement Multiple Countdown Progress Bars in Flutter?
How can I implement instagram's story progress bar on the top. Multiple bars if multiple stories exist, and if there's only one then only one bar. A timer of 10 seconds. What I have so far kinda worked, but it doesn't work when there are 2 or more snaps.

Code

```<code>Container(
    height: 30,
    margin: EdgeInsets.only(top: 50.0),
    child: CustomPaint(
        foregroundPainter: ProgressPainter(value: (this._totalTime) / 10.0 / widget.posts.length),
    ),
)
</code>```

I tried putting it into a listview but it kinda doesn't work.

Update:

I figured a "Row.builder" hack but how can I animate the progress? I'm using countdown as a timer solution and I can get the snaps to change at the end of the timer but the progress bar updating properly is the issue.

```<code>Row(
  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  children: List.generate(widget.posts.length, (index) {
    if (this._index == index) {
      return Expanded(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 10.0),
          height: 30,
          child: CustomPaint(
            foregroundPainter: ProgressPainter(value: this._countDown.remainingTime.inSeconds / 10.0),
          ),
        ),
      );
    } else {
      return Expanded(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 10.0),
          height: 30,
          child: CustomPaint(
            foregroundPainter: ProgressPainter(value: 0.0),
          ),
        ),
      );
    }
  }).reversed.toList(),
)
</code>```

Notes:
I have the effect of the progress bar working but only for one. I have 2 posts, but only one progres bar works, the other remaains 0.

答:
Solved it.

The Countdown:

```<code>int _index = 0;
CountDown _countDown;
StreamSubscription _countDownSubscription;

@override
void initState() {
  super.initState();
  this._initTimer();
}

_initTimer() {
  if (mounted)
    setState(() {
      this._countDown = CountDown(Duration(seconds: widget.posts[this._index].timer));
      this._countDown.remainingTime = Duration(seconds: widget.posts[this._index].timer);
      this._countDownSubscription = this._countDown.stream.listen(null);
    });

  this._countDownSubscription.onData((d) {
    setState(() {}); // Updates the UI to animate the progress bar
  });

  this._countDownSubscription.onDone(() {
    if (widget.posts.length == this._index + 1) {
      Navigator.of(context).pop();
    } else {
      if (mounted)
        setState(() {
          this._index++;
          this._initTimer();
        });
    }
  });
}
</code>```

The Progress Bar:

```<code>class ProgressPainter extends CustomPainter {
  final double value;

  ProgressPainter({this.value});

  Paint backgroundPaint = Paint()
    ..color = Colors.white
    ..style = PaintingStyle.stroke
    ..strokeCap = StrokeCap.round
    ..strokeWidth = 10;

  Paint valuePaint = Paint()
    ..color = Colors.deepPurple
    ..style = PaintingStyle.stroke
    ..strokeCap = StrokeCap.round
    ..strokeWidth = 10;

  @override
  void paint(Canvas canvas, Size size) {
    Path backgroundPath = Path();
    Path valuePath = Path();

    backgroundPath.moveTo(0, size.height / 2);
    backgroundPath.lineTo(size.width, size.height / 2);

    valuePath.moveTo(0, size.height / 2);
    valuePath.lineTo(size.width * this.value, size.height / 2);

    canvas.drawPath(backgroundPath, backgroundPaint);
    canvas.drawPath(valuePath, valuePaint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }
}
</code>```

Dynamic Number of Progress Bars:

```<code>Row(
  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  children: List.generate(widget.posts.length, (index) {
    if (this._index == index) { // Current active post
      return Expanded(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 10.0),
          child: CustomPaint(
            foregroundPainter: ProgressPainter(value: this._countDown.remainingTime.inSeconds / 10.0),
          ),
        ),
      );
    } else if (this._index > index) { // when it's done
      return Expanded(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 10.0),
          child: CustomPaint(
            foregroundPainter: ProgressPainter(value: 0.0),
          ),
        ),
      );
    } else { // When it's next
      return Expanded(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 10.0),
          child: CustomPaint(
            foregroundPainter: ProgressPainter(value: 1.0),
          ),
        ),
      );
    }
  }).reversed.toList(),
)
</code>```

If y'all got a better and simpler solution I'm all for it.

Body:
How can I implement instagram's story progress bar on the top. Multiple bars if multiple stories exist, and if there's only one then only one bar. A timer of 10 seconds. What I have so far kinda worked, but it doesn't work when there are 2 or more snaps.

Code

Container(
    height: 30,
    margin: EdgeInsets.only(top: 50.0),
    child: CustomPaint(
        foregroundPainter: ProgressPainter(value: (this._totalTime) / 10.0 / widget.posts.length),
    ),
)

I tried putting it into a listview but it kinda doesn't work.

Update:

I figured a "Row.builder" hack but how can I animate the progress? I'm using countdown as a timer solution and I can get the snaps to change at the end of the timer but the progress bar updating properly is the issue.

Row(
  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  children: List.generate(widget.posts.length, (index) {
    if (this._index == index) {
      return Expanded(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 10.0),
          height: 30,
          child: CustomPaint(
            foregroundPainter: ProgressPainter(value: this._countDown.remainingTime.inSeconds / 10.0),
          ),
        ),
      );
    } else {
      return Expanded(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 10.0),
          height: 30,
          child: CustomPaint(
            foregroundPainter: ProgressPainter(value: 0.0),
          ),
        ),
      );
    }
  }).reversed.toList(),
)

Notes:
I have the effect of the progress bar working but only for one. I have 2 posts, but only one progres bar works, the other remaains 0.

Body:
Solved it.

The Countdown:

int _index = 0;
CountDown _countDown;
StreamSubscription _countDownSubscription;

@override
void initState() {
  super.initState();
  this._initTimer();
}

_initTimer() {
  if (mounted)
    setState(() {
      this._countDown = CountDown(Duration(seconds: widget.posts[this._index].timer));
      this._countDown.remainingTime = Duration(seconds: widget.posts[this._index].timer);
      this._countDownSubscription = this._countDown.stream.listen(null);
    });

  this._countDownSubscription.onData((d) {
    setState(() {}); // Updates the UI to animate the progress bar
  });

  this._countDownSubscription.onDone(() {
    if (widget.posts.length == this._index + 1) {
      Navigator.of(context).pop();
    } else {
      if (mounted)
        setState(() {
          this._index++;
          this._initTimer();
        });
    }
  });
}

The Progress Bar:

class ProgressPainter extends CustomPainter {
  final double value;

  ProgressPainter({this.value});

  Paint backgroundPaint = Paint()
    ..color = Colors.white
    ..style = PaintingStyle.stroke
    ..strokeCap = StrokeCap.round
    ..strokeWidth = 10;

  Paint valuePaint = Paint()
    ..color = Colors.deepPurple
    ..style = PaintingStyle.stroke
    ..strokeCap = StrokeCap.round
    ..strokeWidth = 10;

  @override
  void paint(Canvas canvas, Size size) {
    Path backgroundPath = Path();
    Path valuePath = Path();

    backgroundPath.moveTo(0, size.height / 2);
    backgroundPath.lineTo(size.width, size.height / 2);

    valuePath.moveTo(0, size.height / 2);
    valuePath.lineTo(size.width * this.value, size.height / 2);

    canvas.drawPath(backgroundPath, backgroundPaint);
    canvas.drawPath(valuePath, valuePaint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }
}

Dynamic Number of Progress Bars:

Row(
  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  children: List.generate(widget.posts.length, (index) {
    if (this._index == index) { // Current active post
      return Expanded(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 10.0),
          child: CustomPaint(
            foregroundPainter: ProgressPainter(value: this._countDown.remainingTime.inSeconds / 10.0),
          ),
        ),
      );
    } else if (this._index > index) { // when it's done
      return Expanded(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 10.0),
          child: CustomPaint(
            foregroundPainter: ProgressPainter(value: 0.0),
          ),
        ),
      );
    } else { // When it's next
      return Expanded(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 10.0),
          child: CustomPaint(
            foregroundPainter: ProgressPainter(value: 1.0),
          ),
        ),
      );
    }
  }).reversed.toList(),
)

If y'all got a better and simpler solution I'm all for it.


问:
SQL: MS Access query results change when new inner join added
Three tables:

Activities

Matches

Ratings

Each match is associated with one activity (AID as a foreign key). And each activity has multiple reviews.

I'm trying to count the number of matches that each activity is associated with:

```<code>SELECT MATCHES.AID, Count(MATCHES.AID) AS CountOfAID
FROM ACTIVITIES INNER JOIN MATCHES ON ACTIVITIES.AID = MATCHES.AID
GROUP BY MATCHES.AID;
</code>```

Returns this just fine:

But as soon as I add the inner join to also include the average rating of each activity:

```<code>SELECT ACTIVITIES.[Activity Name], Count(MATCHES.AID) AS CountOfAID,
Avg(RATINGS.Rating) AS AvgOfRating
FROM (ACTIVITIES INNER JOIN MATCHES ON ACTIVITIES.AID = MATCHES.AID) INNER
JOIN RATINGS ON ACTIVITIES.AID = RATINGS.AID
GROUP BY ACTIVITIES.[Activity Name];
</code>```

This happens:

How can I work around this?

答:
Since both reviews and matches are joined to activity but there's no relationship between them, you're essentially creating a product of review-match per activity. One approach to get the result you want is to perform the grouping on subqueries for the matches and reviews (independently), and only then join them on the activities:</p>

```<code>SELECT a.[Activity Name], CountOfAID, AvgOfRating
FROM   activities a
JOIN   (SELECT   aid, COUNT(*) AS CountOfAID
        FROM     matches
        GROUP BY aid) m ON a.aid = m.aid
JOIN   (SELECT   aid, AVG(rating) AS AvgOfRating
        FROM     ratings
        GROUP BY aid) r ON a.aid = r.aid
</code>```

Body:
Three tables:

Activities

Matches

Ratings

Each match is associated with one activity (AID as a foreign key). And each activity has multiple reviews.

I'm trying to count the number of matches that each activity is associated with:

SELECT MATCHES.AID, Count(MATCHES.AID) AS CountOfAID
FROM ACTIVITIES INNER JOIN MATCHES ON ACTIVITIES.AID = MATCHES.AID
GROUP BY MATCHES.AID;

Returns this just fine:

But as soon as I add the inner join to also include the average rating of each activity:

SELECT ACTIVITIES.[Activity Name], Count(MATCHES.AID) AS CountOfAID,
Avg(RATINGS.Rating) AS AvgOfRating
FROM (ACTIVITIES INNER JOIN MATCHES ON ACTIVITIES.AID = MATCHES.AID) INNER
JOIN RATINGS ON ACTIVITIES.AID = RATINGS.AID
GROUP BY ACTIVITIES.[Activity Name];

This happens:

How can I work around this?

Body:
Since both reviews and matches are joined to activity but there's no relationship between them, you're essentially creating a product of review-match per activity. One approach to get the result you want is to perform the grouping on subqueries for the matches and reviews (independently), and only then join them on the activities:

SELECT a.[Activity Name], CountOfAID, AvgOfRating
FROM   activities a
JOIN   (SELECT   aid, COUNT(*) AS CountOfAID
        FROM     matches
        GROUP BY aid) m ON a.aid = m.aid
JOIN   (SELECT   aid, AVG(rating) AS AvgOfRating
        FROM     ratings
        GROUP BY aid) r ON a.aid = r.aid


问:
How to parse Python code while keeping string literals exactly as-is?
I'm trying to go through all the string literals in Python source code while being able to tell what kind of string literal each one is.

Unfortunately, as you can see in this example, ast.parse doesn't work:

```<code>[node.value.s for node in ast.parse('\'x\'; u\'x\'; b\'x\'; "x"; u"x"; b"x"').body]
</code>```

The output is:

```<code>['x', 'x', b'x', 'x', 'x', b'x']
</code>```

meaning that I can't distinguish between the '' and u'' literals, or the '' and "", etc.

How can I parse Python source code while maintaining the original literal exactly as written?

Is there a built-in way?

答:
The information you're looking for isn't AST-level information. The appropriate level to inspect stuff like this is the token level, and you can use the tokenize module for that.

The tokenize API is pretty awkward - it wants an input that behaves like the readline method of a binary file-like object - so you'll need to open files in binary mode, and if you have a string, you'll need to use encode and io.BytesIO for conversion.

```<code>import tokenize
token_stream = tokenize.tokenize(input_file.readline)
for token in token_stream:
    if token.type == tokenize.STRING:
        do_whatever_with(token.string)
</code>```

Here's the Python 2 version - the function names are different, and you have to access token information positionally, because you get regular tuples instead of namedtuples:

```<code>import tokenize
token_stream = tokenize.generate_tokens(input_file.readline)
for token_type, token_string, _, _, _ in token_stream:
    if token_type == tokenize.STRING:
        do_whatever_with(token_string)
</code>```

Body:
I'm trying to go through all the string literals in Python source code while being able to tell what kind of string literal each one is.

Unfortunately, as you can see in this example, ast.parse doesn't work:

[node.value.s for node in ast.parse('\'x\'; u\'x\'; b\'x\'; "x"; u"x"; b"x"').body]

The output is:

['x', 'x', b'x', 'x', 'x', b'x']

meaning that I can't distinguish between the '' and u'' literals, or the '' and "", etc.

How can I parse Python source code while maintaining the original literal exactly as written?

Is there a built-in way?

Body:
The information you're looking for isn't AST-level information. The appropriate level to inspect stuff like this is the token level, and you can use the tokenize module for that.

The tokenize API is pretty awkward - it wants an input that behaves like the readline method of a binary file-like object - so you'll need to open files in binary mode, and if you have a string, you'll need to use encode and io.BytesIO for conversion.

import tokenize
token_stream = tokenize.tokenize(input_file.readline)
for token in token_stream:
    if token.type == tokenize.STRING:
        do_whatever_with(token.string)

Here's the Python 2 version - the function names are different, and you have to access token information positionally, because you get regular tuples instead of namedtuples:

import tokenize
token_stream = tokenize.generate_tokens(input_file.readline)
for token_type, token_string, _, _, _ in token_stream:
    if token_type == tokenize.STRING:
        do_whatever_with(token_string)


问:
How to calculate the lifetime of the use of a database?
Can you please help me with this problem?

You have the following information:

```<code>Name     Date     Size_Total  Size_Free  Size_Used
 X    20/05/2019     50MB       40MB       10MB
 X    21/05/2019     50MB       35MB       15MB
 X    22/05/2019     50MB       26MB       24MB
 X    23/05/2019     50MB       24MB       26MB
 X    24/05/2019     50MB       22MB       28MB
 X    25/05/2019     50MB       17MB       33MB
 X    26/05/2019     50MB       15MB       35MB
</code>```

These data are extracted from a database daily for monitoring. What statistical function can I use to determine how many days are left to the database to run out of space according to its use?

I appreciate the help.

Thank you so much

答:
A simple solution would be to use linear regression to come up with a linear model of the database size.

Using this input generates the following output.

The equation of the slope of the line is what we're looking for: y = 4.107x + 8. We can use this to find when the database will reach its maximum size by determining where this function intersects with y = 50, the size of the database. This second equation is a horizontal line because the maximum size of the database does not vary with respect to x, time, which is the whole problem.

Looking for the intersection yields the following result:

Remember, however, that the answer, 10.2264, includes the days that have already gone by. We had seven days worth of input, so since our model predicts the database will fill up on day ten, we have roughly two days and some change. This is not a hard figure though, because remember that the database size is increasing irregularly and we could much more or much less time if our base data was not representative of the true database use, or if external factors that directly impacted database use changed.

Note that I did not include computations in the answer because I'm focusing on the high-level concept. I used the first linear regression calculator a quick google search pulled up and then plugged in the equation into Wolfram Alpha, so please actually do this yourself to verify the numbers are correct.

Body:
Can you please help me with this problem?

You have the following information:

Name     Date     Size_Total  Size_Free  Size_Used
 X    20/05/2019     50MB       40MB       10MB
 X    21/05/2019     50MB       35MB       15MB
 X    22/05/2019     50MB       26MB       24MB
 X    23/05/2019     50MB       24MB       26MB
 X    24/05/2019     50MB       22MB       28MB
 X    25/05/2019     50MB       17MB       33MB
 X    26/05/2019     50MB       15MB       35MB

These data are extracted from a database daily for monitoring. What statistical function can I use to determine how many days are left to the database to run out of space according to its use?

I appreciate the help.

Thank you so much


问:
PowerMock with Mockito doesn't create mock for constructor invocations
I'm trying to use PowerMock with mockito to create mock each time any constructor of FileOutputStream is created but it seems to return a real instance instead of a mocked one.

My test class :

```<code>@RunWith(PowerMockRunner.class)
@PrepareForTest({FileOutputStream.class,FilesHelper.class})
public class FilesHelperTest {

@Test
public void createFileFromInputStream_validate_null_progress_subject_doesnt_throws_null_pointer() throws Exception {
    FileOutputStream fileOutputStream = Mockito.mock(FileOutputStream.class);
    PowerMockito.whenNew(FileOutputStream.class).withAnyArguments().thenReturn(fileOutputStream);
    File file = Mockito.mock(File.class);
    BufferedSource bufferedSource = Mockito.mock(BufferedSource.class);
    Mockito.doReturn(true).when(file).exists();
    Mockito.when(bufferedSource.read(Mockito.any(),Mockito.anyLong())).thenReturn(15L,-1L);
    FilesHelper.createFileFromInputStream(file,bufferedSource,8,null);
 }
}
</code>```

My class under test -

```<code>public class FilesHelper {

/**
 * Creates a file out of an input stream wrapped by Okio's {@link BufferedSource}.
 * @param file a file to save the input to
 * @param bufferedSource the source input.
 * @param maxSize the maximum amount of bytes can be loaded to memory
 * @param progressUpdatePublisher an optional update publisher which notifies the writing progress
 * @return a {@link com.bonimoo.wominstaller.data.entities.BaseDownloadStatusDTO.Done} status with all the necessary information.
 * @throws IOException in case of errors while writing
 * @throws IllegalStateException when the file doesn't exists and cannot be created
 */
public static BaseDownloadStatusDTO.Done createFileFromInputStream(File file, BufferedSource bufferedSource, int maxSize, @Nullable PublishSubject<BaseDownloadStatusDTO> progressUpdatePublisher) throws IOException, IllegalStateException {
    if (!file.exists()) {
        Throwable cause = null;
        boolean created = false;
        try {
            created = file.createNewFile();
        } catch (IOException e) {
            cause = e;
        }
        if (!created) {
            throw new IllegalStateException("FilesHelper cannot create new file",cause);
        }
    }
    if (progressUpdatePublisher != null) {
        progressUpdatePublisher.onNext(new BaseDownloadStatusDTO.Started(file.getAbsolutePath()));
    }
    BufferedSink sink = Okio.buffer(Okio.sink(file));
    Buffer buffer = new Buffer();
    long counter = 0L;
    try {
        for (long readCount = bufferedSource.read(buffer, maxSize); readCount > -1 || bufferedSource.exhausted(); readCount = bufferedSource.read(buffer, maxSize)) {
            sink.writeAll(buffer);
            counter += readCount;
            if (progressUpdatePublisher != null) {
                progressUpdatePublisher.onNext(new BaseDownloadStatusDTO.Progress(counter,file.getAbsolutePath(),readCount));
            }
        }
    } finally {
        sink.flush();
        sink.close();
        buffer.close();
        bufferedSource.close();
    }
    return new BaseDownloadStatusDTO.Done(file);
 }
}
</code>```

so when I'm creating the class I'm still getting the null pointer exception which thrown by the real constructor invocation

```<code>java.lang.NullPointerException
    at java.io.FileOutputStream.<init>(FileOutputStream.java:203)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:162)
    at okio.Okio.sink(Okio.java:181)
    at com.bonimoo.wominstaller.data.helpers.FilesHelper.createFileFromInputStream(FilesHelper.java:49)
    at com.bonimoo.wominstaller.data.helpers.FilesHelperTest.createFileFromInputStream_validate_null_progress_subject_doesnt_throws_null_pointer(FilesHelperTest.java:36)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:326)
    at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:89)
    at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:97)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:310)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:131)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.access$100(PowerMockJUnit47RunnerDelegateImpl.java:59)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner$TestExecutorStatement.evaluate(PowerMockJUnit47RunnerDelegateImpl.java:147)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.evaluateStatement(PowerMockJUnit47RunnerDelegateImpl.java:107)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:298)
    at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)
    at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:218)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:160)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:134)
    at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:136)
    at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:117)
    at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:57)
    at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
</code>```

答:
FileOutputStream object is instantiated in okio.Okio.sink method.

So, add Okio.class in @prepareForTest.

Body:
I'm trying to use PowerMock with mockito to create mock each time any constructor of FileOutputStream is created but it seems to return a real instance instead of a mocked one.

My test class :

@RunWith(PowerMockRunner.class)
@PrepareForTest({FileOutputStream.class,FilesHelper.class})
public class FilesHelperTest {

@Test
public void createFileFromInputStream_validate_null_progress_subject_doesnt_throws_null_pointer() throws Exception {
    FileOutputStream fileOutputStream = Mockito.mock(FileOutputStream.class);
    PowerMockito.whenNew(FileOutputStream.class).withAnyArguments().thenReturn(fileOutputStream);
    File file = Mockito.mock(File.class);
    BufferedSource bufferedSource = Mockito.mock(BufferedSource.class);
    Mockito.doReturn(true).when(file).exists();
    Mockito.when(bufferedSource.read(Mockito.any(),Mockito.anyLong())).thenReturn(15L,-1L);
    FilesHelper.createFileFromInputStream(file,bufferedSource,8,null);
 }
}

My class under test -

public class FilesHelper {

/**
 * Creates a file out of an input stream wrapped by Okio's {@link BufferedSource}.
 * @param file a file to save the input to
 * @param bufferedSource the source input.
 * @param maxSize the maximum amount of bytes can be loaded to memory
 * @param progressUpdatePublisher an optional update publisher which notifies the writing progress
 * @return a {@link com.bonimoo.wominstaller.data.entities.BaseDownloadStatusDTO.Done} status with all the necessary information.
 * @throws IOException in case of errors while writing
 * @throws IllegalStateException when the file doesn't exists and cannot be created
 */
public static BaseDownloadStatusDTO.Done createFileFromInputStream(File file, BufferedSource bufferedSource, int maxSize, @Nullable PublishSubject<BaseDownloadStatusDTO> progressUpdatePublisher) throws IOException, IllegalStateException {
    if (!file.exists()) {
        Throwable cause = null;
        boolean created = false;
        try {
            created = file.createNewFile();
        } catch (IOException e) {
            cause = e;
        }
        if (!created) {
            throw new IllegalStateException("FilesHelper cannot create new file",cause);
        }
    }
    if (progressUpdatePublisher != null) {
        progressUpdatePublisher.onNext(new BaseDownloadStatusDTO.Started(file.getAbsolutePath()));
    }
    BufferedSink sink = Okio.buffer(Okio.sink(file));
    Buffer buffer = new Buffer();
    long counter = 0L;
    try {
        for (long readCount = bufferedSource.read(buffer, maxSize); readCount > -1 || bufferedSource.exhausted(); readCount = bufferedSource.read(buffer, maxSize)) {
            sink.writeAll(buffer);
            counter += readCount;
            if (progressUpdatePublisher != null) {
                progressUpdatePublisher.onNext(new BaseDownloadStatusDTO.Progress(counter,file.getAbsolutePath(),readCount));
            }
        }
    } finally {
        sink.flush();
        sink.close();
        buffer.close();
        bufferedSource.close();
    }
    return new BaseDownloadStatusDTO.Done(file);
 }
}

so when I'm creating the class I'm still getting the null pointer exception which thrown by the real constructor invocation

java.lang.NullPointerException
    at java.io.FileOutputStream.<init>(FileOutputStream.java:203)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:162)
    at okio.Okio.sink(Okio.java:181)
    at com.bonimoo.wominstaller.data.helpers.FilesHelper.createFileFromInputStream(FilesHelper.java:49)
    at com.bonimoo.wominstaller.data.helpers.FilesHelperTest.createFileFromInputStream_validate_null_progress_subject_doesnt_throws_null_pointer(FilesHelperTest.java:36)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:326)
    at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:89)
    at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:97)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:310)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:131)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.access$100(PowerMockJUnit47RunnerDelegateImpl.java:59)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner$TestExecutorStatement.evaluate(PowerMockJUnit47RunnerDelegateImpl.java:147)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.evaluateStatement(PowerMockJUnit47RunnerDelegateImpl.java:107)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:298)
    at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)
    at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:218)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:160)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:134)
    at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:136)
    at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:117)
    at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:57)
    at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)


问:
How to sort strings in java , order shoud display Capital Strings first
Need to sort strings in java in a case sensitive, but Capital letters should display first.

What I tried:

```<code>List<String> l = Arrays.asList("aaa","AAA","AAA","aaa","BBB","ccc","CCC");
l.stream().sorted(String.CASE_INSENSITIVE_ORDER);
System.out.println(l);`
</code>```

Output:

```<code>[aaa, AAA, AAA, aaa, BBB, ccc, CCC]
</code>```

Expecting Output:

```<code>[AAA,AAA,aaa,aaa,BBB,CCC,ccc]
</code>```

答:
This is custom sort, not a case sensitive sort. Because in case-sensitive sort, all capital letters will stand before small letters. Therefore, the result will be

```<code>AAA > BBB > CCC > aaa > bbb > ccc
</code>```

To realize your custom sort, you need to use a custom Comparator, as follows

import org.junit.Test;

import java.util.Arrays;
import java.util.List;

public class SortCapitalFirst {

    @Test
    public void runTest(){
        List<String> l = Arrays.asList("aaa","AAA","AAA","aaa","BBB","ccc","CCC");
        l.sort((o1, o2) -> {
            int compareIgnoreCaseResult = o1.compareToIgnoreCase(o2);

            if (compareIgnoreCaseResult != 0){
                return compareIgnoreCaseResult;
            }

            return o1.compareTo(o2);
        });
        System.out.println(l);
    }
}

 ```

Body:
Need to sort strings in java in a case sensitive, but Capital letters should display first.

What I tried:

List<String> l = Arrays.asList("aaa","AAA","AAA","aaa","BBB","ccc","CCC");
l.stream().sorted(String.CASE_INSENSITIVE_ORDER);
System.out.println(l);`

Output:

[aaa, AAA, AAA, aaa, BBB, ccc, CCC]

Expecting Output:

[AAA,AAA,aaa,aaa,BBB,CCC,ccc]

Body:
This is custom sort, not a case sensitive sort. Because in case-sensitive sort, all capital letters will stand before small letters. Therefore, the result will be

AAA > BBB > CCC > aaa > bbb > ccc

To realize your custom sort, you need to use a custom Comparator, as follows

import org.junit.Test;

import java.util.Arrays;
import java.util.List;

public class SortCapitalFirst {

    @Test
    public void runTest(){
        List<String> l = Arrays.asList("aaa","AAA","AAA","aaa","BBB","ccc","CCC");
        l.sort((o1, o2) -> {
            int compareIgnoreCaseResult = o1.compareToIgnoreCase(o2);

            if (compareIgnoreCaseResult != 0){
                return compareIgnoreCaseResult;
            }

            return o1.compareTo(o2);
        });
        System.out.println(l);
    }
}


问:
How to validate javascript content in angular
In my form, I have a text area. The textarea has to allow only javascript content. I have to validate the text area content, to check if it is javascript or not. How to check if the Text area contains data that is only valid javascript content?</p>

答:
Use a JavaScript parser like acorn and check whether you can correctly parse the textarea contents.

The snippet below uses acorn to try and parse the contents of two textareas, one containing valid JavaScript, and one just containing plain text.

function validateJs(textareaId) {
  const textarea = document.getElementById(textareaId);

  try {
    acorn.Parser.parse(textarea.value);
  } catch(e) {
    textarea.style.backgroundColor = 'red';
    return false;
  }

  textarea.style.backgroundColor = 'green';
  return true;
}

validateJs('good');
validateJs('bad');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/acorn/6.1.1/acorn.js"></script>

<textarea id="good" rows="4" cols="25">
function add(a, b) {
  return a + b;
}
</textarea>

<textarea id="bad" rows="4" cols="25">
Hello world!
</textarea></code>```

Body:
Use a JavaScript parser like acorn and check whether you can correctly parse the textarea contents.

The snippet below uses acorn to try and parse the contents of two textareas, one containing valid JavaScript, and one just containing plain text.

function validateJs(textareaId) {
  const textarea = document.getElementById(textareaId);

  try {
    acorn.Parser.parse(textarea.value);
  } catch(e) {
    textarea.style.backgroundColor = 'red';
    return false;
  }

  textarea.style.backgroundColor = 'green';
  return true;
}

validateJs('good');
validateJs('bad');

<script src="https://cdnjs.cloudflare.com/ajax/libs/acorn/6.1.1/acorn.js"></script>

<textarea id="good" rows="4" cols="25">
function add(a, b) {
  return a + b;
}
</textarea>

<textarea id="bad" rows="4" cols="25">
Hello world!
</textarea>


问:
How to make this slider automatic?
I'm designing a carousel slider with this code but I can't figure out how to make this slider automatically sliding.. What do I need to make this slider automatically sliding?

```<code>    class Slider {
      constructor(props) {
        this.rootElement = props.element;
        this.slides = Array.from(
          this.rootElement.querySelectorAll(".slider-list__item")
        );
        this.slidesLength = this.slides.length;
        this.current = 0;
        this.isAnimating = false;
        this.direction = 1; // -1

        this.navBar = this.rootElement.querySelector(".slider__nav-bar");
        this.thumbs = Array.from(this.rootElement.querySelectorAll(".nav-control"));
        this.prevButton = this.rootElement.querySelector(".slider__arrow_prev");
        this.nextButton = this.rootElement.querySelector(".slider__arrow_next");

        this.slides[this.current].classList.add("slider-list__item_active");
        this.thumbs[this.current].classList.add("nav-control_active");

        this._bindEvents();
      }

      goTo(index, dir) {
        if (this.isAnimating) return;
        var self = this;
        let prevSlide = this.slides[this.current];
        let nextSlide = this.slides[index];

        self.isAnimating = true;
        self.current = index;
        nextSlide.classList.add("slider-list__item_active");

      }

      goStep(dir) {
        let index = this.current + dir;
        let len = this.slidesLength;
        let currentIndex = (index + len) % len;
        this.goTo(currentIndex, dir);
      }

      goNext() {
        this.goStep(1);
      }

      goPrev() {
        this.goStep(-1);
      }

      _navClickHandler(e) {
        var self = this;
        if (self.isAnimating) return;
        let target = e.target.closest(".nav-control");
        if (!target) return;
        let index = self.thumbs.indexOf(target);
        if (index === self.current) return;
        let direction = index > self.current ? 1 : -1;
        self.goTo(index, direction);
      }

      _bindEvents() {
        var self = this;
        ["goNext", "goPrev", "_navClickHandler"].forEach(method => {
          self[method] = self[method].bind(self);
        });
        self.nextButton.addEventListener("click", self.goNext);
        self.prevButton.addEventListener("click", self.goPrev);
        self.navBar.addEventListener("click", self._navClickHandler);
      }
    }

    // ===== init ======
    let slider = new Slider({
      element: document.querySelector(".slider")
    });
</code>```

I've also had tried to add this code to the js file and adding mySlides and dot class into the slider.. But still not working

```<code>    var slideIndex = 0;
    showSlides();

    function showSlides() {
      var i;
      var slides = document.getElementsByClassName("mySlides");
      var dots = document.getElementsByClassName("dot");
      for (i = 0; i < slides.length; i++) {
        slides[i].style.display = "none";
      }
      slideIndex++;
      if (slideIndex > slides.length) {slideIndex = 1}
      for (i = 0; i < dots.length; i++) {
        dots[i].className = dots[i].className.replace(" active", "");
      }
      slides[slideIndex-1].style.display = "block";
      dots[slideIndex-1].className += " active";
      setTimeout(showSlides, 2000); // Change image every 2 seconds
    }
</code>```

Here is the Slider HTML code,

```<code>            <div class="slider">

              <ul class="slider-list">

                <li class="mySlides slider-list__item  ">
                  <span class="back__element">
                    <img src="assets/img/back_mango_002.png" />
                  </span>
                  <span class="main__element">
                    <img src="assets/img/bottle_mango_002.png" />
                  </span>
                  <span class="front__element">
                    <img src="assets/img/front_mango_002.png" />
                  </span>
                  <span class="title__element">
                    <span class="title">mango</span>
                  </span>
                  <span class="more__element">
                    <span class="content">
                      <span class="headline">mango</span>
                      <span class="excerpt">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Illo ratione nisi perferendis? Nemo in accusamus cupiditate officiis.</span>
                      <span class="link">
                        <div class="fill"></div>
                        <a href="#">Open catalog</a>
                      </span>
                    </span>
                  </span>
                 </li>

                <li class="mySlides slider-list__item">
                  <span class="back__element">
                    <img src="assets/img/back_bananas_001.png" />
                  </span>
                  <span class="main__element">
                    <img src="assets/img/bottle_bananas_001.png" />
                  </span>
                  <span class="front__element">
                    <img src="assets/img/front_bananas_001.png" />
                  </span>
                  <span class="title__element">
                    <span class="title">bananas</span>
                  </span>
                  <span class="more__element">
                    <span class="content">
                      <span class="headline">bananas</span>
                      <span class="excerpt">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Illo ratione nisi perferendis? Nemo in accusamus cupiditate officiis.</span>
                      <span class="link">
                        <div class="fill fill-dark"></div>
                        <a href="#">Open catalog</a>
                      </span>
                    </span>
                  </span>
                 </li>

                 <li class="mySlides slider-list__item">
                  <span class="back__element">
                    <img src="assets/img/back_oranges_003.png" />
                  </span>
                  <span class="main__element">
                    <img src="assets/img/bottle_oranges_003.png" />
                  </span>
                  <span class="front__element">
                    <img src="assets/img/front_oranges_003.png" />
                  </span>
                  <span class="title__element">
                    <span class="title">oranges</span>
                  </span>
                  <span class="more__element">
                    <span class="content">
                      <span class="headline">oranges</span>
                      <span class="excerpt">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Illo ratione nisi perferendis? Nemo in accusamus cupiditate officiis.</span>
                      <span class="link">
                          <div class="fill"></div>
                        <a href="#">Open catalog</a>
                      </span>
                    </span>
                  </span>
                 </li>

              </ul>

              <div class="slider__nav-bar">
                <a class="dot nav-control"></a>
                <a class="dot nav-control"></a>
                <a class="dot nav-control"></a>
              </div>

              <div class="slider__controls">
                <a class="slider__arrow slider__arrow_prev"></a>
                <a class="slider__arrow slider__arrow_next"></a>
              </div>

            </div>
</code>```

I expect that the slider will automatically sliding when i add the mySlides and dot class, but its just blinking instead

答:
As Bibberty suggested, you just need to setInterval for your slider.

```<code>setInterval(showSlides, 2000); // Change image every 2 seconds

    function showSlides() {
      var i;
      var slides = document.getElementsByClassName("mySlides");
      var dots = document.getElementsByClassName("dot");
      for (i = 0; i < slides.length; i++) {
        slides[i].style.display = "none";
      }
      slideIndex++;
      if (slideIndex > slides.length) {slideIndex = 1}
      for (i = 0; i < dots.length; i++) {
        dots[i].className = dots[i].className.replace(" active", "");
      }
      slides[slideIndex-1].style.display = "block";
      dots[slideIndex-1].className += " active";
    }
</code>```

Title: How to make this slider automatic?

Body:
I'm designing a carousel slider with this code but I can't figure out how to make this slider automatically sliding.. What do I need to make this slider automatically sliding?

    class Slider {
      constructor(props) {
        this.rootElement = props.element;
        this.slides = Array.from(
          this.rootElement.querySelectorAll(".slider-list__item")
        );
        this.slidesLength = this.slides.length;
        this.current = 0;
        this.isAnimating = false;
        this.direction = 1; // -1

        this.navBar = this.rootElement.querySelector(".slider__nav-bar");
        this.thumbs = Array.from(this.rootElement.querySelectorAll(".nav-control"));
        this.prevButton = this.rootElement.querySelector(".slider__arrow_prev");
        this.nextButton = this.rootElement.querySelector(".slider__arrow_next");

        this.slides[this.current].classList.add("slider-list__item_active");
        this.thumbs[this.current].classList.add("nav-control_active");

        this._bindEvents();
      }

      goTo(index, dir) {
        if (this.isAnimating) return;
        var self = this;
        let prevSlide = this.slides[this.current];
        let nextSlide = this.slides[index];

        self.isAnimating = true;
        self.current = index;
        nextSlide.classList.add("slider-list__item_active");

      }

      goStep(dir) {
        let index = this.current + dir;
        let len = this.slidesLength;
        let currentIndex = (index + len) % len;
        this.goTo(currentIndex, dir);
      }

      goNext() {
        this.goStep(1);
      }

      goPrev() {
        this.goStep(-1);
      }

      _navClickHandler(e) {
        var self = this;
        if (self.isAnimating) return;
        let target = e.target.closest(".nav-control");
        if (!target) return;
        let index = self.thumbs.indexOf(target);
        if (index === self.current) return;
        let direction = index > self.current ? 1 : -1;
        self.goTo(index, direction);
      }

      _bindEvents() {
        var self = this;
        ["goNext", "goPrev", "_navClickHandler"].forEach(method => {
          self[method] = self[method].bind(self);
        });
        self.nextButton.addEventListener("click", self.goNext);
        self.prevButton.addEventListener("click", self.goPrev);
        self.navBar.addEventListener("click", self._navClickHandler);
      }
    }

    // ===== init ======
    let slider = new Slider({
      element: document.querySelector(".slider")
    });

I've also had tried to add this code to the js file and adding mySlides and dot class into the slider.. But still not working

    var slideIndex = 0;
    showSlides();

    function showSlides() {
      var i;
      var slides = document.getElementsByClassName("mySlides");
      var dots = document.getElementsByClassName("dot");
      for (i = 0; i < slides.length; i++) {
        slides[i].style.display = "none";
      }
      slideIndex++;
      if (slideIndex > slides.length) {slideIndex = 1}
      for (i = 0; i < dots.length; i++) {
        dots[i].className = dots[i].className.replace(" active", "");
      }
      slides[slideIndex-1].style.display = "block";
      dots[slideIndex-1].className += " active";
      setTimeout(showSlides, 2000); // Change image every 2 seconds
    }

Here is the Slider HTML code,

                    mango

                      mango
                      Lorem ipsum dolor, sit amet consectetur adipisicing elit. Illo ratione nisi perferendis? Nemo in accusamus cupiditate officiis.

                        Open catalog

                    bananas

                      bananas
                      Lorem ipsum dolor, sit amet consectetur adipisicing elit. Illo ratione nisi perferendis? Nemo in accusamus cupiditate officiis.

                        Open catalog

                    oranges

                      oranges
                      Lorem ipsum dolor, sit amet consectetur adipisicing elit. Illo ratione nisi perferendis? Nemo in accusamus cupiditate officiis.

                        Open catalog

I expect that the slider will automatically sliding when i add the mySlides and dot class, but its just blinking instead

Body:
As Bibberty suggested, you just need to setInterval for your slider.

setInterval(showSlides, 2000); // Change image every 2 seconds

    function showSlides() {
      var i;
      var slides = document.getElementsByClassName("mySlides");
      var dots = document.getElementsByClassName("dot");
      for (i = 0; i < slides.length; i++) {
        slides[i].style.display = "none";
      }
      slideIndex++;
      if (slideIndex > slides.length) {slideIndex = 1}
      for (i = 0; i < dots.length; i++) {
        dots[i].className = dots[i].className.replace(" active", "");
      }
      slides[slideIndex-1].style.display = "block";
      dots[slideIndex-1].className += " active";
    }


问:
App testing return "NullInjectorError: No provider for Location!"
Testing an app in Angular 7 with Karma, I can't remove the error in subj.

I have searched various places (mostly here) but either the solutions don't work or are not relevant to my case.

App.component.html:

```<code><app-header></app-header>
<router-outlet></router-outlet>
</code>```

Header.component.ts:

```<code>import { Component, OnInit, ViewChild, ElementRef, AfterViewInit, EventEmitter, Output } from '@angular/core';
import { Router } from '@angular/router';
import { Location } from '@angular/common';

@Component({
    selector: 'app-header',
    templateUrl: './header.component.html',
    styleUrls: ['./header.component.less']
})
export class HeaderComponent implements AfterViewInit, OnInit {
    constructor(private location: Location, private router: Router) {
        setInterval(() => {
            this.now = new Date();
        }, 1000);
    }
...
    onKeyDown(event: KeyboardEvent): void {
        event.preventDefault();
        if (event.which === this.KEY_ESCAPE){
            if (this.router.url !== '/'){
                this.location.back();
            }
        }
    }
</code>```

App.component.spec.ts:

```<code>import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { RouterOutlet } from '@angular/router';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent,
        HeaderComponent,
        RouterOutlet
      ],
    }).compileComponents();
  }));

  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  });
</code>```

```<code>AppComponent should create the app
Error: StaticInjectorError(DynamicTestModule)[HeaderComponent -> Location]:
  StaticInjectorError(Platform: core)[HeaderComponent -> Location]:
    NullInjectorError: No provider for Location!
</code>```

答:
Can u try  to import > CommonModule

```<code>  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [CommonModule]
      declarations: [
        AppComponent,
        HeaderComponent,
        RouterOutlet
      ],
    }).compileComponents();
  }));
</code>```

Body:
Testing an app in Angular 7 with Karma, I can't remove the error in subj.

I have searched various places (mostly here) but either the solutions don't work or are not relevant to my case.

App.component.html:

<app-header></app-header>
<router-outlet></router-outlet>

Header.component.ts:

import { Component, OnInit, ViewChild, ElementRef, AfterViewInit, EventEmitter, Output } from '@angular/core';
import { Router } from '@angular/router';
import { Location } from '@angular/common';

@Component({
    selector: 'app-header',
    templateUrl: './header.component.html',
    styleUrls: ['./header.component.less']
})
export class HeaderComponent implements AfterViewInit, OnInit {
    constructor(private location: Location, private router: Router) {
        setInterval(() => {
            this.now = new Date();
        }, 1000);
    }
...
    onKeyDown(event: KeyboardEvent): void {
        event.preventDefault();
        if (event.which === this.KEY_ESCAPE){
            if (this.router.url !== '/'){
                this.location.back();
            }
        }
    }

App.component.spec.ts:

import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { RouterOutlet } from '@angular/router';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent,
        HeaderComponent,
        RouterOutlet
      ],
    }).compileComponents();
  }));

  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  });

AppComponent should create the app
Error: StaticInjectorError(DynamicTestModule)[HeaderComponent -> Location]:
  StaticInjectorError(Platform: core)[HeaderComponent -> Location]:
    NullInjectorError: No provider for Location!

Body:
Can u try  to import > CommonModule

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [CommonModule]
      declarations: [
        AppComponent,
        HeaderComponent,
        RouterOutlet
      ],
    }).compileComponents();
  }));


问:
Javascript navigator.mediaDevices.getUserMedia get width and height at source
I'm using this code, but when it gets the source the height and width are set by the constraints in the code block below, but I want to get the actual size of the video.

```<code>  navigator.mediaDevices.getUserMedia({
    audio: false,
    video: {
      mandatory: {
        chromeMediaSource: 'desktop',
        chromeMediaSourceId: desktop_id,
        minWidth: 990,
        maxWidth: 990,
        minHeight: 770,
        maxHeight: 770
      }
    }
  }).then(gotStream).catch(getUserMediaError);
</code>```

The resulting captured image is 990x770 of course but this results in an image with a black border around it. The real video sourced is 995x744 but it gets this new size with black borders as a result of the given constraints. If I don't set any constraints then an error is thrown saying the width is 0 so some kind of width needs to be set.

Even manually inputting the video source size of 995x744 into the constraints does not work since it seems to need an area bigger than the source to capture it. Not sure why it can't be captured exactly as it is? Maybe there's something else I'm doing wrong that could remedy this?

How can I get the size of the video as I capture it so the constraints can be set to the actual size of the video? So the captured image is exactly the same size as the source video with no black borders etc.

答:
The answer is quite simple.

In a simple math operation you can see that:

```<code>990 / 770 = 1.28
995 / 744 = 1.33
</code>```

So - When you require a mandatory ratio of 1.28 - of course you will get black borders. You are violating the true aspect ratio of 1.33 which is supported by the camera.

The only way to avoid black border is to require width and height that devide to aspect ratio of 1.33.

Hope this helps.

Body:
I'm using this code, but when it gets the source the height and width are set by the constraints in the code block below, but I want to get the actual size of the video.

  navigator.mediaDevices.getUserMedia({
    audio: false,
    video: {
      mandatory: {
        chromeMediaSource: 'desktop',
        chromeMediaSourceId: desktop_id,
        minWidth: 990,
        maxWidth: 990,
        minHeight: 770,
        maxHeight: 770
      }
    }
  }).then(gotStream).catch(getUserMediaError);

The resulting captured image is 990x770 of course but this results in an image with a black border around it. The real video sourced is 995x744 but it gets this new size with black borders as a result of the given constraints. If I don't set any constraints then an error is thrown saying the width is 0 so some kind of width needs to be set.

Even manually inputting the video source size of 995x744 into the constraints does not work since it seems to need an area bigger than the source to capture it. Not sure why it can't be captured exactly as it is? Maybe there's something else I'm doing wrong that could remedy this?

How can I get the size of the video as I capture it so the constraints can be set to the actual size of the video? So the captured image is exactly the same size as the source video with no black borders etc.

Body:
The answer is quite simple.

In a simple math operation you can see that:

990 / 770 = 1.28
995 / 744 = 1.33

So - When you require a mandatory ratio of 1.28 - of course you will get black borders. You are violating the true aspect ratio of 1.33 which is supported by the camera.

The only way to avoid black border is to require width and height that devide to aspect ratio of 1.33.

Hope this helps.


问:
How to create a taken damage / red vignette effect in pygame
I'm making a 2D game in python using the module pygame. I would like to create a red vignette/bleed effect whenever the player takes damage in my game.  This is seen in many games today, where the edges of the screen will flash red for a second and quickly disappear.

I have tried blitting an image I made in photoshop and scaling it accordingly during an animation cycle, but this was a really performance heavy operation, subsequently causing a lot of lag.  I'm looking for alternatives to this method.

Code declaring a few variables:

```<code>bgX = 0
bgY = 0
damage = pygame.image.load("defensiveGameHUD.png").convert_alpha()
dimensions = [1920,1080]
</code>```

Then I have this in the main loop of my game:

```<code>win.blit(background,(0,0))

if dimensions[0] != 4020:
    dimensions[0] += 30
    bgX -= 15
if dimensions[1] != 4600:
    dimensions[1] += 40
    bgY -= 20

if dimensions[1] != 4600:
    screenDamage = pygame.transform.scale(damage, dimensions)
    win.blit(screenDamage, (bgX, bgY))
else:
    screenDamage = None
</code>```

That is simply an animation that will scale the image in, however, the scaling is improper and this is very costly on performance.

```<code>def smmothstep(edge0, edge1, x):
    t = min(1, max(0, (x - edge0) / (edge1 - edge0)))
    return t * t * (3.0 - 2.0 * t)

def gen_damage_image(scale, source):
    dest = source.copy()
    img_size = dest.get_size()
    for i in range(img_size[0]):
        for j in range(img_size[1]):
            fx = smmothstep(0, img_size[0]/2*scale, min(i, img_size[0]-i))
            fy = smmothstep(0, img_size[1]/2*scale, min(j, img_size[1]-j))
            color =  dest.get_at((i, j))
            fade_color = [int(255 - (1-fx*fy)*(255 - c)) for c in color]
            dest.set_at((i, j), fade_color)
    return dest

def tintDamage(surface, scale):
    i = min(len(dmg_list)-1, max(0, int(scale*(len(dmg_list)-0.5))))
    c.blit(dmg_list[i], (0, 0), special_flags = pygame.BLEND_MULT)

damage = pygame.image.load("defensiveGameHUD.png").convert_alpha()
max_dmg_img = 10
dmg_list = [gen_damage_image((i+1)/max_dmg_img, damage) for i in range(max_dmg_img)]

start_time = 0
tint = 0
damage_effect = False
</code>```

答:
To tint the screen in red can be achieved by pygame.Surface.fill(), by setting special_flags = BLEND_MULT.

The following function "tints" the entire surface in red, by a scale from 0 to 1. If scale is 0, the surface is not tinted and if scale is 1 the entire surface is tinted by the (red) color (255, 0, 0):

def tintDamage(surface, scale):
    GB = min(255, max(0, round(255 * (1-scale))))
    surface.fill((255, GB, GB), special_flags = pygame.BLEND_MULT)
```

<p>The function has to be called right before <code>pygame.display.flip()</code> or <code>pygame.display.update()</code>:</p>

<p>e.g.</p>

<pre class="lang-py prettyprint-override"><code>tintDamage(win, 0.5)
pygame.display.flip()
</code>```

Note, the special_flags = BLEND_MULT can also be set when using pygame.Surface.blit():

win.blit(damage, (bgX, bgY), special_flags = pygame.BLEND_MULT)
```

<p>Or even both effects can be combined.</p>

<hr>

<blockquote>
  <p>That's not exactly the effect I was looking for [...] I would like this effect to sort of scale itself inwards and then outwards, ...</p>
</blockquote>

<p>What you want to do is tricky, because you would have to change each pixel of the damage surface dynamically. That would be much to slow.</p>

<p>But you can precalculate different damage surfaces, depending on an effect scale:</p>

<pre class="lang-py prettyprint-override"><code>def smmothstep(edge0, edge1, x):
    t = min(1, max(0, (x - edge0) / (edge1 - edge0)))
    return t * t * (3.0 - 2.0 * t)

def gen_damage_image(scale, source):
    dest = source.copy()
    img_size = dest.get_size()
    for i in range(img_size[0]):
        for j in range(img_size[1]):
            fx = smmothstep(0, img_size[0]/2*scale, min(i, img_size[0]-i))
            fy = smmothstep(0, img_size[1]/2*scale, min(j, img_size[1]-j))
            color =  dest.get_at((i, j))
            fade_color = [int(255 - (1-fx*fy)*(255 - c)) for c in color]
            dest.set_at((i, j), fade_color)
    return dest

damage = pygame.image.load("defensiveGameHUD.png").convert_alpha()
max_dmg_img = 10
dmg_list = [gen_damage_image((i+1)/max_dmg_img, damage) for i in range(max_dmg_img)]
</code>```

tintDamage choose a damage image of the list, dependent on the scale:

def tintDamage(surface, scale):
    i = min(len(dmg_list)-1, max(0, int(scale*(len(dmg_list)-0.5))))
    c.blit(dmg_list[i], (0, 0), special_flags = pygame.BLEND_MULT)
```

<p>The <em>inwards / outwards</em> effect can be achieved by a sine function. See the example, which starts the effect when <kbd>x</kbd> is pressed: </p>

<p><img src="https://i.stack.imgur.com/rQo5e.gif" alt=""></p>

<pre class="lang-py prettyprint-override"><code>run = True
start_time = 0
tint = 0
damage_effect = False
while run:
    clock.tick(60)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_x:
                damage_effect = True
                tint = 0

    win.fill((196, 196, 196))

    # [...]

    if damage_effect:
        scale = math.sin(tint)
        tintDamage(win, scale)
        tint += 0.1
        damage_effect = scale >= 0
    pygame.display.flip()
</code>```

Since the computation of the images is very slow, I provide a solution, which generated a scale mask on a 20x20 image. The mask is scaled to the size of the damage image and blended with the damage image:

def gen_damage_image(scale, source):
    scale_size = (20, 20)
    scale_img = pygame.Surface(scale_size, flags = pygame.SRCALPHA)
    for i in range(scale_size[0]):
        for j in range(scale_size[1]):
            fx = smmothstep(0, scale_size[0]/2*scale, min(i, scale_size[0]-i))
            fy = smmothstep(0, scale_size[1]/2*scale, min(j, scale_size[1]-j))
            fade_color = [int(max(0, 255 - (1-fx*fy)*255)) for c in range(4)]
            scale_img.set_at((i, j), fade_color)
    dest = source.copy()
    scale_img = pygame.transform.smoothscale(scale_img, dest.get_size())
    dest.blit(scale_img, (0, 0), special_flags = pygame.BLEND_ADD)
    return dest
```

Body:
I'm making a 2D game in python using the module pygame. I would like to create a red vignette/bleed effect whenever the player takes damage in my game.  This is seen in many games today, where the edges of the screen will flash red for a second and quickly disappear.

I have tried blitting an image I made in photoshop and scaling it accordingly during an animation cycle, but this was a really performance heavy operation, subsequently causing a lot of lag.  I'm looking for alternatives to this method.

Code declaring a few variables:

bgX = 0
bgY = 0
damage = pygame.image.load("defensiveGameHUD.png").convert_alpha()
dimensions = [1920,1080]

Then I have this in the main loop of my game:

win.blit(background,(0,0))

if dimensions[0] != 4020:
    dimensions[0] += 30
    bgX -= 15
if dimensions[1] != 4600:
    dimensions[1] += 40
    bgY -= 20

if dimensions[1] != 4600:
    screenDamage = pygame.transform.scale(damage, dimensions)
    win.blit(screenDamage, (bgX, bgY))
else:
    screenDamage = None

That is simply an animation that will scale the image in, however, the scaling is improper and this is very costly on performance.

def smmothstep(edge0, edge1, x):
    t = min(1, max(0, (x - edge0) / (edge1 - edge0)))
    return t * t * (3.0 - 2.0 * t)

def gen_damage_image(scale, source):
    dest = source.copy()
    img_size = dest.get_size()
    for i in range(img_size[0]):
        for j in range(img_size[1]):
            fx = smmothstep(0, img_size[0]/2*scale, min(i, img_size[0]-i))
            fy = smmothstep(0, img_size[1]/2*scale, min(j, img_size[1]-j))
            color =  dest.get_at((i, j))
            fade_color = [int(255 - (1-fx*fy)*(255 - c)) for c in color]
            dest.set_at((i, j), fade_color)
    return dest

def tintDamage(surface, scale):
    i = min(len(dmg_list)-1, max(0, int(scale*(len(dmg_list)-0.5))))
    c.blit(dmg_list[i], (0, 0), special_flags = pygame.BLEND_MULT)

damage = pygame.image.load("defensiveGameHUD.png").convert_alpha()
max_dmg_img = 10
dmg_list = [gen_damage_image((i+1)/max_dmg_img, damage) for i in range(max_dmg_img)]

start_time = 0
tint = 0
damage_effect = False

Body:
To tint the screen in red can be achieved by pygame.Surface.fill(), by setting special_flags = BLEND_MULT.

The following function "tints" the entire surface in red, by a scale from 0 to 1. If scale is 0, the surface is not tinted and if scale is 1 the entire surface is tinted by the (red) color (255, 0, 0):

def tintDamage(surface, scale):
    GB = min(255, max(0, round(255 * (1-scale))))
    surface.fill((255, GB, GB), special_flags = pygame.BLEND_MULT)

The function has to be called right before pygame.display.flip() or pygame.display.update():

e.g.

tintDamage(win, 0.5)
pygame.display.flip()

Note, the special_flags = BLEND_MULT can also be set when using pygame.Surface.blit():

win.blit(damage, (bgX, bgY), special_flags = pygame.BLEND_MULT)

Or even both effects can be combined.

That's not exactly the effect I was looking for [...] I would like this effect to sort of scale itself inwards and then outwards, ...

What you want to do is tricky, because you would have to change each pixel of the damage surface dynamically. That would be much to slow.

But you can precalculate different damage surfaces, depending on an effect scale:

def smmothstep(edge0, edge1, x):
    t = min(1, max(0, (x - edge0) / (edge1 - edge0)))
    return t * t * (3.0 - 2.0 * t)

def gen_damage_image(scale, source):
    dest = source.copy()
    img_size = dest.get_size()
    for i in range(img_size[0]):
        for j in range(img_size[1]):
            fx = smmothstep(0, img_size[0]/2*scale, min(i, img_size[0]-i))
            fy = smmothstep(0, img_size[1]/2*scale, min(j, img_size[1]-j))
            color =  dest.get_at((i, j))
            fade_color = [int(255 - (1-fx*fy)*(255 - c)) for c in color]
            dest.set_at((i, j), fade_color)
    return dest

damage = pygame.image.load("defensiveGameHUD.png").convert_alpha()
max_dmg_img = 10
dmg_list = [gen_damage_image((i+1)/max_dmg_img, damage) for i in range(max_dmg_img)]

tintDamage choose a damage image of the list, dependent on the scale:

def tintDamage(surface, scale):
    i = min(len(dmg_list)-1, max(0, int(scale*(len(dmg_list)-0.5))))
    c.blit(dmg_list[i], (0, 0), special_flags = pygame.BLEND_MULT)

The inwards / outwards effect can be achieved by a sine function. See the example, which starts the effect when x is pressed:

run = True
start_time = 0
tint = 0
damage_effect = False
while run:
    clock.tick(60)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_x:
                damage_effect = True
                tint = 0

    win.fill((196, 196, 196))

    # [...]

    if damage_effect:
        scale = math.sin(tint)
        tintDamage(win, scale)
        tint += 0.1
        damage_effect = scale >= 0
    pygame.display.flip()

Since the computation of the images is very slow, I provide a solution, which generated a scale mask on a 20x20 image. The mask is scaled to the size of the damage image and blended with the damage image:

def gen_damage_image(scale, source):
    scale_size = (20, 20)
    scale_img = pygame.Surface(scale_size, flags = pygame.SRCALPHA)
    for i in range(scale_size[0]):
        for j in range(scale_size[1]):
            fx = smmothstep(0, scale_size[0]/2*scale, min(i, scale_size[0]-i))
            fy = smmothstep(0, scale_size[1]/2*scale, min(j, scale_size[1]-j))
            fade_color = [int(max(0, 255 - (1-fx*fy)*255)) for c in range(4)]
            scale_img.set_at((i, j), fade_color)
    dest = source.copy()
    scale_img = pygame.transform.smoothscale(scale_img, dest.get_size())
    dest.blit(scale_img, (0, 0), special_flags = pygame.BLEND_ADD)
    return dest


问:
what is the difference between Using Xml Parser and Xpath in XML
I Would like to know what are the difference between Using Xml Parser and Xpath in XML.Because, both are used to get the any pieces of information in the xml document.That why i asked this question...</p>

答:
An XML Parser parses the XML-file and creates an object representing the XML document and adhering to the DOM standard. Via this interface you can iterate over the XML document and retrieve the information you want.

XPath is a language to define queries on XML-documents. To be of any use there must be an engine/program which "understands" that language, parses the XML and retrieves the information accordingly.


问:
Talend ESB: How to Consume messages from Queue Only When Database end point is running?
Can you please help me with the below scenario?

Q1. I am consuming messages from ActiveMQ and inserting the consumed messages in the Database table. For some reason, if Database is down I am losing the message. How can I prevent the message without losing them?

Q2. I have to consume the message from the Queue only when the target database is up and running.

I have created a Java Bean code to check the database is up and running. But I am stuck and not able to achieve that. Any help will be much appreciated, please.

Consume the message from the Queue only when the database is up and running.

答: You can use cTalend job before cJMS and create the database connection inside the cTalendJob and pass the return code outside the talend job and check in the route if it is 200 then redirect to the cJMS flow otherwise nothing.</p>


问:
i can't delete image and i get unlink
I can not delete an article or image in case I delete anything that shows the page Whoops

if(!function_exists('image_delete')){
    function image_delete($dir){
        unlink(public_path().'/'.$dir);
    }
}```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Article $article)
    {
        image_delete($article->image); // its helper function
        $article->delete();
        return back()->with('success','تم حذف المقال !!');
    }</code>```

this my problem

答:
Before, you delete any files or folder please check the file or folder exists or not. change your helper code like this. here file_exist function check you dir or files exists or not.</p>

```<code>if(!function_exists('image_delete')){
    function image_delete($dir){
      if(file_exists($dir))
        unlink(public_path().'/'.$dir);
    }
}
</code>```

Title: i can't delete image and i get unlink

Body:
I can not delete an article or image in case I delete anything that shows the page Whoops

if(!function_exists('image_delete')){
    function image_delete($dir){
        unlink(public_path().'/'.$dir);
    }
}

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Article $article)
    {
        image_delete($article->image); // its helper function
        $article->delete();
        return back()->with('success','تم حذف المقال !!');
    }

this my problem

Body:
Before, you delete any files or folder please check the file or folder exists or not. change your helper code like this. here file_exist function check you dir or files exists or not.

if(!function_exists('image_delete')){
    function image_delete($dir){
      if(file_exists($dir))
        unlink(public_path().'/'.$dir);
    }
}