问:
AVPlayer AVPlayerWaitingWhileEvaluatingBufferingRateReason slow loading for larger videos
I have an AVPlayer that is playing a moderately large video (~150mb). When loading the video initially, I find that the player remains idle for upwards of 10-15 seconds in the AVPlayerWaitingWhileEvaluatingBufferingRateReason state. My question is simple: how can I prevent AVPlayer from "evaluating the buffering rate reason" for this long and instead move to immediately playing the video?

I am using a custom resource loader (although this same behaviour is exhibited without using a custom resource loader). Here is the relevant code for creating the AVPlayer (all standard boilerplate):

```<code>AVURLAsset * const playerAsset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
[[playerAsset resourceLoader] setDelegate:self queue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)];

AVPlayerItem * const playerItem = [[AVPlayerItem alloc] initWithAsset:playerAsset];

AVPlayer * const player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
[player play];
_player = player;
</code>```

I then have a method for handling the data request, which I can use to get more information about what the AVPlayer is attempting to load:

```<code>-(void)handleDataRequest:(AVAssetResourceLoadingDataRequest *)dataRequest loadingRequest:(AVAssetResourceLoadingRequest *)loadingRequest {

    NSLog(@"handleDataRequest: %lld-%lld (%@)",[dataRequest requestedOffset],[dataRequest requestedOffset] + [dataRequest requestedLength],[[self player] reasonForWaitingToPlay]);

    NSMutableURLRequest * const request = ... // construct the request
    [request setValue:[NSString stringWithFormat:@"bytes=%lld-%lld",[dataRequest requestedOffset],[dataRequest requestedOffset] + [dataRequest requestedLength]] forHTTPHeaderField:@"Range"];

    NSURLSession * const downloadURLSession = ... // get the session
    NSURLSessionDataTask * const dataTask = [downloadURLSession dataTaskWithRequest:request];
    [dataTask resume];

}
</code>```

Now, on to the issue. Suppose the video length is ~100mb, here's the result of that handleDataRequest log in the above method:

```<code>handleDataRequest: 0-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 3080192-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 5570560-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 7143424-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 9699328-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 12713984-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 14811136-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 17235968-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 20054016-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 22675456-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 25427968-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 28311552-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 30932992-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 32374784-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 35192832-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 37224448-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 39780352-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 41549824-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 43778048-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 46465024-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 49414144-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 52166656-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 54984704-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 57802752-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 60293120-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 62783488-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 65732608-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 68550656-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 70975488-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 73531392-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 76480512-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 79495168-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 82313216-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 83951616-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 86573056-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 88866816-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 91422720-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 92667904-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 95289344-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 98172928-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 32768-5570560 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 2032769-5570560 (AVPlayerWaitingToMinimizeStallsReason)
handleDataRequest: 4032770-5570560 (AVPlayerWaitingToMinimizeStallsReason)
handleDataRequest: 5668864-22675456 ((null))
handleDataRequest: 7668865-22675456 ((null))
handleDataRequest: 9668866-22675456 ((null))
handleDataRequest: 11668867-22675456 ((null))
handleDataRequest: 13668868-22675456 ((null))
</code>```

As you can see, there's nearly 40 HTTP requests just to evaluate the buffering state reason. This takes a very long amount of time.

Here's what I've tried:

Use AVPlayer's playImmediatelyAtRate: instead of play

I saw this suggestion online. I suppose the logic is that playing immediately would do just that, play immediately. This does not work as the player still takes the time (and the requests) to evaluate the buffering rate reason before playing.

Set AVPlayer's automaticallyWaitsToMinimizeStalling to NO

Seems reasonable. We can tell the player not to wait to minimize stalling. Unfortunately, this fails as the player still makes the same requests to evaluate the buffering rate before playing (oddly enough, however, the reasonForWaitingToPlay is null while this is taking place).

Call the loading request's finishLoading method to immediately accelerate the buffering rate evaluation

The logic here was that instead of firing actual HTTP requests while the AVPlayer was evaluating the buffering rate, I could immediately signal that loading was finished. The results of this varied. In some tests, the video would play immediately but only play for a couple of seconds whereas in other tests, the video failed to play at all and would time out.

In conclusion, is there any way to avoid this delay when playing larger videos? Is it truly necessary that the AVPlayer must evaluate the buffering rate prior to starting a video?

答:
Apple has confirmed that the issue is not the size of the video, but instead a malformed MP4 with too many moof+mdat atoms.

At this point in time, this has been determined to be working as intended. Although, I would like to see some way to avoid this initial buffering in the future, even if the MP4 is malformed.

Body:
I have an AVPlayer that is playing a moderately large video (~150mb). When loading the video initially, I find that the player remains idle for upwards of 10-15 seconds in the AVPlayerWaitingWhileEvaluatingBufferingRateReason state. My question is simple: how can I prevent AVPlayer from "evaluating the buffering rate reason" for this long and instead move to immediately playing the video?

I am using a custom resource loader (although this same behaviour is exhibited without using a custom resource loader). Here is the relevant code for creating the AVPlayer (all standard boilerplate):

AVURLAsset * const playerAsset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
[[playerAsset resourceLoader] setDelegate:self queue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)];

AVPlayerItem * const playerItem = [[AVPlayerItem alloc] initWithAsset:playerAsset];

AVPlayer * const player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
[player play];
_player = player;

I then have a method for handling the data request, which I can use to get more information about what the AVPlayer is attempting to load:

-(void)handleDataRequest:(AVAssetResourceLoadingDataRequest *)dataRequest loadingRequest:(AVAssetResourceLoadingRequest *)loadingRequest {

    NSLog(@"handleDataRequest: %lld-%lld (%@)",[dataRequest requestedOffset],[dataRequest requestedOffset] + [dataRequest requestedLength],[[self player] reasonForWaitingToPlay]);

    NSMutableURLRequest * const request = ... // construct the request
    [request setValue:[NSString stringWithFormat:@"bytes=%lld-%lld",[dataRequest requestedOffset],[dataRequest requestedOffset] + [dataRequest requestedLength]] forHTTPHeaderField:@"Range"];

    NSURLSession * const downloadURLSession = ... // get the session
    NSURLSessionDataTask * const dataTask = [downloadURLSession dataTaskWithRequest:request];
    [dataTask resume];

}

Now, on to the issue. Suppose the video length is ~100mb, here's the result of that handleDataRequest log in the above method:

handleDataRequest: 0-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 3080192-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 5570560-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 7143424-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 9699328-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 12713984-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 14811136-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 17235968-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 20054016-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 22675456-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 25427968-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 28311552-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 30932992-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 32374784-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 35192832-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 37224448-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 39780352-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 41549824-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 43778048-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 46465024-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 49414144-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 52166656-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 54984704-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 57802752-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 60293120-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 62783488-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 65732608-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 68550656-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 70975488-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 73531392-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 76480512-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 79495168-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 82313216-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 83951616-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 86573056-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 88866816-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 91422720-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 92667904-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 95289344-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 98172928-100000000 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 32768-5570560 (AVPlayerWaitingWhileEvaluatingBufferingRateReason)
handleDataRequest: 2032769-5570560 (AVPlayerWaitingToMinimizeStallsReason)
handleDataRequest: 4032770-5570560 (AVPlayerWaitingToMinimizeStallsReason)
handleDataRequest: 5668864-22675456 ((null))
handleDataRequest: 7668865-22675456 ((null))
handleDataRequest: 9668866-22675456 ((null))
handleDataRequest: 11668867-22675456 ((null))
handleDataRequest: 13668868-22675456 ((null))

As you can see, there's nearly 40 HTTP requests just to evaluate the buffering state reason. This takes a very long amount of time.

Here's what I've tried:

Use AVPlayer's playImmediatelyAtRate: instead of play

I saw this suggestion online. I suppose the logic is that playing immediately would do just that, play immediately. This does not work as the player still takes the time (and the requests) to evaluate the buffering rate reason before playing.

Set AVPlayer's automaticallyWaitsToMinimizeStalling to NO

Seems reasonable. We can tell the player not to wait to minimize stalling. Unfortunately, this fails as the player still makes the same requests to evaluate the buffering rate before playing (oddly enough, however, the reasonForWaitingToPlay is null while this is taking place).

Call the loading request's finishLoading method to immediately accelerate the buffering rate evaluation

The logic here was that instead of firing actual HTTP requests while the AVPlayer was evaluating the buffering rate, I could immediately signal that loading was finished. The results of this varied. In some tests, the video would play immediately but only play for a couple of seconds whereas in other tests, the video failed to play at all and would time out.

In conclusion, is there any way to avoid this delay when playing larger videos? Is it truly necessary that the AVPlayer must evaluate the buffering rate prior to starting a video?


来源: stackexchange

问:
influx aggregateWindow with continuous counter
An influx 2 database stores incrementing values from an mechanical counter (gas counter).
The goal is to build a query to get the consumption over a certain interval, e.g. one day.
With SQL I would group the data in the desired interval and than calculate max() - min()  +1 for that interval.
What is the preferred way to do that with the flux query language?

```<code>from(bucket: "Energy")
|> range(start: v.timeRangeStart, stop: v.timeRangeStop)
|> filter(fn: (r) => r["_measurement"] == "gas")
|> filter(fn: (r) => r["kind"] == "count")
|> aggregateWindow(every: 24h, fn: difference, createEmpty: false)
|> yield(name: "interval")
</code>```

does not work, error @5:6-5:69: missing required argument column (argument fn)

答:
The solution is to examine difference() before aggregateWindow and as aggregate function to use sum.</p>
```<code>from(bucket: "Energy")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> filter(fn: (r) => r["_measurement"] == "gas")
  |> filter(fn: (r) => r["_field"] == "count")
  |> difference()
  |> aggregateWindow(every: 1h, fn: sum, createEmpty: false)
  |> yield(name: "consumption")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
An influx 2 database stores incrementing values from an mechanical counter (gas counter).
The goal is to build a query to get the consumption over a certain interval, e.g. one day.
With SQL I would group the data in the desired interval and than calculate max() - min()  +1 for that interval.
What is the preferred way to do that with the flux query language?

from(bucket: "Energy")
|> range(start: v.timeRangeStart, stop: v.timeRangeStop)
|> filter(fn: (r) => r["_measurement"] == "gas")
|> filter(fn: (r) => r["kind"] == "count")
|> aggregateWindow(every: 24h, fn: difference, createEmpty: false)
|> yield(name: "interval")

does not work, error @5:6-5:69: missing required argument column (argument fn)

Body:
The solution is to examine difference() before aggregateWindow and as aggregate function to use sum.

from(bucket: "Energy")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> filter(fn: (r) => r["_measurement"] == "gas")
  |> filter(fn: (r) => r["_field"] == "count")
  |> difference()
  |> aggregateWindow(every: 1h, fn: sum, createEmpty: false)
  |> yield(name: "consumption")


问:
PHP check if point is inside a circle
I have codes below

circle.php

```<code>class point{
    private $x;
    private $y;

    function __construct($x, $y){
        $this->x = $x;
        $this->y = $y;
    }

    public function getX(){
        return $this->x;
    }

    public function getY(){
        return $this->y;
    }

}

class circle{
    private $x_circle;
    private $y_circle;
    private $radius;

    function __construct($x_circle, $y_circle, $radius){
        $this->x_circle = $x_circle;
        $this->y_circle = $y_circle;
        $this->radius = $radius;
    }

    public function getCircleX(){
        return $this->x_circle;
    }

    public function getCircleY(){
        return $this->y_circle;
    }

    public function getRadius(){
        return $this->radius;
    }

    public function checkIfInside(){
        if(pow(getX() - getCircleX(), 2) + pow(getY() - getCircleY(), 2) < pow(getRadius(),2)){
            return true;
        } else {
            return false;
        }

    }
}
</code>```

index.php

```<code>include 'circle.php';

$point= new point(3, 4);
$circle= new circle(10, 10, 100);
$circle->checkIfInside();
</code>```

I try to check if point is inside a circle. With point class we declare point coordinates(x,y). With circle class we declare the coordinates of circle(x,y) and radius. But I get this error: Uncaught Error: Call to undefined function getX()

答:
You need to fix your checkIfInside function. It should receive a point as an argument. Also it lacks $point and $this references when calling methods.

```<code>public function checkIfInside($point) {
    return pow($point->getX() - $this->getCircleX(), 2) + pow($point->getY() - $this->getCircleY(), 2) < pow($this->getRadius(),2))
}
</code>```

Also, you should pass the point as an argument in your main code.

```<code>include 'circle.php';

$point = new point(3, 4);
$circle = new circle(10, 10, 100);
$circle->checkIfInside($point);
</code>```

Title: PHP check if point is inside a circle

Body:
I have codes below

circle.php

class point{
    private $x;
    private $y;

    function __construct($x, $y){
        $this->x = $x;
        $this->y = $y;
    }

    public function getX(){
        return $this->x;
    }

    public function getY(){
        return $this->y;
    }

}

class circle{
    private $x_circle;
    private $y_circle;
    private $radius;

    function __construct($x_circle, $y_circle, $radius){
        $this->x_circle = $x_circle;
        $this->y_circle = $y_circle;
        $this->radius = $radius;
    }

    public function getCircleX(){
        return $this->x_circle;
    }

    public function getCircleY(){
        return $this->y_circle;
    }

    public function getRadius(){
        return $this->radius;
    }

    public function checkIfInside(){
        if(pow(getX() - getCircleX(), 2) + pow(getY() - getCircleY(), 2) < pow(getRadius(),2)){
            return true;
        } else {
            return false;
        }

    }
}

index.php

include 'circle.php';

$point= new point(3, 4);
$circle= new circle(10, 10, 100);
$circle->checkIfInside();

I try to check if point is inside a circle. With point class we declare point coordinates(x,y). With circle class we declare the coordinates of circle(x,y) and radius. But I get this error: Uncaught Error: Call to undefined function getX()

Body:
You need to fix your checkIfInside function. It should receive a point as an argument. Also it lacks $point and $this references when calling methods.

public function checkIfInside($point) {
    return pow($point->getX() - $this->getCircleX(), 2) + pow($point->getY() - $this->getCircleY(), 2) < pow($this->getRadius(),2))
}

Also, you should pass the point as an argument in your main code.

include 'circle.php';

$point = new point(3, 4);
$circle = new circle(10, 10, 100);
$circle->checkIfInside($point);


问:
How to visually indicate custom keyboard shortcuts on web apps
While there is a WebAIM guideline on keyboard accessibility, I was unable to find any guidelines - or even recommendations - about how to convey the existence of custom keyboard shortcuts to sighted people.

For screen reader users like myself it is simple enough:

```<code><input type="submit" aria-keyshortcuts="Alt+S" value="Send" />
</code>```

A screen reader would then announce "Send button Alt plus S" and the keyboard shortcut would also be apparent for braille display users.

Sighted users who cannot or do not want to use the mouse, however, need a simple indicator of which keyboard shortcuts are available on a given control so that they have a similar user experience and don't have to search for lists of keyboard shortcuts in separate documentation. (Such lists are, of course, important, but they shouldn't be the only way for sighted users to know which keyboard shortcuts they can use.)

Can you provide me with resources or suggestions how to visually indicate available keyboard shortcuts?

答:
The guidance for aria-keyshortcuts says:

Authors SHOULD provide a way to expose keyboard shortcuts so that all users may discover them, such as through the use of a tooltip.

which is essentially what you're asking about.  You know you should convey the information to all users but how should that info be conveyed?  A tooltip, as suggested in the spec, is one possibility but only if that tooltip is exposed for keyboard users too.  Currently, a tooltip (title attribute) is only displayed upon mouse hover with Firefox and Chrome (not sure about Safari).  Say what you will about Internet Explorer but IE would display the tooltip upon keyboard focus so that's a great feature.  That feature was carried forward into Edge as well.

So you can use a tooltip but would still need another way to convey that information for all users.  If space allows, I often see the keyboard hint as text right on the page.  Ideally, the hint is near the element it applies to but if there are several shortcut keys, then having a section with all the keys listed might be a better option.  Have an appropriate <h#> element for that section to make it easier to find with a screen reader.

Note that using the accesskey attribute for the shortcut key will automatically be announced by screen readers so you wouldn't need aria-keyshortcuts.  But that attribute only allows a simple letter and would still have the issue of it not being conveyed to sighted keyboard users.  Browsers should automatically display a tooltip for an element with an accesskey but sadly they don't.

Another alternative is suggested in this answer, How to display a specific shortcut key in HTML?.  Look at the CSS solution (link should go directly to that answer) but instead of referring to accesskey in the CSS, refer to aria-keyshortcuts.  (Ignore the javascript part of that answer.)

Body:
While there is a WebAIM guideline on keyboard accessibility, I was unable to find any guidelines - or even recommendations - about how to convey the existence of custom keyboard shortcuts to sighted people.

For screen reader users like myself it is simple enough:

<input type="submit" aria-keyshortcuts="Alt+S" value="Send" />

A screen reader would then announce "Send button Alt plus S" and the keyboard shortcut would also be apparent for braille display users.

Sighted users who cannot or do not want to use the mouse, however, need a simple indicator of which keyboard shortcuts are available on a given control so that they have a similar user experience and don't have to search for lists of keyboard shortcuts in separate documentation. (Such lists are, of course, important, but they shouldn't be the only way for sighted users to know which keyboard shortcuts they can use.)

Can you provide me with resources or suggestions how to visually indicate available keyboard shortcuts?


问:
Ruby on Rails Routing Question
I'm working on a website where users can sell tickets to their events. Tickets being sold for events are going to be promoted by promoters. In turn, the client wants a unique url that a promoter can email out to potential customers to sell tickets to.  Thus, I have to create a unique url that includes the promoters unique code along with an event id (To track sales).  The problem I am having is figuring out how to create this unique url. There's a many-to-many relationship between Event and Promoter joined together by a Promotion table.  The Promotion table will track each event's promoters as well as have an attribute to store how many tickets sold. In the Promoter table I will store basic information, such as name, along with the unique code the system will generate.

I know I can create a named route that can find an Event by id or a Promoter by id. The problem is I need to have the Event Id in the url along with the promoters unique code (unless there's a better way to do this). I will then be able to write a query to find an Event with a condition of the Promoter's unique code.

Any thoughts on how I might accomplish this? I think what is stumping me is that there is two parameters in the url.

Update:

```<code>map.buy_ticket 'buy_ticket/:id_1/:id_2',
 :controller => :events,
 :action => :buyTicket,
 :id_1 => /\d+/,
 :id_2 => /[a-z]+[0-9]+/i
</code>```

答:
You can find the answer at your own question. When I the share link to this question, here's what I have:

```<code>http://stackoverflow.com/q/7102231/293686
</code>```

The number 7102231 is your question id and 293686 is my user id, so, when I share this question somewhere else SO knows it was me that did it, which is the same thing you're trying to do, just create a route that contains both ids and you're done.

ContentLicense: CC BY-SA 3.0

Title: Ruby on Rails Routing Question

Body:
I'm working on a website where users can sell tickets to their events. Tickets being sold for events are going to be promoted by promoters. In turn, the client wants a unique url that a promoter can email out to potential customers to sell tickets to.  Thus, I have to create a unique url that includes the promoters unique code along with an event id (To track sales).  The problem I am having is figuring out how to create this unique url. There's a many-to-many relationship between Event and Promoter joined together by a Promotion table.  The Promotion table will track each event's promoters as well as have an attribute to store how many tickets sold. In the Promoter table I will store basic information, such as name, along with the unique code the system will generate.

I know I can create a named route that can find an Event by id or a Promoter by id. The problem is I need to have the Event Id in the url along with the promoters unique code (unless there's a better way to do this). I will then be able to write a query to find an Event with a condition of the Promoter's unique code.

Any thoughts on how I might accomplish this? I think what is stumping me is that there is two parameters in the url.

Update:

map.buy_ticket 'buy_ticket/:id_1/:id_2',
 :controller => :events,
 :action => :buyTicket,
 :id_1 => /\d+/,
 :id_2 => /[a-z]+[0-9]+/i

Body:
You can find the answer at your own question. When I the share link to this question, here's what I have:

http://stackoverflow.com/q/7102231/293686

The number 7102231 is your question id and 293686 is my user id, so, when I share this question somewhere else SO knows it was me that did it, which is the same thing you're trying to do, just create a route that contains both ids and you're done.


问:
Unable to reference path for a folder of csv files
https://colab.research.google.com/drive/1C5Fnf8Rxq8wG2fGakvbWQ9AKu9cLsnr8#scrollTo=DZ7srOAiN1in

Above is the link to my Google Colab notebook.

I have downloaded a folder of multiple csv files that I am trying to reference. Here is my current path:'drive/MyDrive/FFP_bro'.

This is the error I am getting: IsADirectoryError: [Errno 21] Is a directory: 'drive/MyDrive/FFP_bro'

答: I can't access your notebook but my guess is that the path address is not correct. You might want to show a snippet of your code and your directory architecture to get answers.</p>


问:
Combining two ffmpeg commands
At the moment, I managed to achieve my goal by issuing these two commands:

```<code>ffmpeg -y -f ogg -i pipe:0 -c:a libfdk_aac tmp.m4a
ffmpeg -y -i tmp.m4a -i ${PATH_DIR}cover.jpg -map 0 -map 1 -c copy -c:v:1 mpeg -disposition:v:0 attached_pic -metadata title="${title}" -metadata album="${album}" -metadata artist="${artist}" "${fname}"
</code>```

How to combine them into one command?

答:
You can pipe the ffmpeg output from one command to the other:

```<code>ffmpeg -i example.mp4 -f mpeg pipe:1 | ffmpeg -i pipe:0 example.mov
</code>```

-f defines the format of the stream and pipe:1 sends the output to the pipe.

In the second command xou van accept the input via -i pipe:0.

Title: Combining two ffmpeg commands

Body:
At the moment, I managed to achieve my goal by issuing these two commands:

ffmpeg -y -f ogg -i pipe:0 -c:a libfdk_aac tmp.m4a
ffmpeg -y -i tmp.m4a -i ${PATH_DIR}cover.jpg -map 0 -map 1 -c copy -c:v:1 mpeg -disposition:v:0 attached_pic -metadata title="${title}" -metadata album="${album}" -metadata artist="${artist}" "${fname}"

How to combine them into one command?

Body:
You can pipe the ffmpeg output from one command to the other:

ffmpeg -i example.mp4 -f mpeg pipe:1 | ffmpeg -i pipe:0 example.mov

-f defines the format of the stream and pipe:1 sends the output to the pipe.

In the second command xou van accept the input via -i pipe:0.


问:
Limit type of JsonArray elements to the same type, but not limit types
We have the following JSON:

{ "someName" : [1,2,3,4,5] }
```
<p>or</p>
<pre class="lang-json prettyprint-override"><code>{ "someName" : ["one","two","three"] }
</code>```

We want to draft a JSON Schema following the OpenAPI 3.x specification. Our constraint: an array element can be integer or string, but all array elements must be the same type. Our schema looks like this:

{
   "type": "array",
   "items": {
     "oneOf": [
        {"type": "string"},
        {"type": "integer"}
        ]
     }
}
```

This does limit the data type inside the array, but still allows to mix strings and integers in one array which we need to avoid.

<s>{"someName" : 1, "two", "three", 4}</s>

We looked at this question, but it didn't address consistent data type

Is there a way in OpenAPI Schema to enforce uniqueness per array?

答:
You need to bring the oneOf up a level. Also, anyOf is a better choice in this situation. The result is the same in this case, but anyOf is more efficient.

{
   "type": "array",
   "anyOf": [
     { "items": { "type": "string" } },
     { "items": { "type": "integer" } },
   ]
}
```
<p>Edit: In response to comment ...</p>
<p>To work around the bug, you can try pulling the <code>type</code> into the <code>anyOf</code>. The duplication is unfortunate an will make the schema less efficient, but it will probably help get around the bug.</p>
<pre class="lang-json prettyprint-override"><code>{
  "anyOf": [
    {
      "type": "array",
      "items": { "type": "string" }
    },
    {
      "type": "array",
      "items": { "type": "integer" }
    }
  ]
}
</code>```

Body:
We have the following JSON:

{ "someName" : [1,2,3,4,5] }

or

{ "someName" : ["one","two","three"] }

We want to draft a JSON Schema following the OpenAPI 3.x specification. Our constraint: an array element can be integer or string, but all array elements must be the same type. Our schema looks like this:

{
   "type": "array",
   "items": {
     "oneOf": [
        {"type": "string"},
        {"type": "integer"}
        ]
     }
}

This does limit the data type inside the array, but still allows to mix strings and integers in one array which we need to avoid.

<s>{"someName" : 1, "two", "three", 4}</s>

We looked at this question, but it didn't address consistent data type

Is there a way in OpenAPI Schema to enforce uniqueness per array?

Body:
You need to bring the oneOf up a level. Also, anyOf is a better choice in this situation. The result is the same in this case, but anyOf is more efficient.

{
   "type": "array",
   "anyOf": [
     { "items": { "type": "string" } },
     { "items": { "type": "integer" } },
   ]
}

Edit: In response to comment ...

To work around the bug, you can try pulling the type into the anyOf. The duplication is unfortunate an will make the schema less efficient, but it will probably help get around the bug.

{
  "anyOf": [
    {
      "type": "array",
      "items": { "type": "string" }
    },
    {
      "type": "array",
      "items": { "type": "integer" }
    }
  ]
}


问:
@typescript-eslint/naming-convention break linting
So I would like to allow _ on function parameters IF they are not used.

I edited my eslint rule :

"@typescript-eslint/naming-convention"

with

```<code>          {
            "selector": "parameter",
            "modifiers": ["unused"],
            "trailingUnderscore": "require"
          },
    ```

Following the guide

https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/naming-convention.md#individual-selectors

This sould work, but I get the following error :

```
```    Value {"selector":"parameter","modifiers":["unused"],"trailingUnderscore":"require"} should have required property 'format'.
    Value {"selector":"parameter","modifiers":["unused"],"trailingUnderscore":"require"} should match exactly one schema in oneOf.
```
``````

答:
You must include the format property for the rule as an array or null value, such as:

```<code>{
    "format": null,
    "selector": "parameter",
    "modifiers": ["unused"],
    "trailingUnderscore": "require"
}
</code>```

Or:

```<code>{
    "format": ["PascalCase"],
    ...
}
</code>```

Body:
So I would like to allow _ on function parameters IF they are not used.

I edited my eslint rule :

"@typescript-eslint/naming-convention"

with

          {
            "selector": "parameter",
            "modifiers": ["unused"],
            "trailingUnderscore": "require"
          },
    ```

Following the guide

https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/naming-convention.md#individual-selectors

This sould work, but I get the following error :

    Value {"selector":"parameter","modifiers":["unused"],"trailingUnderscore":"require"} should have required property 'format'.
    Value {"selector":"parameter","modifiers":["unused"],"trailingUnderscore":"require"} should match exactly one schema in oneOf.

Body:
You must include the format property for the rule as an array or null value, such as:

{
    "format": null,
    "selector": "parameter",
    "modifiers": ["unused"],
    "trailingUnderscore": "require"
}

Or:

{
    "format": ["PascalCase"],
    ...
}


问:
Group array of string arrays with LINQ
I have array like this, values are string:

```<code>var arr1 = new [] { "H", "item1", "item2" };
var arr2 = new [] { "T", "thing1", "thing2" };
var arr3 = new [] { "T", "thing1", "thing2" };
var arr4 = new [] { "END", "something" };
var arr5 = new [] { "H", "item1", "item2" };
var arr6 = new [] { "T", "thing1", "thing2" };
var arr7 = new [] { "T", "thing1", "thing2" };
var arr8 = new [] { "END", "something" };

var allArrays = new [] { arr1, arr2, arr3, arr4, arr5, arr6, arr7, arr8 };
</code>```

I need to group this in to a new array of arrays, so that one array has arrays that start with H or T. The END records (not included in the results) are the delimiters between each section; each new array starts after an END array.

In the end I would like to have somethng like this:

```<code>[
[ [H, item1, item2], [T, thing1, thing2], [T, thing1, thing2] ]
[ [H, item1, item2], [T, thing1, thing2], [T, thing1, thing2] ]
]
</code>```

I know how I can do this with for each loop, but I'm looking for a cleaner way, possibly using linq. All suggestions are much valued, thank you!

答:
you can try this

```<code>List<string[]> list = new List<string[]>();
var newArr = allArrays.Select(a => AddToArr(list, a)).Where(a => a != null);
</code>```

and helper (this code can be put inline, but it easier to read this way)

```<code>private static string[][] AddToArr(List<string[]> list, string[] arr)
{
    if (arr[0] != "END")
    {
        list.Add(arr);
        return null;
    }
    var r = list.ToArray();
    list.Clear();
    return r;
}
</code>```

result

```<code>[
[["H","item1","item2"],["T","thing1","thing2"],["T","thing1","thing2"]],
[["H","item3","item4"],["T","thing3","thing4"],["T","thing5","thing6"]]
]
</code>```

Title: Group array of string arrays with LINQ

Body:
I have array like this, values are string:

var arr1 = new [] { "H", "item1", "item2" };
var arr2 = new [] { "T", "thing1", "thing2" };
var arr3 = new [] { "T", "thing1", "thing2" };
var arr4 = new [] { "END", "something" };
var arr5 = new [] { "H", "item1", "item2" };
var arr6 = new [] { "T", "thing1", "thing2" };
var arr7 = new [] { "T", "thing1", "thing2" };
var arr8 = new [] { "END", "something" };

var allArrays = new [] { arr1, arr2, arr3, arr4, arr5, arr6, arr7, arr8 };

I need to group this in to a new array of arrays, so that one array has arrays that start with H or T. The END records (not included in the results) are the delimiters between each section; each new array starts after an END array.

In the end I would like to have somethng like this:

[
[ [H, item1, item2], [T, thing1, thing2], [T, thing1, thing2] ]
[ [H, item1, item2], [T, thing1, thing2], [T, thing1, thing2] ]
]

I know how I can do this with for each loop, but I'm looking for a cleaner way, possibly using linq. All suggestions are much valued, thank you!

Body:
you can try this

List<string[]> list = new List<string[]>();
var newArr = allArrays.Select(a => AddToArr(list, a)).Where(a => a != null);

and helper (this code can be put inline, but it easier to read this way)

private static string[][] AddToArr(List<string[]> list, string[] arr)
{
    if (arr[0] != "END")
    {
        list.Add(arr);
        return null;
    }
    var r = list.ToArray();
    list.Clear();
    return r;
}

result

[
[["H","item1","item2"],["T","thing1","thing2"],["T","thing1","thing2"]],
[["H","item3","item4"],["T","thing3","thing4"],["T","thing5","thing6"]]
]


问:
Flutter New Project Buile Error 18 Problem
I just new. when I created new flutter project, it show 18 error:
that just always happen, but not at the first time I installing flutter

I also check the flutter doctor and there is no problem. Hope u can solve my problem.

答: Probably you are using a old version of the sdk (no null safety), so you can remove the ? after key parameter ou comment the line 8</p>


问:
Variable database name for ContentProvider
I am creating a custom ContentProvider in Android, all the examples I find show the database name being hardcoded, instantiated like this:

```<code>public class ItemProvider extends ContentProvider {

    private static String DATABASE_NAME = "xyz";

    public static class ItemDatabaseHelper extends SQLiteOpenHelper {

    ItemDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);

    }
</code>```

What I want to do is use a variable for the database name at runtime, I dont want to hard code the database name in the class. I have tried to find examples of doing this using the ContentProvider class, and have looked through the documentation as well. I can do this if I shed the ContentProvider class and just use a SQLiteOpenHelper class because I can pass in the database name to the constructor as a parameter but I cannot figure out if its possible for ContentProvider. Here is how I get a variable name for the database using SQLiteOpenHelper:

```<code>public static class ItemDatabaseHelper extends SQLiteOpenHelper {

    ItemDatabaseHelper(Context context, String dbname) {
        super(context, dbname, null, DATABASE_VERSION);
    }
</code>```

Can anyone help me get a variable database name for a Content Provider?

Thanks.

答:
First, let me say that I've looked at lots of examples for ContentProvider code on the web, and the one that ended up helping me the most was this one:

http://mobile.tutsplus.com/tutorials/android/android-sdk_content-providers/

I have a very similar situation to yours, where I want to have several differently-named databases containing vehicle fuel mileage data.  Each of the names consists of a vehicle name (specified by the user) and the current year, plus the fixed text "fuel_data" to make the database filenames human-readable.

Unlike all of the examples I found, I do not create an instance of the database in the ContentProvider's onCreate method.  This is because I don't yet know the vehicle name at that point, thanks to the way my code is written (and the fact that ContentProviders are instantiated so early in the Activity lifecycle).

Once I do know the vehicle name (from which I can easily construct the database name), I call a simple little method that I added to my ContentProvider class.  As you can see, all it does is close the prior database (if one was open) and open the new one (using the name that I now have available).

I call this method again every time the user selects a new vehicle.

`    private static FuelDatabase mDB = null;

```<code> public static void switchDatabases( Context context, String newVehicleName )
 {
     if ( mDB != null )
     {
     mbB.close();
     }

     mDB = new FuelDatabase( context, newVehicleName + "." + getCurrentYear( context ) );
 }`
</code>```

Body:
I am creating a custom ContentProvider in Android, all the examples I find show the database name being hardcoded, instantiated like this:

public class ItemProvider extends ContentProvider {

    private static String DATABASE_NAME = "xyz";

    public static class ItemDatabaseHelper extends SQLiteOpenHelper {

    ItemDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);

    }

What I want to do is use a variable for the database name at runtime, I dont want to hard code the database name in the class. I have tried to find examples of doing this using the ContentProvider class, and have looked through the documentation as well. I can do this if I shed the ContentProvider class and just use a SQLiteOpenHelper class because I can pass in the database name to the constructor as a parameter but I cannot figure out if its possible for ContentProvider. Here is how I get a variable name for the database using SQLiteOpenHelper:

public static class ItemDatabaseHelper extends SQLiteOpenHelper {

    ItemDatabaseHelper(Context context, String dbname) {
        super(context, dbname, null, DATABASE_VERSION);
    }

Can anyone help me get a variable database name for a Content Provider?

Thanks.

Body:
First, let me say that I've looked at lots of examples for ContentProvider code on the web, and the one that ended up helping me the most was this one:

http://mobile.tutsplus.com/tutorials/android/android-sdk_content-providers/

I have a very similar situation to yours, where I want to have several differently-named databases containing vehicle fuel mileage data.  Each of the names consists of a vehicle name (specified by the user) and the current year, plus the fixed text "fuel_data" to make the database filenames human-readable.

Unlike all of the examples I found, I do not create an instance of the database in the ContentProvider's onCreate method.  This is because I don't yet know the vehicle name at that point, thanks to the way my code is written (and the fact that ContentProviders are instantiated so early in the Activity lifecycle).

Once I do know the vehicle name (from which I can easily construct the database name), I call a simple little method that I added to my ContentProvider class.  As you can see, all it does is close the prior database (if one was open) and open the new one (using the name that I now have available).

I call this method again every time the user selects a new vehicle.

`    private static FuelDatabase mDB = null;

 public static void switchDatabases( Context context, String newVehicleName )
 {
     if ( mDB != null )
     {
     mbB.close();
     }

     mDB = new FuelDatabase( context, newVehicleName + "." + getCurrentYear( context ) );
 }`


问:
simple replacement of variables on wolfram-mathematica
I would like to make a simple replacement or substitution:
y=a+b
a=2d+e
b=f+g
How make Wolfram-Mathematica automatically show and make the substitution or replacement of variables a and b an show this result:
y=2d+e  +  f+g

?

答:
Try

```<code>y==a+b/.{a->2d+e,b->f+g}
</code>```

and see if that is what you are looking for.

That takes the expression y==a+b and does the list of substitutions to it

Body:
Try

y==a+b/.{a->2d+e,b->f+g}

and see if that is what you are looking for.

That takes the expression y==a+b and does the list of substitutions to it


问:
localstorage values resetting after refresh and localstorage is not defined
My array and local storage keep resetting after every refresh. I've seen some answers like I need to parse the data and then stringify it. The issue I've faced is I keep getting an error message saying 'local storage is not defined' and an internal server error 500.

I've written the code below

//object

```<code>"items": [
    {
      "id": 119603782,
      "node_id": "MDEwOlJlcG9zaXRvcnkxMTk2MDM3ODI=",
      "name": "react-contextual",
      "full_name": "drcmda/react-contextual",
      "private": false,
     },
{
      "id": 119603782,
      "node_id": "MDEwOlJlcG9zaXRvcnkxMTk2MDM3ODI=",
      "name": "react-contextual",
      "full_name": "drcmda/react-contextual",
      "private": false,
     }

</code>```

Getting the object

```<code>export async function getServerSideProps() {
  const res = await fetch(
    "https://api.github.com/search/repositories?q=created:%3E2017-01-10&sort=stars&order=desc"
  );
  const data = await res.json();

  return {
    props: {
      data,
    },
  };
}
</code>```

This is my function

```<code>//trying to keep the values after a page refresh
const favs = JSON.parse(localStorage.getItem('name')) || [];

//localstorage is not defined
//define it here
const storage = typeof window !== 'undefined'? localStorage.getItem('name') : null

//check for value then store it in array and to local storage
function checkId (e) {
 if(e.target.value !==  ""){
   favs.push(e.target.value)
 //check if it exists
localStorage.getItem('name') === null
 //if exists store it
localStorage.setItem('name', JSON.stringify(favs))
   console.log(favs);

 }
}

    <div className="grid grid-cols-3 rows-2 text-lg font-bold">
         {storage}

    </div>

<div className="grid grid-cols-3 grid-rows-2 gap-2 bg-black text-white border-white">
        {data.items
          .sort(function (a, b) {
            return  new Date (b.created_at) - new Date(a.created_at) || a.stargazers_count - b.stargazers_count
          })
          .map((d) => (

    <button id="btn" onClick={checkId} value={d.name}>Favorite me </button>

</code>```

答:
This was the answer

const favs = typeof window !== "undefined" ? JSON.parse(localStorage.getItem('name')): null || [];

Body:
My array and local storage keep resetting after every refresh. I've seen some answers like I need to parse the data and then stringify it. The issue I've faced is I keep getting an error message saying 'local storage is not defined' and an internal server error 500.

I've written the code below

//object

"items": [
    {
      "id": 119603782,
      "node_id": "MDEwOlJlcG9zaXRvcnkxMTk2MDM3ODI=",
      "name": "react-contextual",
      "full_name": "drcmda/react-contextual",
      "private": false,
     },
{
      "id": 119603782,
      "node_id": "MDEwOlJlcG9zaXRvcnkxMTk2MDM3ODI=",
      "name": "react-contextual",
      "full_name": "drcmda/react-contextual",
      "private": false,
     }

Getting the object

export async function getServerSideProps() {
  const res = await fetch(
    "https://api.github.com/search/repositories?q=created:%3E2017-01-10&sort=stars&order=desc"
  );
  const data = await res.json();

  return {
    props: {
      data,
    },
  };
}

This is my function

//trying to keep the values after a page refresh
const favs = JSON.parse(localStorage.getItem('name')) || [];

//localstorage is not defined
//define it here
const storage = typeof window !== 'undefined'? localStorage.getItem('name') : null

//check for value then store it in array and to local storage
function checkId (e) {
 if(e.target.value !==  ""){
   favs.push(e.target.value)
 //check if it exists
localStorage.getItem('name') === null
 //if exists store it
localStorage.setItem('name', JSON.stringify(favs))
   console.log(favs);

 }
}

         {storage}

        {data.items
          .sort(function (a, b) {
            return  new Date (b.created_at) - new Date(a.created_at) || a.stargazers_count - b.stargazers_count
          })
          .map((d) => (

    <button id="btn" onClick={checkId} value={d.name}>Favorite me </button>


问:
Portable Go module with bundled files that must be read
I'm trying to create a portable Go module that will be re-used in many different projects. This module, in order to function, needs to be able to read non-Go files that are bundled as part of the module. In this case, they're some certificate bundles. The selection of which file to load is dynamic and based on input arguments.

What is the best way to specify the path to these files when loading them? I can't seem to find any Go functions to get a path relative to the module (vs. relative to the executable that is using this module). For example, if my module structure looks like this:

```<code>mymodule/
  go.mod
  go.sum
  loadcerts.go
  certs/
    cert_A.pem
    cert_B.pem
</code>```

And I need to do something like this:

```<code>// loadcerts.go

package mymodule

func LoadCerts(useB bool) error {
    newCertPool := x509.NewCertPool()

    // This is just to show that the selection is dynamic, and since
    // there are many different potential files to load, we can't
    // embed them all
    bundleName := "cert_A.pem"
    if useB {
        bundleName = "cert_B.pem"
    }
    pem, err := ioutil.ReadFile(fmt.Sprintf("./certs/%s", bundleName))
    if err != nil {
        return err
    }
    if ok := newCertPool.AppendCertsFromPEM(pem); !ok {
        return err
    }
    ...
}
</code>```

Referencing this file with a relative path (./certs/cert1.pem) doesn't work, since Go uses the executable's working directory for relative paths, and this imported module is somewhere entirely different.

How can I load this .pem file that is bundled with the portable module, regardless of where this module is being imported to?

答:
Embed the files in the executable as a file system:

```<code>//go:embed certs
var f embed.FS
</code>```

Read the files from the file system:

```<code>pem, err := f.ReadFile(fmt.Sprintf("certs/%s", bundleName))
</code>```

Body:
I'm trying to create a portable Go module that will be re-used in many different projects. This module, in order to function, needs to be able to read non-Go files that are bundled as part of the module. In this case, they're some certificate bundles. The selection of which file to load is dynamic and based on input arguments.

What is the best way to specify the path to these files when loading them? I can't seem to find any Go functions to get a path relative to the module (vs. relative to the executable that is using this module). For example, if my module structure looks like this:

mymodule/
  go.mod
  go.sum
  loadcerts.go
  certs/
    cert_A.pem
    cert_B.pem

And I need to do something like this:

// loadcerts.go

package mymodule

func LoadCerts(useB bool) error {
    newCertPool := x509.NewCertPool()

    // This is just to show that the selection is dynamic, and since
    // there are many different potential files to load, we can't
    // embed them all
    bundleName := "cert_A.pem"
    if useB {
        bundleName = "cert_B.pem"
    }
    pem, err := ioutil.ReadFile(fmt.Sprintf("./certs/%s", bundleName))
    if err != nil {
        return err
    }
    if ok := newCertPool.AppendCertsFromPEM(pem); !ok {
        return err
    }
    ...
}

Referencing this file with a relative path (./certs/cert1.pem) doesn't work, since Go uses the executable's working directory for relative paths, and this imported module is somewhere entirely different.

How can I load this .pem file that is bundled with the portable module, regardless of where this module is being imported to?

Body:
Embed the files in the executable as a file system:

//go:embed certs
var f embed.FS

Read the files from the file system:

pem, err := f.ReadFile(fmt.Sprintf("certs/%s", bundleName))


问:
Adding TabButton dynamically to TabBar in QML
I am trying to add a tabButton to TabBar dynamically on pressing a button but i have spent a lot of time searching but i am not getting how to add, below is the code which i am working on :

MyTabButton.qml

```<code>import QtQuick 2.4
import QtQuick.Controls 2.2

Item
{
    property int BtnWidth:0
    property int BtnHeight:0
    property string BtnText: ""
    property bool isChecked : false

    TabButton
    {
        id:tabBtn
        text:BtnText
        width:BtnWidth
        height:BtnHeight

    }
}
</code>```

MainForm.qml

```<code>import QtQuick 2.4
import QtQuick.Controls 2.2

Rectangle
{
    Button
    {
        id:button
        width:100
        height:100
        anchors.top:parent.top
        text:qStr("Add")
        onClicked{
            //How to add logic here to add tab in below tabBar.
        }
    }
    TabBar
    {
        id:tabBar
        anchors.top:button.bottom
        width:500
        height:500
    }
}
</code>```

答:
Try it in Window

```<code>Row {
    anchors.fill: parent
    TabBar {
        id: tabBar

        currentIndex: 0
        width: parent.width - addButton.width

        TabButton { text: "TabButton" }
    }

    Component {
        id: tabButton
        TabButton { text: "TabButton" }
    }

    Button {
        id: addButton
        text: "+"
        flat: true
        onClicked: {
            tabBar.addItem(tabButton.createObject(tabBar))
            console.log("added:", tabBar.itemAt(tabBar.count - 1))
        }
    }
}
</code>```

Body:
I am trying to add a tabButton to TabBar dynamically on pressing a button but i have spent a lot of time searching but i am not getting how to add, below is the code which i am working on :

MyTabButton.qml

import QtQuick 2.4
import QtQuick.Controls 2.2

Item
{
    property int BtnWidth:0
    property int BtnHeight:0
    property string BtnText: ""
    property bool isChecked : false

    TabButton
    {
        id:tabBtn
        text:BtnText
        width:BtnWidth
        height:BtnHeight

    }
}

MainForm.qml

import QtQuick 2.4
import QtQuick.Controls 2.2

Rectangle
{
    Button
    {
        id:button
        width:100
        height:100
        anchors.top:parent.top
        text:qStr("Add")
        onClicked{
            //How to add logic here to add tab in below tabBar.
        }
    }
    TabBar
    {
        id:tabBar
        anchors.top:button.bottom
        width:500
        height:500
    }
}

Body:
Try it in Window

Row {
    anchors.fill: parent
    TabBar {
        id: tabBar

        currentIndex: 0
        width: parent.width - addButton.width

        TabButton { text: "TabButton" }
    }

    Component {
        id: tabButton
        TabButton { text: "TabButton" }
    }

    Button {
        id: addButton
        text: "+"
        flat: true
        onClicked: {
            tabBar.addItem(tabButton.createObject(tabBar))
            console.log("added:", tabBar.itemAt(tabBar.count - 1))
        }
    }
}


问:
How to update database with server-side information without reloading the page
I'm developing a like/dislike system using php and MySQL, but I have a problem. When I add a like, let's say, I do it by adding a row to the likes table, that contains the post id and the user id. The user id is stored in a $_SESSION, and I can't just pass it to the html and make a AJAX request to run some php code and add the like, because this way it's too easy to simply change the user id.

So basicaly I don't want to reload the page to first get the $_SESSION value but I don't now how to get it's value after the page has loaded. I don't know if this is doable with php only, if not, what language should I use

答:
if you're using send ajax request for saving the like or dislike value. after saving the like/dislike value. you have to return a new like value count. in PHP simply echo the value that will automatically come to your ajax success if not simply return the new like/dislike info, encode with JSON and return the value.
get these values in the success function and target the like and dislike button or div and change the new value with an ajax response.

if you want to code answer please share your code here so it's better understood by everyone


问:
Unexpected performance loss when calling Cython function within Python script?
So I have a time-critical section of code within a Python script, and I decided to write a Cython module (with one function -- all I need) to replace it. Unfortunately, the execution speed of the function I'm calling from the Cython module (which I'm calling within my Python script) isn't nearly as fast as I tested it to be in a variety of other scenarios. Note that I CANNOT share the code itself because of contract law! See the following cases, and take them as an initial description of my issue:

(1) Execute Cython function by using the Python interpreter to import the module and run the function. Runs relatively quickly (~0.04 sec on ~100 separate tests, versus original ~0.24 secs).

(2) Call Cython function within Python script at 'global' level (i.e. not inside any function). Same speed as case (1).

(3) Call Cython function within Python script, with Cython function inside my Python script's main function; tested with the Cython function in global and local namespaces, all with the same speed as case (1).

(4) Same as (3), but inside a simple for-loop within said Python function. Same speed as case (1).

(5) problem! Same as (4), but inside yet another for-loop: Cython function's execution time (whether called globally or locally) balloons to ~10 times that of the other cases, and this is where I need the function to get called. Nothing odd to report about this loop, and I tested all of the components of this loop (adjusting/removing what I could). I also tried using a 'while' loop for giggles, to no avail.

"One thing I've yet to try is making this inner-most loop a function and going from there." EDIT: Just tried this- no luck.

Thanks for any suggestions you have- I deeply regret not being able to share my code...it hurts my soul a little, but my client just can't have this code floating around. Let me know if there is any other information that I can provide!

-The Real Problem and an Initial (ugly) Solution-

It turns out that the best hint in this scenario was the obvious one (as usual): it wasn't the for-loop that was causing the problem; why would it? After a few more tests, it became obvious that something about the way I was calling my Cython function was wrong, because I could call it elsewhere (using an input variable different from the one going to the 'real' Cython function) without the performance loss issue.

The underlying issue: data types. I wrote my Cython function to expect a list full of standard floats. Unfortunately, my code did this:

```<code>function_input = list(numpy_array_containing_npfloat64_data) # yuck.
type(function_input[0]) = numpy.float64
output = Cython_Function(function_input)
</code>```

inside the Cython function:

```<code>def Cython_Function(list function_input):
    cdef many_vars
    """process lots of vars expecting C floats""" # Slowness from converting numpy.float64's --> floats???
    type(output) = list
    return output
</code>```

I'm aware that I can play around more with types in the Cython function, which I very well may do to prevent having to 'list' an existing numpy array. Anyway, here is my current solution:

```<code>function_input = [float(x) for x in function_input]
</code>```

I welcome any feedback and suggestions for improvement. The function_input numpy array doesn't really need the precision of numpy.float64, but it does get used a few times before getting passed to my Cython function.

答:
It could be that, while individually, each function call with the Cython implementation is faster than its corresponding Python function, there is more overhead in the Cython function call because it has to look up the name in the module namespace. You can try assigning the function to a local callable first, for example:

```<code>from module import function

def main():
    my_func = functon
    for i in sequence:
        my_func()
</code>```

If possible, you should try to include the loops within the Cython function, which would reduce the overhead of a Python loop to the (very minimal) overhead of a compiled C loop. I understand that it might not be possible (i.e. need references from a global/larger scope), but it's worth some investigation on your part. Good luck!

Body:
So I have a time-critical section of code within a Python script, and I decided to write a Cython module (with one function -- all I need) to replace it. Unfortunately, the execution speed of the function I'm calling from the Cython module (which I'm calling within my Python script) isn't nearly as fast as I tested it to be in a variety of other scenarios. Note that I CANNOT share the code itself because of contract law! See the following cases, and take them as an initial description of my issue:

(1) Execute Cython function by using the Python interpreter to import the module and run the function. Runs relatively quickly (~0.04 sec on ~100 separate tests, versus original ~0.24 secs).

(2) Call Cython function within Python script at 'global' level (i.e. not inside any function). Same speed as case (1).

(3) Call Cython function within Python script, with Cython function inside my Python script's main function; tested with the Cython function in global and local namespaces, all with the same speed as case (1).

(4) Same as (3), but inside a simple for-loop within said Python function. Same speed as case (1).

(5) problem! Same as (4), but inside yet another for-loop: Cython function's execution time (whether called globally or locally) balloons to ~10 times that of the other cases, and this is where I need the function to get called. Nothing odd to report about this loop, and I tested all of the components of this loop (adjusting/removing what I could). I also tried using a 'while' loop for giggles, to no avail.

"One thing I've yet to try is making this inner-most loop a function and going from there." EDIT: Just tried this- no luck.

Thanks for any suggestions you have- I deeply regret not being able to share my code...it hurts my soul a little, but my client just can't have this code floating around. Let me know if there is any other information that I can provide!

-The Real Problem and an Initial (ugly) Solution-

It turns out that the best hint in this scenario was the obvious one (as usual): it wasn't the for-loop that was causing the problem; why would it? After a few more tests, it became obvious that something about the way I was calling my Cython function was wrong, because I could call it elsewhere (using an input variable different from the one going to the 'real' Cython function) without the performance loss issue.

The underlying issue: data types. I wrote my Cython function to expect a list full of standard floats. Unfortunately, my code did this:

function_input = list(numpy_array_containing_npfloat64_data) # yuck.
type(function_input[0]) = numpy.float64
output = Cython_Function(function_input)

inside the Cython function:

def Cython_Function(list function_input):
    cdef many_vars
    """process lots of vars expecting C floats""" # Slowness from converting numpy.float64's --> floats???
    type(output) = list
    return output

I'm aware that I can play around more with types in the Cython function, which I very well may do to prevent having to 'list' an existing numpy array. Anyway, here is my current solution:

function_input = [float(x) for x in function_input]

I welcome any feedback and suggestions for improvement. The function_input numpy array doesn't really need the precision of numpy.float64, but it does get used a few times before getting passed to my Cython function.

Body:
It could be that, while individually, each function call with the Cython implementation is faster than its corresponding Python function, there is more overhead in the Cython function call because it has to look up the name in the module namespace. You can try assigning the function to a local callable first, for example:

from module import function

def main():
    my_func = functon
    for i in sequence:
        my_func()

If possible, you should try to include the loops within the Cython function, which would reduce the overhead of a Python loop to the (very minimal) overhead of a compiled C loop. I understand that it might not be possible (i.e. need references from a global/larger scope), but it's worth some investigation on your part. Good luck!


问:
Weird White lines in Android Launcher?
I'm currently programming and I noticed that there are strange white lines around the app in the Android Launcher. With other apps, everything is normal. Can someone help me how to remove them?
Screenshot</p>

答:
Is that an actual image?

So this was a problem for us a while back. The result of the investigation ended with this blog post.

https://blog.jakelee.co.uk/avoiding-a-1-pixel-line-on-zeplin-exports-or-why-density-matters/

(Thanks Jake)

Title: Weird White lines in Android Launcher?


问:
PHP check if point is inside a circle
I have codes below

circle.php

```<code>class point{
    private $x;
    private $y;

    function __construct($x, $y){
        $this->x = $x;
        $this->y = $y;
    }

    public function getX(){
        return $this->x;
    }

    public function getY(){
        return $this->y;
    }

}

class circle{
    private $x_circle;
    private $y_circle;
    private $radius;

    function __construct($x_circle, $y_circle, $radius){
        $this->x_circle = $x_circle;
        $this->y_circle = $y_circle;
        $this->radius = $radius;
    }

    public function getCircleX(){
        return $this->x_circle;
    }

    public function getCircleY(){
        return $this->y_circle;
    }

    public function getRadius(){
        return $this->radius;
    }

    public function checkIfInside(){
        if(pow(getX() - getCircleX(), 2) + pow(getY() - getCircleY(), 2) < pow(getRadius(),2)){
            return true;
        } else {
            return false;
        }

    }
}
</code>```

index.php

```<code>include 'circle.php';

$point= new point(3, 4);
$circle= new circle(10, 10, 100);
$circle->checkIfInside();
</code>```

I try to check if point is inside a circle. With point class we declare point coordinates(x,y). With circle class we declare the coordinates of circle(x,y) and radius. But I get this error: Uncaught Error: Call to undefined function getX()

答:
The main issues:

in checkIfInside methods are called as if they are global functions. You should instead include the object on which the method should be called, using the -> notation. For instance, it should not be getCircleX(), but $this->getCircleX()

This function should know which point you want to check with, so it should be an argument: public function checkIfInside($point). The caller should pass this as argument in the call.

Not a problem, but if (boolean) { return true; } else { return false; } is an anti-pattern. Just return the boolean.

Corrected method:

```<code>    public function checkIfInside($point){
        return pow($point->getX() - $this->getCircleX(), 2) + pow($point->getY() - $this->getCircleY(), 2)
            < pow($this->getRadius(),2);
    }
</code>```

Corrected call in main program:

```<code>$result = $circle->checkIfInside($point);
</code>```

Title: PHP check if point is inside a circle

Body:
I have codes below

circle.php

class point{
    private $x;
    private $y;

    function __construct($x, $y){
        $this->x = $x;
        $this->y = $y;
    }

    public function getX(){
        return $this->x;
    }

    public function getY(){
        return $this->y;
    }

}

class circle{
    private $x_circle;
    private $y_circle;
    private $radius;

    function __construct($x_circle, $y_circle, $radius){
        $this->x_circle = $x_circle;
        $this->y_circle = $y_circle;
        $this->radius = $radius;
    }

    public function getCircleX(){
        return $this->x_circle;
    }

    public function getCircleY(){
        return $this->y_circle;
    }

    public function getRadius(){
        return $this->radius;
    }

    public function checkIfInside(){
        if(pow(getX() - getCircleX(), 2) + pow(getY() - getCircleY(), 2) < pow(getRadius(),2)){
            return true;
        } else {
            return false;
        }

    }
}

index.php

include 'circle.php';

$point= new point(3, 4);
$circle= new circle(10, 10, 100);
$circle->checkIfInside();

I try to check if point is inside a circle. With point class we declare point coordinates(x,y). With circle class we declare the coordinates of circle(x,y) and radius. But I get this error: Uncaught Error: Call to undefined function getX()

Body:
The main issues:

in checkIfInside methods are called as if they are global functions. You should instead include the object on which the method should be called, using the -> notation. For instance, it should not be getCircleX(), but $this->getCircleX()

This function should know which point you want to check with, so it should be an argument: public function checkIfInside($point). The caller should pass this as argument in the call.

Not a problem, but if (boolean) { return true; } else { return false; } is an anti-pattern. Just return the boolean.

Corrected method:

    public function checkIfInside($point){
        return pow($point->getX() - $this->getCircleX(), 2) + pow($point->getY() - $this->getCircleY(), 2)
            < pow($this->getRadius(),2);
    }

Corrected call in main program:

$result = $circle->checkIfInside($point);


问:
What the value of "chrono::steady_clock::now().time_since_epoch().count()" represents?
```<code>cout << chrono::steady_clock::now().time_since_epoch().count() << "\n"; // it prints a 14-digit value
</code>```

Is is the number of nanoseconds passed since 1970?

答:
Is is the number of nanoseconds passed since 1970?

Very unlikely.

It is the number of some duration unit passed since some time.  Neither the unit nor the epoch is standardized.

This may not sound useful, and a single reading of std::chrono::steady_clock::now() arguably isn't very useful.  (Beyond, say, seeding a random number generator perhaps)

steady_clock readings are intended to be compared against other steady_clock readings.  It is useful for measuring elapsed time.

The count() is only useful if you cast the duration to a known duration period.

Body:
cout << chrono::steady_clock::now().time_since_epoch().count() << "\n"; // it prints a 14-digit value

Is is the number of nanoseconds passed since 1970?


问:
"The requested module ' does not provide an export named 'default' " error, but only in relative import
I have this api module from outside. When it is installed as a node_module (with npm install), then doing an import like this works:

```<code>import MyAPI from 'api'
</code>```

However, when I look into the api folder in the node_modules and take out the api.js, which is entry point of the module, and do a relative import like this:

```<code>import MyAPI from './api.js'
</code>```

Then I get the error:

```<code>"The requested module ./api.js does not provide an export named 'default'"
</code>```

I have no control over how the api module is built. How can it work in one case but not another? This is Node 12.

答:
You've confirmed that the package.json in the module's folder doesn't have "type": "module" in it. That's the issue. It's using the older CommonJS system instead of the newer, standard ESM system your module is using. Node.js does some automatic conversion when loading old-style CommonJS modules via ESM (details).

If you want to copy that file out of its module and use it in a different module environment, you'll have to convert its exports (and potentially imports) to ESM. For example, instead of:

```<code>exports.example = function example() { };
</code>```

it would be

```<code>export function example() { }
</code>```

but it's potentially complicated, because the two systems work differently. CommonJS is dynamic, based on property assignment (although the result is static), ESM is static, declarative (although the result is, in some ways, dynamic).

Body:
I have this api module from outside. When it is installed as a node_module (with npm install), then doing an import like this works:

import MyAPI from 'api'

However, when I look into the api folder in the node_modules and take out the api.js, which is entry point of the module, and do a relative import like this:

import MyAPI from './api.js'

Then I get the error:

"The requested module ./api.js does not provide an export named 'default'"

I have no control over how the api module is built. How can it work in one case but not another? This is Node 12.

Body:
You've confirmed that the package.json in the module's folder doesn't have "type": "module" in it. That's the issue. It's using the older CommonJS system instead of the newer, standard ESM system your module is using. Node.js does some automatic conversion when loading old-style CommonJS modules via ESM (details).

If you want to copy that file out of its module and use it in a different module environment, you'll have to convert its exports (and potentially imports) to ESM. For example, instead of:

exports.example = function example() { };

it would be

export function example() { }

but it's potentially complicated, because the two systems work differently. CommonJS is dynamic, based on property assignment (although the result is static), ESM is static, declarative (although the result is, in some ways, dynamic).


问:
PHP Regex Match those which start with Capital letter
It sounds pretty simple but I cant figure this out, please help me out.

So... I have file with following data:

```<code>Name: Santi
Surname: Dore
Name: Rob
Surname: Doe
and so on..
</code>```

I need to match only the whole part that starts with "Name:" ... NOT "Surname:" ...

Here is what I am using right now to match it:

```<code>/Name(:)(.*)/i
</code>```

It will match both but I need just Name: ...

Please dont suggest any other way of finding, just please help me out with regex to work the way I described.

答:
```<code>/\b^(Name):\s[A-Z]+\s\b/
</code>```

use \s for handling spaces.

Body:
It sounds pretty simple but I cant figure this out, please help me out.

So... I have file with following data:

Name: Santi
Surname: Dore
Name: Rob
Surname: Doe
and so on..

I need to match only the whole part that starts with "Name:" ... NOT "Surname:" ...

Here is what I am using right now to match it:

/Name(:)(.*)/i

It will match both but I need just Name: ...

Please dont suggest any other way of finding, just please help me out with regex to work the way I described.

Body:
/\b^(Name):\s[A-Z]+\s\b/

use \s for handling spaces.


问:
Is each data unique in rdbms columns
A column in mysql consists of a 'SQL' and another value is 'sql'.

```<code>select col from table_name where col = 'SQL';
</code>```

Does this return both SQL and sql.

答:
Case-sensitivity is determined by the collation of a column. The default collations are case-insensitive, so the string comparison you show would match both "sql" and "SQL".

Read https://dev.mysql.com/doc/refman/8.0/en/case-sensitivity.html

If your column has a binary collation, or if the column is a binary string (data types BINARY, VARBINARY, BLOB), then the string comparison will be case-sensitive.

Title: Is each data unique in rdbms columns

Body:
A column in mysql consists of a 'SQL' and another value is 'sql'.

select col from table_name where col = 'SQL';

Does this return both SQL and sql.


问:
Priority Queue - Order Messed Up
I'm having a weird issue where my priority queue prints the last created item first, and then prints everything else in order.

I am working on a version of this assignment for my computer science class. We are using the in-built PriorityQueue in Java. A Disk object can hold 1,000,000 KB of data and a disk has priority if it has the most free space.

In my solution, Disk 7 was created latest, and it is printed on top despite the lower priority. Does anyone know what might be causing this?

Here is my solution:

```<code>public static void findWorstFit(String fileName) throws FileNotFoundException {
    PriorityQueue<Disk> disks = new PriorityQueue<>();
    double totalSize = 0;

    // Process each file and add it to a disk
    Scanner fileScanner = new Scanner(new File(fileName));
    while(fileScanner.hasNextInt()) {
        int file = fileScanner.nextInt();
        if(disks.size() > 0 && disks.peek().freeSpace >= file)
            disks.peek().add(file);
        else
            disks.offer(new Disk(disks.size(), file));
        totalSize += file;
    }

    // Print all the disks
    System.out.println("Total size = " + totalSize/1000000 + " GB");
    System.out.println("Disks req'd = " + disks.size());
    while(!disks.isEmpty())
        System.out.println(disks.poll());
}
</code>```

Here is the expected output:

```<code>Total size  = 6.580996 GB
Disks req'd = 8
5 325754: 347661 326585
0 227744: 420713 351543
7 224009: 383972 392019
4 190811: 324387 484802
6 142051: 340190 263485 254274
3 116563: 347560 204065 331812
2 109806: 396295 230973 262926
1  82266: 311011 286309 320414
</code>```

And here is the actual output:

```<code>Total size  = 6.580996 GB
Disks req'd = 8
7 224009: 383972 392019
5 325754: 347661 326585
0 227744: 420713 351543
4 190811: 324387 484802
6 142051: 340190 263485 254274
3 116563: 347560 204065 331812
2 109806: 396295 230973 262926
1  82266: 311011 286309 320414
</code>```

答:
As i see it, there are two possible errors.

Your implementation of Comparable in Disk is incorrect.

This line - disks.peek().add(file); is fishy, it's connected to the first possibility. Elements in PriorityQueue are being ordered when adding to the queue or removing from it. Here you are the changing state of already inserted element, eventually changing its priority(depends on Comparable implementation). But this will not change its ordering in the queue, even though its priority might change.

Title: Priority Queue - Order Messed Up

Body:
I'm having a weird issue where my priority queue prints the last created item first, and then prints everything else in order.

I am working on a version of this assignment for my computer science class. We are using the in-built PriorityQueue in Java. A Disk object can hold 1,000,000 KB of data and a disk has priority if it has the most free space.

In my solution, Disk 7 was created latest, and it is printed on top despite the lower priority. Does anyone know what might be causing this?

Here is my solution:

public static void findWorstFit(String fileName) throws FileNotFoundException {
    PriorityQueue<Disk> disks = new PriorityQueue<>();
    double totalSize = 0;

    // Process each file and add it to a disk
    Scanner fileScanner = new Scanner(new File(fileName));
    while(fileScanner.hasNextInt()) {
        int file = fileScanner.nextInt();
        if(disks.size() > 0 && disks.peek().freeSpace >= file)
            disks.peek().add(file);
        else
            disks.offer(new Disk(disks.size(), file));
        totalSize += file;
    }

    // Print all the disks
    System.out.println("Total size = " + totalSize/1000000 + " GB");
    System.out.println("Disks req'd = " + disks.size());
    while(!disks.isEmpty())
        System.out.println(disks.poll());
}

Here is the expected output:

Total size  = 6.580996 GB
Disks req'd = 8
5 325754: 347661 326585
0 227744: 420713 351543
7 224009: 383972 392019
4 190811: 324387 484802
6 142051: 340190 263485 254274
3 116563: 347560 204065 331812
2 109806: 396295 230973 262926
1  82266: 311011 286309 320414

And here is the actual output:

Total size  = 6.580996 GB
Disks req'd = 8
7 224009: 383972 392019
5 325754: 347661 326585
0 227744: 420713 351543
4 190811: 324387 484802
6 142051: 340190 263485 254274
3 116563: 347560 204065 331812
2 109806: 396295 230973 262926
1  82266: 311011 286309 320414


问:
Arrange data frame by all columns using dplyr
I am generating data frames of 1s and 0s as follows:

library(tidyverse)
library(glue)

num_var <- 3

rep(list(c(0L, 1L)), num_var) %>%
  set_names(glue("var_{seq_len(num_var)}")) %>%
  expand.grid() %>%
  mutate(total = rowSums(.)) %>%
  select(total, everything()) %>%
  arrange(total, desc(var_1, var_2, var_3))

#>   total var_1 var_2 var_3
#> 1     0     0     0     0
#> 2     1     1     0     0
#> 3     1     0     1     0
#> 4     1     0     0     1
#> 5     2     1     1     0
#> 6     2     1     0     1
#> 7     2     0     1     1
#> 8     3     1     1     1
```

<p>Created on 2018-01-08 by the reprex
package (v0.1.1.9000).</p>

<p>I would need to arrange by the total sum of the variable in ascending order, and then each variable in descending order. This is fairly straightforward using <code>dplyr::arrange()</code>. However, I would like to have a more robust method of arranging. For example, if <code>num_var</code> is changed to, then, the final line must also be changed to <code>arrange(total, desc(var_1, var_2, var_3, var_4))</code>. I have tried using the tidy selector <code>everything()</code> to  arrange as I do with the <code>select()</code> function, but this errors:</p>

<pre class="lang-r prettyprint-override"><code>library(tidyverse)
library(glue)

num_var <- 3

rep(list(c(0L, 1L)), num_var) %>%
  set_names(glue("var_{seq_len(num_var)}")) %>%
  expand.grid() %>%
  mutate(total = rowSums(.)) %>%
  select(total, everything()) %>%
  arrange(total, desc(everything()))

#> Error in arrange_impl(.data, dots): Evaluation error: No tidyselect variables were registered.
</code>```

Created on 2018-01-08 by the reprex
package (v0.1.1.9000).

Is there a way to select variables for arranging without naming them all directly?

答:
For newer versions of dplyr, you can now use across:

library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union

iris %>%
  arrange(across(everything(), desc)) %>%
  head()
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
#> 1          7.9         3.8          6.4         2.0 virginica
#> 2          7.7         3.8          6.7         2.2 virginica
#> 3          7.7         3.0          6.1         2.3 virginica
#> 4          7.7         2.8          6.7         2.0 virginica
#> 5          7.7         2.6          6.9         2.3 virginica
#> 6          7.6         3.0          6.6         2.1 virginica

all.equal(iris %>%
            arrange(across(everything(), desc)) ,
          iris %>%
            arrange(desc(Sepal.Length), desc(Sepal.Width), desc(Petal.Length), desc(Petal.Width), desc(Species)))
#> [1] TRUE
```

Created on 2022-02-07 by the reprex package (v2.0.1)

Body:
I am generating data frames of 1s and 0s as follows:

library(tidyverse)
library(glue)

num_var <- 3

rep(list(c(0L, 1L)), num_var) %>%
  set_names(glue("var_{seq_len(num_var)}")) %>%
  expand.grid() %>%
  mutate(total = rowSums(.)) %>%
  select(total, everything()) %>%
  arrange(total, desc(var_1, var_2, var_3))

#>   total var_1 var_2 var_3
#> 1     0     0     0     0
#> 2     1     1     0     0
#> 3     1     0     1     0
#> 4     1     0     0     1
#> 5     2     1     1     0
#> 6     2     1     0     1
#> 7     2     0     1     1
#> 8     3     1     1     1

Created on 2018-01-08 by the reprex
package (v0.1.1.9000).

I would need to arrange by the total sum of the variable in ascending order, and then each variable in descending order. This is fairly straightforward using dplyr::arrange(). However, I would like to have a more robust method of arranging. For example, if num_var is changed to, then, the final line must also be changed to arrange(total, desc(var_1, var_2, var_3, var_4)). I have tried using the tidy selector everything() to  arrange as I do with the select() function, but this errors:

library(tidyverse)
library(glue)

num_var <- 3

rep(list(c(0L, 1L)), num_var) %>%
  set_names(glue("var_{seq_len(num_var)}")) %>%
  expand.grid() %>%
  mutate(total = rowSums(.)) %>%
  select(total, everything()) %>%
  arrange(total, desc(everything()))

#> Error in arrange_impl(.data, dots): Evaluation error: No tidyselect variables were registered.

Created on 2018-01-08 by the reprex
package (v0.1.1.9000).

Is there a way to select variables for arranging without naming them all directly?

Body:
For newer versions of dplyr, you can now use across:

library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union

iris %>%
  arrange(across(everything(), desc)) %>%
  head()
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
#> 1          7.9         3.8          6.4         2.0 virginica
#> 2          7.7         3.8          6.7         2.2 virginica
#> 3          7.7         3.0          6.1         2.3 virginica
#> 4          7.7         2.8          6.7         2.0 virginica
#> 5          7.7         2.6          6.9         2.3 virginica
#> 6          7.6         3.0          6.6         2.1 virginica

all.equal(iris %>%
            arrange(across(everything(), desc)) ,
          iris %>%
            arrange(desc(Sepal.Length), desc(Sepal.Width), desc(Petal.Length), desc(Petal.Width), desc(Species)))
#> [1] TRUE

Created on 2022-02-07 by the reprex package (v2.0.1)


问:
How to align a picture,name and the post with css like facebook does?
I am trying to align  a full name,picture and the post just like they do in most social networks (linked-in or facebook).But i cant align them the well.Can anybody please try to fill the gaps with necessary css commands?Thank you in advance.

```<code><div>
 <span class="picture"> <img src="/assets/images/rails.png"/></span>
  <a  href="#" class="user-name">user-full-name</a>
 <span class="post"></span>
 </div>
</code>```

css

```<code> .picture{height:40px;
         width:40px;
         }

  .user-name{
         margin-bottom:35px;
            }
   .post{     }
</code>```

答:
```<code>.inline_table{
  display: inline-table;
  position: relative;
}
</code>```

is another property you might want to look at ... any element which has both position relative AND inline table .. will be aligned left to right butted up against each other.

so in this example:

```<code><div id="profile_picture" class="inline_table">
<div id="profile_name" class="inline_table">
<div id="profile_post" class="inline_table">
</code>```

will all be aligned along the same row

Body:
I am trying to align  a full name,picture and the post just like they do in most social networks (linked-in or facebook).But i cant align them the well.Can anybody please try to fill the gaps with necessary css commands?Thank you in advance.

  user-full-name

css

 .picture{height:40px;
         width:40px;
         }

  .user-name{
         margin-bottom:35px;
            }
   .post{     }

Body:
.inline_table{
  display: inline-table;
  position: relative;
}

is another property you might want to look at ... any element which has both position relative AND inline table .. will be aligned left to right butted up against each other.

so in this example:

<div id="profile_picture" class="inline_table">
<div id="profile_name" class="inline_table">
<div id="profile_post" class="inline_table">

will all be aligned along the same row


问:
How to build html table from json file using node js?
How to build html table from json file using node js?
I have a JSON file and I want to display it in an html document, how can I do it?</p>

答:
try this:</p>
```<code><!DOCTYPE html>
<html>
<head>
    <title>Convert JSON Data to HTML Table</title>
    <style>
        th, td, p, input, h3 {
            font:15px 'Segoe UI';
        }
        table, th, td {
            border: solid 1px #ddd;
            border-collapse: collapse;
            padding: 2px 3px;
            text-align: center;
        }
        th {
            font-weight:bold;
        }
    </style>
</head>
<body>
    <h3>
        Click the button to create a dynamic table using data extracted from a JSON array.
    </h3>
    <input type='button' onclick='tableFromJson()'
        value='Create Table from JSON data' />

    <p id='showData'></p>

    <p id='msg'></p>
</body>

<script>
    // scroll down for ES6 features.

    // using regular methods.

    function tableFromJson() {
        // the json data. (you can change the values for output.)
        var myBooks = [
            {'Book ID': '1', 'Book Name': 'Challenging Times',
                'Category': 'Business', 'Price': '125.60'
            },
            {'Book ID': '2', 'Book Name': 'Learning JavaScript',
                'Category': 'Programming', 'Price': '56.00'
            },
            {'Book ID': '3', 'Book Name': 'Popular Science',
                'Category': 'Science', 'Price': '210.40'
            }
        ]

        // Extract value from table header.
        // ('Book ID', 'Book Name', 'Category' and 'Price')
        var col = [];
        for (var i = 0; i < myBooks.length; i++) {
            for (var key in myBooks[i]) {
                if (col.indexOf(key) === -1) {
                    col.push(key);
                }
            }
        }

        // Create a table.
        var table = document.createElement("table");

        // Create table header row using the extracted headers above.
        var tr = table.insertRow(-1);                   // table row.

        for (var i = 0; i < col.length; i++) {
            var th = document.createElement("th");      // table header.
            th.innerHTML = col[i];
            tr.appendChild(th);
        }

        // add json data to the table as rows.
        for (var i = 0; i < myBooks.length; i++) {

            tr = table.insertRow(-1);

            for (var j = 0; j < col.length; j++) {
                var tabCell = tr.insertCell(-1);
                tabCell.innerHTML = myBooks[i][col[j]];
            }
        }

        // Now, add the newly created table with json data, to a container.
        var divShowData = document.getElementById('showData');
        divShowData.innerHTML = "";
        divShowData.appendChild(table);

    }

</script>
</html>
</code>```

Body:
try this:

<!DOCTYPE html>
<html>
<head>
    <title>Convert JSON Data to HTML Table</title>
    <style>
        th, td, p, input, h3 {
            font:15px 'Segoe UI';
        }
        table, th, td {
            border: solid 1px #ddd;
            border-collapse: collapse;
            padding: 2px 3px;
            text-align: center;
        }
        th {
            font-weight:bold;
        }
    </style>
</head>
<body>
    <h3>
        Click the button to create a dynamic table using data extracted from a JSON array.
    </h3>
    <input type='button' onclick='tableFromJson()'
        value='Create Table from JSON data' />

    <p id='showData'></p>

    <p id='msg'></p>
</body>

<script>
    // scroll down for ES6 features.

    // using regular methods.

    function tableFromJson() {
        // the json data. (you can change the values for output.)
        var myBooks = [
            {'Book ID': '1', 'Book Name': 'Challenging Times',
                'Category': 'Business', 'Price': '125.60'
            },
            {'Book ID': '2', 'Book Name': 'Learning JavaScript',
                'Category': 'Programming', 'Price': '56.00'
            },
            {'Book ID': '3', 'Book Name': 'Popular Science',
                'Category': 'Science', 'Price': '210.40'
            }
        ]

        // Extract value from table header.
        // ('Book ID', 'Book Name', 'Category' and 'Price')
        var col = [];
        for (var i = 0; i < myBooks.length; i++) {
            for (var key in myBooks[i]) {
                if (col.indexOf(key) === -1) {
                    col.push(key);
                }
            }
        }

        // Create a table.
        var table = document.createElement("table");

        // Create table header row using the extracted headers above.
        var tr = table.insertRow(-1);                   // table row.

        for (var i = 0; i < col.length; i++) {
            var th = document.createElement("th");      // table header.
            th.innerHTML = col[i];
            tr.appendChild(th);
        }

        // add json data to the table as rows.
        for (var i = 0; i < myBooks.length; i++) {

            tr = table.insertRow(-1);

            for (var j = 0; j < col.length; j++) {
                var tabCell = tr.insertCell(-1);
                tabCell.innerHTML = myBooks[i][col[j]];
            }
        }

        // Now, add the newly created table with json data, to a container.
        var divShowData = document.getElementById('showData');
        divShowData.innerHTML = "";
        divShowData.appendChild(table);

    }

</script>
</html>