问:
First 4 li element's onClick work but everyone after doesn't - in FF 3.6 and Chrome
Sorry for the confusing title, but that's about the best I can describe it... So I have a TD element and when it's double clicked a jquery ajax function returns a ul from a PHP script.

New code (sorry for so much of it):

Here is the jQuery Ajax code:

```<code>    //Create PU:
    $('#DD_'+IDNum).append('<div class="popUp" id="PU_'+IDNum+'"></div>');

    //ajax:
    $.ajaxSetup ({
        cache: false
    });
    var ajax_load = '<img class="loading" id="LG_'+IDNum+'" src="../images/loading.gif" />';
    if(key==0)
        var term = '';
    else
        var term = $('#TC_'+IDNum).val();
    //load() functions
    var loadUrl = "./ddGet.php?Ele="+element+"&Client="+ClientID+"&vendorName="+vendorName+"&id="+IDNum+"&term="+term;
    $('#PU_'+IDNum+'').html(ajax_load).load(loadUrl);
</code>```

Here is a snippet of the PHP:

```<code>$result = mysql_query($query) or die(mysql_error());
$response= '<ul id="DD_UL">';
$resultArray = array();
$class = "li-odd";
$i = 1;
while($row = mysql_fetch_array($result))
{
    if(!in_array($row[0], $resultArray)){
    $resultArray[]=$row[0];
    if(isset($row[1]))
        $roW1 = ' - '.$row[1];
    else
        $roW1 = '';
    $response .= "\n".'<li id="LI_'.$id.'_'.$i.'" class="'.$class.'">'.$row[0].$roW1.'</li>';
    //selectLI(\'LI_'.$id.'_'.$i.'\')
    if($class == "li-odd")
        $class = "li-even";
    else
        $class = "li-odd";
    $i++;
    }
}
$response .= '</ul>';
echo $response;
</code>```

Here is the response text:

```<code><ul id="DD_UL">
<li id="LI_1_1_1" class="li-odd">E02_02</li>
<li id="LI_1_1_2" class="li-even">E02_03</li>
<li id="LI_1_1_3" class="li-odd">E02_04</li>
<li id="LI_1_1_4" class="li-even">E02_05</li>
<li id="LI_1_1_5" class="li-odd">E02_06</li>
<li id="LI_1_1_6" class="li-even">E02_07</li>
<li id="LI_1_1_7" class="li-odd">E02_08</li>
<li id="LI_1_1_8" class="li-even">E02_09</li>
<li id="LI_1_1_9" class="li-odd">E02_10</li>
<li id="LI_1_1_10" class="li-even">E02_11</li>
<li id="LI_1_1_11" class="li-odd">E02_13</li>
<li id="LI_1_1_12" class="li-even">E02_14</li>
<li id="LI_1_1_13" class="li-odd">E02_20</li>
</ul>
</code>```

And finally the new function that is called after the UL is displayed that assigns the .live:

```<code>function selectLI(){
        $('#DD_UL').live('click',function(e){
        var id = e.target
        id = $(id).attr('id');
        var IDNum = id.substr(3);
        IDNum = IDNum.substring(0,IDNum.lastIndexOf("_"));
        var newVal = $('#'+id).html();
        if(newVal.indexOf(" - ")>0)
            newVal = newVal.substring(0, newVal.indexOf(" - "));
        $('#TC_'+IDNum).val(newVal);
        });
    }
</code>```

Not so simple anymore, huh?  Well first I noticed that in Chrome the onclick would only work if it was like one of the first 4 li's or so clicked.  After the first four (or so) nothing would happen.  I then noticed that FF 3.6 was doing the same thing.  I check IE (although the page is not meant to be run in IE) and it worked.  Finally FF 4 works fine as well.

I say "or so" because sometimes it's the first 4,5,6,7...  Sometimes there appears to be a pattern but I can't figure it out.  I would post more code, however there is a lot of it and I don't see the point since the issue is basically occurring with the above response text.

I have no idea what to do next.

答:
A suggestion:

Remove all onClick attributes from the anchors. Instead, set an ID attribute on the UL element (for instance list).

Then, add this to your jQuery code:

```<code>$('#list').live('click', function(e) {
    var anchor = e.target;
    // do stuff with your anchor
});
</code>```

Live demo: http://jsfiddle.net/7Lqtn/

Body:
Sorry for the confusing title, but that's about the best I can describe it... So I have a TD element and when it's double clicked a jquery ajax function returns a ul from a PHP script.

New code (sorry for so much of it):

Here is the jQuery Ajax code:

    //Create PU:
    $('#DD_'+IDNum).append('

');

    //ajax:
    $.ajaxSetup ({
        cache: false
    });
    var ajax_load = '';
    if(key==0)
        var term = '';
    else
        var term = $('#TC_'+IDNum).val();
    //load() functions
    var loadUrl = "./ddGet.php?Ele="+element+"&Client="+ClientID+"&vendorName="+vendorName+"&id="+IDNum+"&term="+term;
    $('#PU_'+IDNum+'').html(ajax_load).load(loadUrl);

Here is a snippet of the PHP:

$result = mysql_query($query) or die(mysql_error());
$response= '
';
$resultArray = array();
$class = "li-odd";
$i = 1;
while($row = mysql_fetch_array($result))
{
    if(!in_array($row[0], $resultArray)){
    $resultArray[]=$row[0];
    if(isset($row[1]))
        $roW1 = ' - '.$row[1];
    else
        $roW1 = '';
    $response .= "\n".'
'.$row[0].$roW1.'
';
    //selectLI(\'LI_'.$id.'_'.$i.'\')
    if($class == "li-odd")
        $class = "li-even";
    else
        $class = "li-odd";
    $i++;
    }
}
$response .= '
';
echo $response;

Here is the response text:

E02_02

E02_03

E02_04

E02_05

E02_06

E02_07

E02_08

E02_09

E02_10

E02_11

E02_13

E02_14

E02_20

And finally the new function that is called after the UL is displayed that assigns the .live:

function selectLI(){
        $('#DD_UL').live('click',function(e){
        var id = e.target
        id = $(id).attr('id');
        var IDNum = id.substr(3);
        IDNum = IDNum.substring(0,IDNum.lastIndexOf("_"));
        var newVal = $('#'+id).html();
        if(newVal.indexOf(" - ")>0)
            newVal = newVal.substring(0, newVal.indexOf(" - "));
        $('#TC_'+IDNum).val(newVal);
        });
    }

Not so simple anymore, huh?  Well first I noticed that in Chrome the onclick would only work if it was like one of the first 4 li's or so clicked.  After the first four (or so) nothing would happen.  I then noticed that FF 3.6 was doing the same thing.  I check IE (although the page is not meant to be run in IE) and it worked.  Finally FF 4 works fine as well.

I say "or so" because sometimes it's the first 4,5,6,7...  Sometimes there appears to be a pattern but I can't figure it out.  I would post more code, however there is a lot of it and I don't see the point since the issue is basically occurring with the above response text.

I have no idea what to do next.

Body:
A suggestion:

Remove all onClick attributes from the anchors. Instead, set an ID attribute on the UL element (for instance list).

Then, add this to your jQuery code:

$('#list').live('click', function(e) {
    var anchor = e.target;
    // do stuff with your anchor
});

Live demo: http://jsfiddle.net/7Lqtn/


来源: stackexchange

问:
Do nothing on table row hover - How could I do this?
I have been trying to disable the row hover for antd table (for expandable rows) but no success. I want to disable the hover on all child rows.

Here is a simple table that I am generating using antd.

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Table } from 'antd';

const columns = [
    {
        title: 'Name',
        dataIndex: 'name',
        key: 'name',
    }
];

const data = [
    {
        key: 1,
        name: 'John Brown sr.',
        age: 60,
        address: 'New York No. 1 Lake Park',
        children: [
        {
            key: 11,
            name: 'John Brown',
        },
        {
            key: 12,
            name: 'John Brown jr.'
        },
        {
            key: 13,
            name: 'Jim Green sr.'
        },
        ],
    }
];

ReactDOM.render(
    <Table columns={columns} dataSource={data} />,
    document.getElementById('container'),
);
</code>```

Here is the table fiddle that shows the table, that gets rendered. The CSS that I am trying to apply the change the hover is:

```<code>tr.ant-table-row.ant-table-row-level-1:hover {
   background: red;
}
</code>```

But this does not work. I see a fluctuation of colors between red and blue. How could I do this?

What I mainly want is no hover effect. But I am unable to do this.

答:
The accepted answers did not work for me, if anyone else has this problem this is how I fixed it:

First, set the className property in the Table component to something, for e.g. 'time-table-row-select' like below:

```<code><Table
    dataSource={data}
    columns={columns}
    className='time-table-row-select'
/>
</code>```

Then add the following in CSS:

```<code>.time-table-row-select > .ant-spin-nested-loading > .ant-spin-container > div > .ant-table-content > .ant-table-body > table > tbody > tr:hover > td {
    background-color: unset;
}
</code>```

Alternatively, if you're using the scroll parameter you need to use this:

```<code>.time-table-row-select > .ant-spin-nested-loading > .ant-spin-container > div > .ant-table-content > .ant-table-scroll > .ant-table-body > table > tbody > tr:hover > td {
    background-color: unset;
}
</code>```

Since there appears to be additional caveats depending on how you are using the table, I'll go through my logic for how to figure out which class selector to use (as it seems like most people on web development stackoverflow do not do this & it's incredibly frustrating):

Find the location of the class you provided to the Table component, then append each subsequent child tag to your selector until you reach the tr tag that follows tbody, add :hover to it, then add > td to that

ContentLicense: CC BY-SA 4.0

Body:
I have been trying to disable the row hover for antd table (for expandable rows) but no success. I want to disable the hover on all child rows.

Here is a simple table that I am generating using antd.

import React from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Table } from 'antd';

const columns = [
    {
        title: 'Name',
        dataIndex: 'name',
        key: 'name',
    }
];

const data = [
    {
        key: 1,
        name: 'John Brown sr.',
        age: 60,
        address: 'New York No. 1 Lake Park',
        children: [
        {
            key: 11,
            name: 'John Brown',
        },
        {
            key: 12,
            name: 'John Brown jr.'
        },
        {
            key: 13,
            name: 'Jim Green sr.'
        },
        ],
    }
];

ReactDOM.render(

,
    document.getElementById('container'),
);

Here is the table fiddle that shows the table, that gets rendered. The CSS that I am trying to apply the change the hover is:

tr.ant-table-row.ant-table-row-level-1:hover {
   background: red;
}

But this does not work. I see a fluctuation of colors between red and blue. How could I do this?

What I mainly want is no hover effect. But I am unable to do this.

Body:
The accepted answers did not work for me, if anyone else has this problem this is how I fixed it:

First, set the className property in the Table component to something, for e.g. 'time-table-row-select' like below:

<Table
    dataSource={data}
    columns={columns}
    className='time-table-row-select'
/>

Then add the following in CSS:

.time-table-row-select > .ant-spin-nested-loading > .ant-spin-container > div > .ant-table-content > .ant-table-body > table > tbody > tr:hover > td {
    background-color: unset;
}

Alternatively, if you're using the scroll parameter you need to use this:

.time-table-row-select > .ant-spin-nested-loading > .ant-spin-container > div > .ant-table-content > .ant-table-scroll > .ant-table-body > table > tbody > tr:hover > td {
    background-color: unset;
}

Since there appears to be additional caveats depending on how you are using the table, I'll go through my logic for how to figure out which class selector to use (as it seems like most people on web development stackoverflow do not do this & it's incredibly frustrating):

Find the location of the class you provided to the Table component, then append each subsequent child tag to your selector until you reach the tr tag that follows tbody, add :hover to it, then add > td to that


问:
How to set secure flag in my cookie using ngx-cookie-service for Angular?
I want to set the secure flag in my cookie when I create it. I think I have the solution but I want to be sure in order to continue. I use the ngx-cookie-service to set my cookie.

Here is my code:

```<code>const now = new Date();
now.setHours(now.getHours() + 8);
const secureFlag = true;
this.cookieService.set('usertype', 'agent', now, '/', '/', secureFlag);
</code>```

The thing is that I don't know if I have to declare the 4th and 5th parameter like that because if I don't declare them it shows error.

For example I try this:

```<code>const now = new Date();
now.setHours(now.getHours() + 8);
const secureFlag = true;
this.cookieService.set('usertype', 'agent', now, secureFlag);
</code>```

and it warns me with Argument of type 'true' is not assignable to parameter of type 'string'

Do I have to use '/' for path and domain parameters when I don't want to define them?

答:
The get method of CookieService supports the following parameters:

```<code>    /**
     * @param name     Cookie name
     * @param value    Cookie value
     * @param expires  Number of days until the cookies expires or an actual `Date`
     * @param path     Cookie path
     * @param domain   Cookie domain
     * @param secure   Secure flag
     * @param sameSite OWASP samesite token `Lax`, `None`, or `Strict`. Defaults to `None`
     */
    set(name: string, value: string, expires?: number | Date, path?: string, domain?: string, secure?: boolean, sameSite?: 'Lax' | 'None' | 'Strict'): void;

</code>```

The error Argument of type 'true' is not assignable to parameter of type 'string'
it’s because you’re sending the secure parameter instead of path.

Body:
I want to set the secure flag in my cookie when I create it. I think I have the solution but I want to be sure in order to continue. I use the ngx-cookie-service to set my cookie.

Here is my code:

const now = new Date();
now.setHours(now.getHours() + 8);
const secureFlag = true;
this.cookieService.set('usertype', 'agent', now, '/', '/', secureFlag);

The thing is that I don't know if I have to declare the 4th and 5th parameter like that because if I don't declare them it shows error.

For example I try this:

const now = new Date();
now.setHours(now.getHours() + 8);
const secureFlag = true;
this.cookieService.set('usertype', 'agent', now, secureFlag);

and it warns me with Argument of type 'true' is not assignable to parameter of type 'string'

Do I have to use '/' for path and domain parameters when I don't want to define them?

Body:
The get method of CookieService supports the following parameters:

    /**
     * @param name     Cookie name
     * @param value    Cookie value
     * @param expires  Number of days until the cookies expires or an actual `Date`
     * @param path     Cookie path
     * @param domain   Cookie domain
     * @param secure   Secure flag
     * @param sameSite OWASP samesite token `Lax`, `None`, or `Strict`. Defaults to `None`
     */
    set(name: string, value: string, expires?: number | Date, path?: string, domain?: string, secure?: boolean, sameSite?: 'Lax' | 'None' | 'Strict'): void;

The error Argument of type 'true' is not assignable to parameter of type 'string'
it’s because you’re sending the secure parameter instead of path.


问:
Is it possible to make pods of a StatefulSet to run different app images in Kubernetes?
I want to create a StatefulSet where I want my first pod(i.e. ordeal index-0)to behave as a router(routing-app) for the pods starting with ordeal index 1(serving-app).

I am new to Kubernetes StatefulSets, and still trying to figure out their usage in real world applications.Please let me know, if am trying out something that I should not do from the design perspective or should I try something else to accomplish my requirement. Thanks, J

答: You cannot have two pods of same statefulsets running different images. It is possible to run two different images in one pod and it will be same for all the pods of your statefulset. You need to create two different statefulsets or your application which requires persistence as statefulset and other as deployment. Refer the documentation https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#limitations for more information.


问:
Run matplotlib plot label, then display error box
I'm testing a simple line graph.

```<code>from matplotlib import pyplot
import random
fig = pyplot.figure(figsize=(20,8),dpi=80)
x = range (2,26,2)
y = [15,13,14,5,17,20,25,26,26,24,22,18]
z = [random.randint(20,35) for i in range(12)]
pyplot.xticks(range(2,24,1),rotation = 45,fontproperties = my_font) #rotation旋转度数
pyplot.yticks(range(min(y),max(y)+1))
pyplot.xlabel("")
pyplot.ylabel("")
pyplot.title("")
pyplot.grid(alpha=0.4,linestyle='--')
pyplot.legend()
pyplot.plot(x,y, label='111111' ,color='orange',linestyle=':')
pyplot.plot(x,z, label="222222" ,color='#000000',linestyle='-.') # --
pyplot.show()
</code>```

But when I run it, the display of label on top right corner CANNOT display well.
It should display 11111 or 22222 in the box. But it now displays empty box.
How to solve this?
error screenshot

答: The legend uses the labels defined in the pyplot.plot() function. Therefore you first have to plot your data and then call pyplot.legend()

Body:
I'm testing a simple line graph.

from matplotlib import pyplot
import random
fig = pyplot.figure(figsize=(20,8),dpi=80)
x = range (2,26,2)
y = [15,13,14,5,17,20,25,26,26,24,22,18]
z = [random.randint(20,35) for i in range(12)]
pyplot.xticks(range(2,24,1),rotation = 45,fontproperties = my_font) #rotation旋转度数
pyplot.yticks(range(min(y),max(y)+1))
pyplot.xlabel("")
pyplot.ylabel("")
pyplot.title("")
pyplot.grid(alpha=0.4,linestyle='--')
pyplot.legend()
pyplot.plot(x,y, label='111111' ,color='orange',linestyle=':')
pyplot.plot(x,z, label="222222" ,color='#000000',linestyle='-.') # --
pyplot.show()

But when I run it, the display of label on top right corner CANNOT display well.
It should display 11111 or 22222 in the box. But it now displays empty box.
How to solve this?
error screenshot


问:
Need Advice: Facebook Like Button to like a subsite
i'm struggling around for days now ...this is the scenario:

a user can upload a pic and add some text on the site. After that, he/she gets a link that leads to his created content. I want the user not only to share his content with the link, but also on facebook with specified image and text. Tried this with open graph tags, but it is bad changing those tags dynamicly before liking because fb caches that info and does not recognize specific changes ... but correct me if i'm wrong ...

The problem seems to be, that when the user clicks on the like button, the content to share is not the actual site, but the subsite with its content ...

How would you do this?
Thanks for any advice!

答: doing it with the fbjs sdk was the right hint ... now it works perfektly and individual ...</p>

ContentLicense: CC BY-SA 3.0


问:
How to create a service mock implementation in laravel
I am quite on new Laravel I am trying to create some mock services.

If I will send a request to some URL :http:/example.com?token={token}. It will return user data if I have token access. The case is that I don't have token access and I cannot get user data. Now I want to create mock service to get user data when I don't have a token and save data on the database.

For example, I have CSV fill user data like this:

```<code>   *----*-------*-------------*---------------*
   | Id |  Name | phoneNumber |  dateOfBirth  |
   *----*-------*-------------*---------------*
   | #1 | test1 |   1234      |  12-12-2001   |
   | #2 | test1 |   12345     |  12-12-2005   |
   *----*-------*-------------*---------------*
</code>```

when I am sending request to my laravel application then I want to create service-mock implementation with the service interface. My mock service adapter now should user above csv data and store data in the database.

I am not getting how I can create this type of mock service on laravel. Anyone, will you please give me some idea of how I can do the implementation.

It would really help if some get some ideas for implementation.

答:
Laravel comes with a feature called model factories that are designed to allow you to quickly build out “fake” models (dummy data) which probably what you're looking for.

These have several use cases with the two biggest being–testing (mocking) and database seeding.

Documentation

Body:
I am quite on new Laravel I am trying to create some mock services.

If I will send a request to some URL :http:/example.com?token={token}. It will return user data if I have token access. The case is that I don't have token access and I cannot get user data. Now I want to create mock service to get user data when I don't have a token and save data on the database.

For example, I have CSV fill user data like this:

   *----*-------*-------------*---------------*
   | Id |  Name | phoneNumber |  dateOfBirth  |
   *----*-------*-------------*---------------*
   | #1 | test1 |   1234      |  12-12-2001   |
   | #2 | test1 |   12345     |  12-12-2005   |
   *----*-------*-------------*---------------*

when I am sending request to my laravel application then I want to create service-mock implementation with the service interface. My mock service adapter now should user above csv data and store data in the database.

I am not getting how I can create this type of mock service on laravel. Anyone, will you please give me some idea of how I can do the implementation.

It would really help if some get some ideas for implementation.


问:
php artisan migrate - SQLSTATE[HY000] [1045] Access denied for user 'laravel'@'localhost'
I want to set up and learn Laravel following this course

When I try to use the command php artisan migrate I get this error:

```<code>[Illuminate\Database\QueryException]
  SQLSTATE[HY000] [1045] Access denied for user 'laravel'@'localhost' (using password: NO) (SQL: select * from information_schema.tables whe
  re table_schema = laravel and table_name = migrations)

[PDOException]
  SQLSTATE[HY000] [1045] Access denied for user 'laravel'@'localhost' (using password: NO)
</code>```

I have looked for answers. I figured I may have to make some changes in the .env file, but I don't know what, and nothing I have tried so far has worked.

```<code>DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=laravel
DB_PASSWORD=
</code>```

I'm using Ubuntu 16.04, not a Mac OS X as in the video, so I wonder what should I do differently? Is there some MySQL setting I did not set correctly?

答:
I also had such problem. I created a new database by

```<code>CREATE DATABASE askiDB CHARACTER SET utf8;
</code>```

Then in the navigator console of MySQL Workbench I selected this database and in the administrative roles tab selected all Roles. Then I set a password in the login tab.
Moreover, in .env file of the project I set the DB_USERNAME and DB_PASSWORD of this file correctly.
Then I execute the below command
    php artisan migrate

and it worked fine.

Body:
I want to set up and learn Laravel following this course

When I try to use the command php artisan migrate I get this error:

[Illuminate\Database\QueryException]
  SQLSTATE[HY000] [1045] Access denied for user 'laravel'@'localhost' (using password: NO) (SQL: select * from information_schema.tables whe
  re table_schema = laravel and table_name = migrations)

[PDOException]
  SQLSTATE[HY000] [1045] Access denied for user 'laravel'@'localhost' (using password: NO)

I have looked for answers. I figured I may have to make some changes in the .env file, but I don't know what, and nothing I have tried so far has worked.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=laravel
DB_PASSWORD=

I'm using Ubuntu 16.04, not a Mac OS X as in the video, so I wonder what should I do differently? Is there some MySQL setting I did not set correctly?

Body:
I also had such problem. I created a new database by

CREATE DATABASE askiDB CHARACTER SET utf8;

Then in the navigator console of MySQL Workbench I selected this database and in the administrative roles tab selected all Roles. Then I set a password in the login tab.
Moreover, in .env file of the project I set the DB_USERNAME and DB_PASSWORD of this file correctly.
Then I execute the below command
    php artisan migrate

and it worked fine.


问:
Can Ruby print out time difference (duration) readily?
Can Ruby do something like this?

```<code>irb(main):001:0> start = Time.now
=> Thu Nov 05 01:02:54 -0800 2009

irb(main):002:0> Time.now - start
=> 25.239

irb(main):003:0> (Time.now - start).duration
=> "25 seconds"
</code>```

(the duration method doesn't exist now)...  and similarly, report

```<code>23 minutes and 35 seconds
1 hour and 33 minutes
2 days and 3 hours
</code>```

(either report the whole duration, up to how many seconds, or report up to 2 numbers and units (if day and hour is reported, then no need to tell how many minutes))

答:
I know this is a Ruby specific question, but if you found it like me, looking for a solution in the context of Rails,
please, consider ActiveSupport::Duration and it's inspect and parts methods in particular.

For example:

start = Time.now
# => 2020-02-15 19:12:50.128638

ActiveSupport::Duration.build(Time.now - start).inspect
# => "1 minute and 52.477355 seconds"

ActiveSupport::Duration.build(Time.now - start).parts
# => {:minutes=>1, :seconds=>55.457125}
```

If you are not satisfied by inpect output, you can try to implement your own logic based on parts hash.

P.S. If you have a Plain Ruby project, do not forget that you can use ActiveSupport as a standalone library.

ContentLicense: CC BY-SA 2.5

Body:
Can Ruby do something like this?

irb(main):001:0> start = Time.now
=> Thu Nov 05 01:02:54 -0800 2009

irb(main):002:0> Time.now - start
=> 25.239

irb(main):003:0> (Time.now - start).duration
=> "25 seconds"

(the duration method doesn't exist now)...  and similarly, report

23 minutes and 35 seconds
1 hour and 33 minutes
2 days and 3 hours

(either report the whole duration, up to how many seconds, or report up to 2 numbers and units (if day and hour is reported, then no need to tell how many minutes))

Body:
I know this is a Ruby specific question, but if you found it like me, looking for a solution in the context of Rails,
please, consider ActiveSupport::Duration and it's inspect and parts methods in particular.

For example:

start = Time.now
# => 2020-02-15 19:12:50.128638

ActiveSupport::Duration.build(Time.now - start).inspect
# => "1 minute and 52.477355 seconds"

ActiveSupport::Duration.build(Time.now - start).parts
# => {:minutes=>1, :seconds=>55.457125}

If you are not satisfied by inpect output, you can try to implement your own logic based on parts hash.

P.S. If you have a Plain Ruby project, do not forget that you can use ActiveSupport as a standalone library.


问:
Designing database schema for models with multiple sorts of data
This question is about database design and how to best split your
entities when they serve more than one purpose.

My database schema models sports events around the world. What type of
event and sport, when and where it is played, what the participants
are and the winner and so on. One of the entities in the schema is
Country which keeps track of in which country in the world the sport
event took place in.

This works well, but then I also need to add auxilliary data to the
Country model, which is not related to the sport events model per se,
but is required for rendering the data nicely on a web page.

Examples of that data is the countrys flags sprite offset in the
sprite image, a long description of the country, the adjective for the
country (China - chinese etc), number of visitors on the country page
and the subjective importance of the country on a scale from 1-5
(events in countries rated five are shown on the front page).

I could easily put all those attributes on the Country object itself,
but it seems wrong, and pollutes my clean sports event schema. I don't
think the structure of the data should be mixed with details like how
to render it nicely... So the question is how I should organise it
instead?

答: I would keep this data on a 'Countries' table and create a FK to your sports data.  This will allow you to easily maintain each Country's attributes  as you will only have to update them in one place and the changes will take effect everywhere it is referenced.  I don't think this pollutes your data as the information is relevant to your application.  Furthermore, if you do try to separate this data it will only make your schema more complex and maintenance more difficult.  </p>


问:
How to get the Label name of the pie chart using angular
I just created pie chart in angular 8. And I can able to view it. But I just want to get the label name based on the pie chart click.

Image:

Installed

```<code>npm install ng2-charts
</code>```

Added below lines in html file:

```<code><div style="display: block">
    <canvas id="pie" baseChart
            [data]="pieChartData"
            [labels]="pieChartLabels"
            [chartType]="pieChartType"
            (chartHover)="chartHovered($event)"
            (chartClick)="chartClicked($event)"></canvas>
  </div>
</code>```

Added below lines in script file:

```<code> public pieChartLabels: string[] = ['PayCreditWallet','Paypal','Google Pay','Amazon Pay'];
 public pieChartData: number[] = [1,2,3,4];
 public pieChartType: any = 'pie';

  // events
  public chartClicked(e: any): void {
    alert(e);
  }

 public chartHovered(e: any): void {

    console.log(e.data);
  }
</code>```

When I click the Label (slice) in pie chart I can see click event as alert as mentioned above. Is it possible to get the label name when I click the specific label in pie chart (Slice). Example: In pie chart if I click 'AmazonPay' alert should shows 'AmazonPay'. I don't know how to achieve this. Can someone please help me on this?

答:
Try this code:

.ts file

```<code> public barChartOptions = {
    legend: {
      labels: {
        //fontFamily: '"Arvo", serif',
        fontSize: 20,
      }
    }
  };
public chartClicked(e: any): void {
    if (e.active.length > 0) {
      const chart = e.active[0]._chart;
      const activePoints = chart.getElementAtEvent(e.event);
        if ( activePoints.length > 0) {
          // get the internal index of slice in pie chart
          const clickedElementIndex = activePoints[0]._index;
          const label = chart.data.labels[clickedElementIndex];
          console.log(label)
        }
      }
  }
</code>```

.html

```<code><div style="display: block">
    <canvas id="pie" baseChart
            [data]="pieChartData"
            [labels]="pieChartLabels"
            [chartType]="pieChartType"
            (chartHover)="chartHovered($event)"
            (chartClick)="chartClicked($event)"
            [options]="barChartOptions"></canvas>
  </div>
</code>```

working link

https://stackblitz.com/edit/angular-lrq4ee

Github link for this

https://github.com/valor-software/ng2-charts/issues/489

Body:
I just created pie chart in angular 8. And I can able to view it. But I just want to get the label name based on the pie chart click.

Image:

Installed

npm install ng2-charts

Added below lines in html file:

    <canvas id="pie" baseChart
            [data]="pieChartData"
            [labels]="pieChartLabels"
            [chartType]="pieChartType"
            (chartHover)="chartHovered($event)"
            (chartClick)="chartClicked($event)"></canvas>

Added below lines in script file:

 public pieChartLabels: string[] = ['PayCreditWallet','Paypal','Google Pay','Amazon Pay'];
 public pieChartData: number[] = [1,2,3,4];
 public pieChartType: any = 'pie';

  // events
  public chartClicked(e: any): void {
    alert(e);
  }

 public chartHovered(e: any): void {

    console.log(e.data);
  }

When I click the Label (slice) in pie chart I can see click event as alert as mentioned above. Is it possible to get the label name when I click the specific label in pie chart (Slice). Example: In pie chart if I click 'AmazonPay' alert should shows 'AmazonPay'. I don't know how to achieve this. Can someone please help me on this?

Body:
Try this code:

.ts file

 public barChartOptions = {
    legend: {
      labels: {
        //fontFamily: '"Arvo", serif',
        fontSize: 20,
      }
    }
  };
public chartClicked(e: any): void {
    if (e.active.length > 0) {
      const chart = e.active[0]._chart;
      const activePoints = chart.getElementAtEvent(e.event);
        if ( activePoints.length > 0) {
          // get the internal index of slice in pie chart
          const clickedElementIndex = activePoints[0]._index;
          const label = chart.data.labels[clickedElementIndex];
          console.log(label)
        }
      }
  }

.html

<div style="display: block">
    <canvas id="pie" baseChart
            [data]="pieChartData"
            [labels]="pieChartLabels"
            [chartType]="pieChartType"
            (chartHover)="chartHovered($event)"
            (chartClick)="chartClicked($event)"
            [options]="barChartOptions"></canvas>
  </div>

working link

https://stackblitz.com/edit/angular-lrq4ee

Github link for this

https://github.com/valor-software/ng2-charts/issues/489


问:
get the url of the visited page using a bookmarklet
How can I get the actual url of the visited page using a bookmarklet?

The idea is to click on a bookmark and the script in the bookmark returns the url.

This was a function available in Plex some time ago as a "watch later" feature to save a playlist. So it is working, but I don't know how.

答:
javascript:(()=>{console.log(location.href);})();
```

<p><code>location.href</code> holds the current URL string.</p>

<hr>

<p><strong>Edit</strong> in response to question in comment</p>

<blockquote>
  <p>Any idea how I can send it to php like this: <code>script.php?url=this_url</code></p>

  <p>or</p>

  <p>How can I send the current URL as search parameter value to another URL?</p>
</blockquote>

<p>Let's say you want to send it to <code>https://example.com?script.php?url=</code> <code><the current URL></code>. You'd just set <code>location.href</code> to the new URL and use <code>encodeURI</code> to encode the current URL (from <code>location.href</code>). (Kind of meta, right?) This is what that would look like:</p>

<pre class="lang-js prettyprint-override"><code>javascript:(()=>{location.href=`https://example.com/script.php?url=${encodeURI(location.href)}`;})();
</code>```

In fact, I'll make it even easier for you. Just expand and run the code snippet below, and you can input the URL that you want to send it to (e.g. https://example.com/script?url=) and you'll see the JavaScript bookmarklet update as you type.

(() => {
  'use strict';

  const copyTextToClipboard = text => new Promise(async (resolve, reject) => {
    const fallback = text => {
      const textArea = document.createElement("textarea");
      textArea.value = text;
      textArea.style.position='fixed';
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
      try {
        const successful = document.execCommand('copy');
        successful
          ? resolve(true)
          : reject(new Error('"document.execCommand(\'copy\')" failed'));
      } catch (err) {
        reject(err);
      }
      finally {
        document.body.removeChild(textArea);
      }
    };

    if (!navigator.clipboard) {
      fallback(text);
      return;
    }
    try {
      await navigator.clipboard.writeText(text);
      resolve(true);
    }
    catch (err) {
      reject(err);
    }
  });

  const input = document.getElementById('input');
  const output = document.getElementById('output');
  const copyButton = document.getElementById('copy');

  const makeBookmarklet = string =>
    `javascript:(()=>{location.href=\`${string}\${encodeURI(location.href)}\`;})();`;

  const updateOutput = ev => {
    output.textContent = makeBookmarklet(ev.target.value.trim());
  };

  const placeholder = 'https://example.com/script.php?url=';
  input.placeholder = placeholder;
  output.textContent = makeBookmarklet(placeholder);
  input.addEventListener('input', updateOutput);
  copyButton.addEventListener('click', () => copyTextToClipboard(output.textContent));
})();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  box-sizing: border-box;
}

#input,
#output,
#copy {
  border-radius: 0.25em;
  padding: 0.5em;
}

#input {
  font-family: monospace;
  display: block;
  width: 100%;
}

#output {
  background-color: lightgrey;
  padding: 1em;
}

#copy {
  background-color: grey;
  color: white;
  cursor: pointer;
}

pre {
  font-size: 1.2em;
  /* height: 5em; */
  margin: 1em 0 0.5em;
  overflow-x: auto;
  padding: 1em 0;
}</code>```

  <input id="input" type="text" />
  ```<code id="output"></code>```

<button id="copy">Copy bookmarklet</button>

```

Body:
javascript:(()=>{console.log(location.href);})();

location.href holds the current URL string.

Edit in response to question in comment

Any idea how I can send it to php like this: script.php?url=this_url

or

How can I send the current URL as search parameter value to another URL?

Let's say you want to send it to https://example.com?script.php?url= <the current URL>. You'd just set location.href to the new URL and use encodeURI to encode the current URL (from location.href). (Kind of meta, right?) This is what that would look like:

javascript:(()=>{location.href=`https://example.com/script.php?url=${encodeURI(location.href)}`;})();

In fact, I'll make it even easier for you. Just expand and run the code snippet below, and you can input the URL that you want to send it to (e.g. https://example.com/script?url=) and you'll see the JavaScript bookmarklet update as you type.

(() => {
  'use strict';

  const copyTextToClipboard = text => new Promise(async (resolve, reject) => {
    const fallback = text => {
      const textArea = document.createElement("textarea");
      textArea.value = text;
      textArea.style.position='fixed';
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
      try {
        const successful = document.execCommand('copy');
        successful
          ? resolve(true)
          : reject(new Error('"document.execCommand(\'copy\')" failed'));
      } catch (err) {
        reject(err);
      }
      finally {
        document.body.removeChild(textArea);
      }
    };

    if (!navigator.clipboard) {
      fallback(text);
      return;
    }
    try {
      await navigator.clipboard.writeText(text);
      resolve(true);
    }
    catch (err) {
      reject(err);
    }
  });

  const input = document.getElementById('input');
  const output = document.getElementById('output');
  const copyButton = document.getElementById('copy');

  const makeBookmarklet = string =>
    `javascript:(()=>{location.href=\`${string}\${encodeURI(location.href)}\`;})();`;

  const updateOutput = ev => {
    output.textContent = makeBookmarklet(ev.target.value.trim());
  };

  const placeholder = 'https://example.com/script.php?url=';
  input.placeholder = placeholder;
  output.textContent = makeBookmarklet(placeholder);
  input.addEventListener('input', updateOutput);
  copyButton.addEventListener('click', () => copyTextToClipboard(output.textContent));
})();

* {
  box-sizing: border-box;
}

#input,
#output,
#copy {
  border-radius: 0.25em;
  padding: 0.5em;
}

#input {
  font-family: monospace;
  display: block;
  width: 100%;
}

#output {
  background-color: lightgrey;
  padding: 1em;
}

#copy {
  background-color: grey;
  color: white;
  cursor: pointer;
}

pre {
  font-size: 1.2em;
  /* height: 5em; */
  margin: 1em 0 0.5em;
  overflow-x: auto;
  padding: 1em 0;
}

<div>
  <input id="input" type="text" />
  <pre><code id="output"></code></pre>
  <div><button id="copy">Copy bookmarklet</button></div>
</div>


问:
font-face with bold weight not being recognized
I am using 2 @font-face on my index.css file with the purpose of using a font in regular weight and in bold weight as my default font in my entire application:

index.css file:

```<code>body {
    padding: 0px;
    margin:0px;
    font-family: "LucidaGrande";
}

@font-face {
  font-family: 'LucidaGrande';
  src: local('LucidaGrande'), url(../assets/fonts/LucidaGrande.ttf) format('truetype');
}

@font-face {
  font-family: 'LucidaGrande';
  font-weight: 900;
  src: local('LucidaGrande'), url(../assets/fonts/LucidaGrandeBold.ttf) format('truetype');
}
</code>```

Now, the regular weight seems to be working for the entire application, however, on an other part of my application I am trying to use the font in bold weight like this:

```<code>#presentation-text em{
    font-size: 35px;
    color: rgb(139, 59, 28);
    font-style: normal;
    font-weight: 900;
  }
</code>```

However the 900 i.e the bold weight is not being applied, still regular.

Am I using this correctly?

答:
If you're using @font-face, never use local(...). The whole reason you're using @font-face is to ensure that you control exactly which font resource gets loaded for which (set of) font properties. The last thing you want is for the OS to black-box fetch you what it thinks the font is for the name you specified. Even if it really does find Lucida Grande for some user, there is zero guarantee it's going to be the same version you have installed on your development machine.

Interestingly that actually tangential to the real problem here: the way you've written your CSS right now means that, because you have the font installed locally, whatever follows local(...) will never even be looked at by the browser, similar to what happens when you're using font-family: serif, Times. The browser knows how to resolve the first thing, so it immediately stops: it already found what it needed to find.

Effectively your current CSS, running in a browser on your own machine, says this, as far as the browser is concerned:

```<code>@font-face {
  font-family: 'LucidaGrande';
  src: local('LucidaGrande);
}

@font-face {
  font-family: 'LucidaGrande';
  font-weight: 900;
  src: local('LucidaGrande);
}
</code>```

So you're loading the exact same thing in both declarations. As CSS weights for the text shaper in the browser are entirely independent from the system text engine, the result is exactly what you're seeing: both rules declare the same font resource as the one to use when you say font-family: LucidaGrande, both with or without font-weight: 900.

Drop local(...) and it'll instead work exactly as you need it to.

Also, you'll want to turn those .ttf files into WOFF2 and then load those, because they're much smaller, as well as a promise to the browser that these are indeed unencumbered webfonts.

Body:
I am using 2 @font-face on my index.css file with the purpose of using a font in regular weight and in bold weight as my default font in my entire application:

index.css file:

body {
    padding: 0px;
    margin:0px;
    font-family: "LucidaGrande";
}

@font-face {
  font-family: 'LucidaGrande';
  src: local('LucidaGrande'), url(../assets/fonts/LucidaGrande.ttf) format('truetype');
}

@font-face {
  font-family: 'LucidaGrande';
  font-weight: 900;
  src: local('LucidaGrande'), url(../assets/fonts/LucidaGrandeBold.ttf) format('truetype');
}

Now, the regular weight seems to be working for the entire application, however, on an other part of my application I am trying to use the font in bold weight like this:

#presentation-text em{
    font-size: 35px;
    color: rgb(139, 59, 28);
    font-style: normal;
    font-weight: 900;
  }

However the 900 i.e the bold weight is not being applied, still regular.

Am I using this correctly?

Body:
If you're using @font-face, never use local(...). The whole reason you're using @font-face is to ensure that you control exactly which font resource gets loaded for which (set of) font properties. The last thing you want is for the OS to black-box fetch you what it thinks the font is for the name you specified. Even if it really does find Lucida Grande for some user, there is zero guarantee it's going to be the same version you have installed on your development machine.

Interestingly that actually tangential to the real problem here: the way you've written your CSS right now means that, because you have the font installed locally, whatever follows local(...) will never even be looked at by the browser, similar to what happens when you're using font-family: serif, Times. The browser knows how to resolve the first thing, so it immediately stops: it already found what it needed to find.

Effectively your current CSS, running in a browser on your own machine, says this, as far as the browser is concerned:

@font-face {
  font-family: 'LucidaGrande';
  src: local('LucidaGrande);
}

@font-face {
  font-family: 'LucidaGrande';
  font-weight: 900;
  src: local('LucidaGrande);
}

So you're loading the exact same thing in both declarations. As CSS weights for the text shaper in the browser are entirely independent from the system text engine, the result is exactly what you're seeing: both rules declare the same font resource as the one to use when you say font-family: LucidaGrande, both with or without font-weight: 900.

Drop local(...) and it'll instead work exactly as you need it to.

Also, you'll want to turn those .ttf files into WOFF2 and then load those, because they're much smaller, as well as a promise to the browser that these are indeed unencumbered webfonts.


问:
C# calculate accurate age
anyone know how to get the age based on a date(birthdate)

im thinking of something like this

```<code>string age = DateTime.Now.GetAccurateAge();
</code>```

and the output will be some thing like 20Years 5Months 20Days

答:
If you have a Instance Variable/Property that names DateOfBirth, you can use this method. Otherwise, you can pass the Date of Birth as a parameter for method.
I made some calculus and I proved that never fails.

```<code>public int AgeCalc(){
      DateTime now = DateTime.Now;
      double age =  Math.Floor((DateTime.Now - DateOfBirth).TotalDays)/((DateTime.IsLeapYear(year: now.Year)? 366 : 365));
      return (age % 1) >= 0.951 ? Math.Round(age) : Math.Floor(age);
}

</code>```

I hope that this can help you :)

Title: C# calculate accurate age

Body:
anyone know how to get the age based on a date(birthdate)

im thinking of something like this

string age = DateTime.Now.GetAccurateAge();

and the output will be some thing like 20Years 5Months 20Days

Body:
If you have a Instance Variable/Property that names DateOfBirth, you can use this method. Otherwise, you can pass the Date of Birth as a parameter for method.
I made some calculus and I proved that never fails.

public int AgeCalc(){
      DateTime now = DateTime.Now;
      double age =  Math.Floor((DateTime.Now - DateOfBirth).TotalDays)/((DateTime.IsLeapYear(year: now.Year)? 366 : 365));
      return (age % 1) >= 0.951 ? Math.Round(age) : Math.Floor(age);
}

I hope that this can help you :)


问:
Query a table while excluding values referenced in other tables
I have a database filled with transactions from various bank accounts. Each transactions comes with a user_id, bank_id, account_id and a transaction_id. I'd like to exclude transactions when querying, if the user chooses to ignore a bank, account or an individual transaction.

In other words, if a user:

ignores a bank, all transactions with that bank_id are skipped,

ignores an account, all transactions with that account_id are skipped,

ignores an individual transaction, the transaction with that transaction_id is skipped.

My current database looks like this:

```<code>-- Simplified for brevity.
CREATE TABLE IF NOT EXISTS transactions
(
    user_id        TEXT NOT NULL,
    transaction_id TEXT NOT NULL,
    account_id     TEXT NOT NULL,
    bank_id        TEXT NOT NULL,
    PRIMARY KEY (user_id, transaction_id)
);

-- Exclusion tables for banks and accounts are similar.
CREATE TABLE IF NOT EXISTS excluded_transactions
(
    id             INTEGER PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
    user_id        TEXT NOT NULL,
    transaction_id TEXT NOT NULL
);

CREATE INDEX IF NOT EXISTS exc_trn_idx ON excluded_transactions (user_id, transaction_id);
</code>```

Whenever a user abc excludes a bank, account or a transaction, it is added to the appropriate exclusion table. The query then looks like this:

```<code>WITH b AS (
  SELECT bank_id FROM excluded_banks WHERE user_id = 'abc'
), a AS (
  SELECT account_id FROM excluded_accounts WHERE user_id = 'abc'
), t AS (
  SELECT transaction_id FROM excluded_transactions WHERE user_id = 'abc'
)
SELECT * FROM transactions
WHERE user_id = 'abc'
AND bank_id NOT IN (SELECT * FROM b)
AND account_id NOT IN (SELECT * FROM a)
AND transaction_id NOT IN (SELECT * FROM t)
</code>```

This gives an OK performance on a test set of ~1M transactions (~100ms planning time, ~1s execution time, on average). However, I'm worried it will degrade significantly as the database grows.

My question is: how can I improve the tables/queries to efficiently retrieve transactions with the constraints mentioned above? Slower writes are acceptable if they make the reads faster. Also, if the general approach I took is suboptimal, please let me know and/or suggest an improved one.

答:
I would suggest writing this as:

```<code>SELECT t.*
FROM transactions t
WHERE t.user_id = 'abc' AND
      NOT EXISTS (SELECT 1
                  FROM excluded_banks eb
                  WHERE eb.bank_id = t.bank_id AND
                        eb.user_id = t.user_id
                 ) AND
      NOT EXISTS (SELECT 1
                  FROM excluded_accounts ea
                  WHERE ea.account_id = t.account_id AND
                        ea.user_id = t.user_id
                 ) AND
      NOT EXISTS (SELECT 1
                  FROM excluded_transaction et
                  WHERE et.transaction_id = t.transaction_id AND
                        et.user_id = t.user_id
                 );
</code>```

Then be sure you have the following indexes:

excluded_banks(user_id, bank_id)

excluded_accounts(user_id, account_id)

excluded_transaction(user_id, transaction_id)

Body:
I have a database filled with transactions from various bank accounts. Each transactions comes with a user_id, bank_id, account_id and a transaction_id. I'd like to exclude transactions when querying, if the user chooses to ignore a bank, account or an individual transaction.

In other words, if a user:

ignores a bank, all transactions with that bank_id are skipped,

ignores an account, all transactions with that account_id are skipped,

ignores an individual transaction, the transaction with that transaction_id is skipped.

My current database looks like this:

-- Simplified for brevity.
CREATE TABLE IF NOT EXISTS transactions
(
    user_id        TEXT NOT NULL,
    transaction_id TEXT NOT NULL,
    account_id     TEXT NOT NULL,
    bank_id        TEXT NOT NULL,
    PRIMARY KEY (user_id, transaction_id)
);

-- Exclusion tables for banks and accounts are similar.
CREATE TABLE IF NOT EXISTS excluded_transactions
(
    id             INTEGER PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
    user_id        TEXT NOT NULL,
    transaction_id TEXT NOT NULL
);

CREATE INDEX IF NOT EXISTS exc_trn_idx ON excluded_transactions (user_id, transaction_id);

Whenever a user abc excludes a bank, account or a transaction, it is added to the appropriate exclusion table. The query then looks like this:

WITH b AS (
  SELECT bank_id FROM excluded_banks WHERE user_id = 'abc'
), a AS (
  SELECT account_id FROM excluded_accounts WHERE user_id = 'abc'
), t AS (
  SELECT transaction_id FROM excluded_transactions WHERE user_id = 'abc'
)
SELECT * FROM transactions
WHERE user_id = 'abc'
AND bank_id NOT IN (SELECT * FROM b)
AND account_id NOT IN (SELECT * FROM a)
AND transaction_id NOT IN (SELECT * FROM t)

This gives an OK performance on a test set of ~1M transactions (~100ms planning time, ~1s execution time, on average). However, I'm worried it will degrade significantly as the database grows.

My question is: how can I improve the tables/queries to efficiently retrieve transactions with the constraints mentioned above? Slower writes are acceptable if they make the reads faster. Also, if the general approach I took is suboptimal, please let me know and/or suggest an improved one.

Body:
I would suggest writing this as:

SELECT t.*
FROM transactions t
WHERE t.user_id = 'abc' AND
      NOT EXISTS (SELECT 1
                  FROM excluded_banks eb
                  WHERE eb.bank_id = t.bank_id AND
                        eb.user_id = t.user_id
                 ) AND
      NOT EXISTS (SELECT 1
                  FROM excluded_accounts ea
                  WHERE ea.account_id = t.account_id AND
                        ea.user_id = t.user_id
                 ) AND
      NOT EXISTS (SELECT 1
                  FROM excluded_transaction et
                  WHERE et.transaction_id = t.transaction_id AND
                        et.user_id = t.user_id
                 );

Then be sure you have the following indexes:

excluded_banks(user_id, bank_id)

excluded_accounts(user_id, account_id)

excluded_transaction(user_id, transaction_id)


问:
FSharp.Compiler.Service FSharpChecker fails to compile dynamic assembly when referencing IAsyncDisposable
Running the following in a dotnet core 3.1 console application fails to compile the assembly:

```<code>module Test

open FSharp.Compiler.SourceCodeServices
open FSharp.Compiler.Text

let source = """module Test

type TestType() =
    interface System.IAsyncDisposable with
        member __.DisposeAsync() =
            System.Threading.Tasks.ValueTask()
"""

let references =
    [
        "Microsoft.Bcl.AsyncInterfaces"
    ]

[<EntryPoint>]
let main(args) =
    let checker = FSharpChecker.Create()

    let options =
        { FSharpParsingOptions.Default with
            SourceFiles = [|"empty.fs"|]
        }

    let sourceText = SourceText.ofString source

    let parseResult =
        checker.ParseFile("empty.fs", sourceText, options) |> Async.RunSynchronously

    let input = parseResult.ParseTree.Value

    let thisAssembly =
        System.Reflection.Assembly.GetExecutingAssembly().GetName().Name

    let allReferences =
        thisAssembly :: references

    let errors, _, assemblyOpt =
        checker.CompileToDynamicAssembly([input], "TestProject", allReferences, None)
        |> Async.RunSynchronously

    0
</code>```

assemblyOpt is None and the errors array contains the following messages:

```<code>The type 'IAsyncDisposable' is not defined in 'System'. Maybe you want one of the following:
   IDisposable
The type 'obj' is not an interface type
The type 'IAsyncDisposable' is not defined in 'System'. Maybe you want one of the following:
   IDisposable
The type 'IAsyncDisposable' is not defined in 'System'. Maybe you want one of the following:
   IDisposable
This type is not an interface type
No abstract or interface member was found that corresponds to this override
The value, constructor, namespace or type 'ValueTask' is not defined.
p_tyar_spec: from error
p_tyar_spec: from error
</code>```

However, both Microsoft.Bcl.AsyncInterfaces, and System should contain IAsyncDisposable. What's causing the missing reference error?

答:
I suspect its the assembly list is incomplete in some way, you can confirm this by altering the dynamic assembly generation function to the following:

```<code>checker.CompileToDynamicAssembly([input], "TestProject", allReferences, None, noframework = true)
</code>```

noframework = true

Which works, (I just tested it)

Body:
Running the following in a dotnet core 3.1 console application fails to compile the assembly:

module Test

open FSharp.Compiler.SourceCodeServices
open FSharp.Compiler.Text

let source = """module Test

type TestType() =
    interface System.IAsyncDisposable with
        member __.DisposeAsync() =
            System.Threading.Tasks.ValueTask()
"""

let references =
    [
        "Microsoft.Bcl.AsyncInterfaces"
    ]

[<EntryPoint>]
let main(args) =
    let checker = FSharpChecker.Create()

    let options =
        { FSharpParsingOptions.Default with
            SourceFiles = [|"empty.fs"|]
        }

    let sourceText = SourceText.ofString source

    let parseResult =
        checker.ParseFile("empty.fs", sourceText, options) |> Async.RunSynchronously

    let input = parseResult.ParseTree.Value

    let thisAssembly =
        System.Reflection.Assembly.GetExecutingAssembly().GetName().Name

    let allReferences =
        thisAssembly :: references

    let errors, _, assemblyOpt =
        checker.CompileToDynamicAssembly([input], "TestProject", allReferences, None)
        |> Async.RunSynchronously

    0

assemblyOpt is None and the errors array contains the following messages:

The type 'IAsyncDisposable' is not defined in 'System'. Maybe you want one of the following:
   IDisposable
The type 'obj' is not an interface type
The type 'IAsyncDisposable' is not defined in 'System'. Maybe you want one of the following:
   IDisposable
The type 'IAsyncDisposable' is not defined in 'System'. Maybe you want one of the following:
   IDisposable
This type is not an interface type
No abstract or interface member was found that corresponds to this override
The value, constructor, namespace or type 'ValueTask' is not defined.
p_tyar_spec: from error
p_tyar_spec: from error

However, both Microsoft.Bcl.AsyncInterfaces, and System should contain IAsyncDisposable. What's causing the missing reference error?

Body:
I suspect its the assembly list is incomplete in some way, you can confirm this by altering the dynamic assembly generation function to the following:

checker.CompileToDynamicAssembly([input], "TestProject", allReferences, None, noframework = true)

noframework = true

Which works, (I just tested it)


问:
How to move all element in array to bottom if?
How to move all elements in an array to the bottom if the element of an array(object) not have field date?

```<code>let records = [{"id": 1}, {"id": 2, "date": new Date()}];

return records.sort(function(a: any, b: any) {
      return a.hasOwnProperty('date')
        ? -1
        : b.hasOwnProperty('date')
        ? 1
        : 0;
    });
</code>```

So I need that all elements with the date were sorted and rest others without date placed on the bottom of the list.

答:
You could check and move the undwanted to bottom by taking a delta of the check.

const
    getISO = d => d instanceof Date
        ? d.toISOString()
        : d;

let records = [{ id: 1 }, { id: 2, date: new Date('2020-01-01') }, { id: 3 }, , { id: 2 }, { id: 4, date: new Date }];

records.sort((a, b) =>
    Number('date' in b) - Number('date' in a) ||
    getISO(b.date || '').localeCompare(getISO(a.date || ''))
);

console.log(records);```

Body:
How to move all elements in an array to the bottom if the element of an array(object) not have field date?

let records = [{"id": 1}, {"id": 2, "date": new Date()}];

return records.sort(function(a: any, b: any) {
      return a.hasOwnProperty('date')
        ? -1
        : b.hasOwnProperty('date')
        ? 1
        : 0;
    });

So I need that all elements with the date were sorted and rest others without date placed on the bottom of the list.


问:
Fastest way to build 64 bit int from four 16 bit values?
Basically I'm trying to build a unique 64bit id from coordinates that I can then pull apart later on. These operations will be performed billions of times in short order, so speed is critical. Here is what I am after.  I have 4 - 32 bit integers but only the bottom 16 bits are relevant. I want to concatenate the bottom 16 bits into one 64 bit 'long' (doesn't matter if it's signed or not, since the bits are the same).  So if I have:

```<code>largeId = 0000 0000 0000 0000   0000 0000 1000 1000
x       = 0000 0000 0000 0000   0000 0000 1100 1100
y       = 0000 0000 0000 0000   0000 0000 1110 1110
z       = 0000 0000 0000 0000   0000 0000 1111 1111
</code>```

it will become:

```<code>Id = 0000 0000 1000 1000   0000 0000 1100 1100   0000 0000 1110 1110   0000 0000 1111 1111
</code>```

I've written a few routines that produce the desired results (i.e. builds and pulls apart) and have timed them using 500^3 iterations to try to find the fastest routine.  The routine that decodes the 64 bit number back into 4 int variables runs at about 43% of the time required to encode them.  How can I speed up the encoding??

Routines:  (updated with variations of Paul Smiths suggestions below)

```<code>        public static long GetCombinedId(int largeId, int x, int y, int z)
        {

            var _largeId = (long)largeId;
            var _x = (long)x;
            var _y = (long)y;
            var _z = (long)z;

            return (_largeId << 48) | (_x << 32) | (_y << 16) | _z;

        }

        public static long GetCombinedId2(int largeId, int x, int y, int z)
        {
            return ((long)largeId << 48) | ((long)x << 32) | ((long)y << 16) | (long)z;
        }

        public static long GetCombinedId3(int largeId, int x, int y, int z)
        {
            unchecked
            {
                return ((long)(largeId << 16 | x) << 32) | (y << 16 | z );
            }

        }

        public static void GetCoordinates(long id, out int largeId, out int x, out int y, out int z)
        {

            largeId = (int)(id >> 48);

            x = (int)((id >> 32) & 0x0000_0000_0000_FFFF);
            y = (int)((id >> 16) & 0x0000_0000_0000_FFFF);
            z = (int)(id & 0x0000_0000_0000_FFFF);

        }

        public static void GetCoordinates2(long id, out int largeId, out int x, out int y, out int z)
        {

            largeId = (int)(id >> 48);

            x = (int)((id << 16 ) >> 48);
            y = (int)((id << 32 ) >> 48);
            z = (int)((id << 48 ) >> 48);

        }
</code>```

Variations of Paul Smith's technique described in answers section

```<code>  [StructLayout(LayoutKind.Explicit)]
        public struct Mapper
        {
            [FieldOffset(0)] public Int64 Combined;
            [FieldOffset(0)] public Int16 Short0;
            [FieldOffset(2)] public Int16 Short1;
            [FieldOffset(4)] public Int16 Short2;
            [FieldOffset(6)] public Int16 Short3;
        }

        public static long GetId4(int largeId, int x, int y, int z)
        {

            Mapper mapper = new Mapper()
            {
                Short0 = (Int16)z,
                Short1 = (Int16)y,
                Short2 = (Int16)x,
                Short3 = (Int16)largeId
            };

            return mapper.Combined;

        }

        private static Mapper _mapper = new Mapper();
        public static long GetId5(int largeId, int x, int y, int z)
        {

            _mapper.Short0 = (Int16)z;
            _mapper.Short1 = (Int16)y;
            _mapper.Short2 = (Int16)x;
            _mapper.Short3 = (Int16)largeId;

            return _mapper.Combined;
        }

        [StructLayout(LayoutKind.Explicit)]
        public struct Mapper2
        {
            [FieldOffset(0)] public Int64 Combined;
            [FieldOffset(0)] public Int32 Integer0;
            [FieldOffset(4)] public Int32 Integer1;
        }

        private static Mapper2 _mapper2 = new Mapper2();
        public static long GetId6(int largeId, int x, int y, int z)
        {

            _mapper2.Integer0 = y << 16 | z;   //dangerous because we aren't checking upper bits of z
            _mapper2.Integer1 = largeId << 16 | x; //dangerous because we aren't checking upper bits of x

            return _mapper2.Combined;
        }
</code>```

Results:

```<code>GetId1 = 2168ms
GetId2 = 1824ms
GetId3 = 1679ms
GetId4 = 2217ms
GetId5 = 2008ms
GetId6 = 1757ms
GetCoord1 = 785ms
GetCoord2 = 865ms
Routine1: 71776849217913036   binary: 11111111000000001010101000000000101110110000000011001100
Routine2: 71776849217913036   binary: 11111111000000001010101000000000101110110000000011001100
Routine3: 71776849217913036   binary: 11111111000000001010101000000000101110110000000011001100
Routine4: 71776849217913036   binary: 11111111000000001010101000000000101110110000000011001100
Routine5: 71776849217913036   binary: 11111111000000001010101000000000101110110000000011001100
Routine6: 71776849217913036   binary: 11111111000000001010101000000000101110110000000011001100
255, 170, 187, 204
255, 170, 187, 204
</code>```

Is there a better/faster way to encode the 4 integers into a 64 bit long?

(fyi...the BitConverter class is paralyzingly slow and was removed because it isn't feasible)

答:
5 days later and a question popped into my head while taking a shower...What if the time is being eaten up by moving the return value off the local stack into the calling procedure stack?  Turns out...it was.

The new method below takes the fastest method from above (method #3) and instead of returning the variable (which causes the "stack to stack" copy), I pass in a the return value as an "out" reference.  This allows the calculation to be performed directly into the resultant variable from the calling procedure.

Doing this...I can now encode faster than I can decode, which was the goal all along.  Below is the new routine and speed comparisons.

```<code>        public static void GetId7(int largeId, int x, int y, int z, out long id)
        {

            id = ((long)(largeId << 16 | x) << 32) | (y << 16 | z);

        }
</code>```

Speed comparisons.  GetId7 shows the new results:

```<code>GetId1 = 2282ms
GetId2 = 1910ms
GetId3 = 1782ms
GetId4 = 2306ms
GetId5 = 2092ms
GetId6 = 1816ms
GetId7 = 831ms
GetCoord1 = 828ms
GetCoord2 = 930ms
Routine1: 71776849217913036   binary: 11111111000000001010101000000000101110110000000011001100
Routine2: 71776849217913036   binary: 11111111000000001010101000000000101110110000000011001100
Routine3: 71776849217913036   binary: 11111111000000001010101000000000101110110000000011001100
Routine4: 71776849217913036   binary: 11111111000000001010101000000000101110110000000011001100
Routine5: 71776849217913036   binary: 11111111000000001010101000000000101110110000000011001100
Routine6: 71776849217913036   binary: 11111111000000001010101000000000101110110000000011001100
Routine7: 71776849217913036   binary: 11111111000000001010101000000000101110110000000011001100
255, 170, 187, 204
255, 170, 187, 204
</code>```

Not that it's needed, but I am curious if anyone can get it even faster.

Body:
Basically I'm trying to build a unique 64bit id from coordinates that I can then pull apart later on. These operations will be performed billions of times in short order, so speed is critical. Here is what I am after.  I have 4 - 32 bit integers but only the bottom 16 bits are relevant. I want to concatenate the bottom 16 bits into one 64 bit 'long' (doesn't matter if it's signed or not, since the bits are the same).  So if I have:

largeId = 0000 0000 0000 0000   0000 0000 1000 1000
x       = 0000 0000 0000 0000   0000 0000 1100 1100
y       = 0000 0000 0000 0000   0000 0000 1110 1110
z       = 0000 0000 0000 0000   0000 0000 1111 1111

it will become:

Id = 0000 0000 1000 1000   0000 0000 1100 1100   0000 0000 1110 1110   0000 0000 1111 1111

I've written a few routines that produce the desired results (i.e. builds and pulls apart) and have timed them using 500^3 iterations to try to find the fastest routine.  The routine that decodes the 64 bit number back into 4 int variables runs at about 43% of the time required to encode them.  How can I speed up the encoding??

Routines:  (updated with variations of Paul Smiths suggestions below)

        public static long GetCombinedId(int largeId, int x, int y, int z)
        {

            var _largeId = (long)largeId;
            var _x = (long)x;
            var _y = (long)y;
            var _z = (long)z;

            return (_largeId << 48) | (_x << 32) | (_y << 16) | _z;

        }

        public static long GetCombinedId2(int largeId, int x, int y, int z)
        {
            return ((long)largeId << 48) | ((long)x << 32) | ((long)y << 16) | (long)z;
        }

        public static long GetCombinedId3(int largeId, int x, int y, int z)
        {
            unchecked
            {
                return ((long)(largeId << 16 | x) << 32) | (y << 16 | z );
            }

        }

        public static void GetCoordinates(long id, out int largeId, out int x, out int y, out int z)
        {

            largeId = (int)(id >> 48);

            x = (int)((id >> 32) & 0x0000_0000_0000_FFFF);
            y = (int)((id >> 16) & 0x0000_0000_0000_FFFF);
            z = (int)(id & 0x0000_0000_0000_FFFF);

        }

        public static void GetCoordinates2(long id, out int largeId, out int x, out int y, out int z)
        {

            largeId = (int)(id >> 48);

            x = (int)((id << 16 ) >> 48);
            y = (int)((id << 32 ) >> 48);
            z = (int)((id << 48 ) >> 48);

        }

Variations of Paul Smith's technique described in answers section

  [StructLayout(LayoutKind.Explicit)]
        public struct Mapper
        {
            [FieldOffset(0)] public Int64 Combined;
            [FieldOffset(0)] public Int16 Short0;
            [FieldOffset(2)] public Int16 Short1;
            [FieldOffset(4)] public Int16 Short2;
            [FieldOffset(6)] public Int16 Short3;
        }

        public static long GetId4(int largeId, int x, int y, int z)
        {

            Mapper mapper = new Mapper()
            {
                Short0 = (Int16)z,
                Short1 = (Int16)y,
                Short2 = (Int16)x,
                Short3 = (Int16)largeId
            };

            return mapper.Combined;

        }

        private static Mapper _mapper = new Mapper();
        public static long GetId5(int largeId, int x, int y, int z)
        {

            _mapper.Short0 = (Int16)z;
            _mapper.Short1 = (Int16)y;
            _mapper.Short2 = (Int16)x;
            _mapper.Short3 = (Int16)largeId;

            return _mapper.Combined;
        }

        [StructLayout(LayoutKind.Explicit)]
        public struct Mapper2
        {
            [FieldOffset(0)] public Int64 Combined;
            [FieldOffset(0)] public Int32 Integer0;
            [FieldOffset(4)] public Int32 Integer1;
        }

        private static Mapper2 _mapper2 = new Mapper2();
        public static long GetId6(int largeId, int x, int y, int z)
        {

            _mapper2.Integer0 = y << 16 | z;   //dangerous because we aren't checking upper bits of z
            _mapper2.Integer1 = largeId << 16 | x; //dangerous because we aren't checking upper bits of x

            return _mapper2.Combined;
        }

Results:

GetId1 = 2168ms
GetId2 = 1824ms
GetId3 = 1679ms
GetId4 = 2217ms
GetId5 = 2008ms
GetId6 = 1757ms
GetCoord1 = 785ms
GetCoord2 = 865ms
Routine1: 71776849217913036   binary: 11111111000000001010101000000000101110110000000011001100
Routine2: 71776849217913036   binary: 11111111000000001010101000000000101110110000000011001100
Routine3: 71776849217913036   binary: 11111111000000001010101000000000101110110000000011001100
Routine4: 71776849217913036   binary: 11111111000000001010101000000000101110110000000011001100
Routine5: 71776849217913036   binary: 11111111000000001010101000000000101110110000000011001100
Routine6: 71776849217913036   binary: 11111111000000001010101000000000101110110000000011001100
255, 170, 187, 204
255, 170, 187, 204

Is there a better/faster way to encode the 4 integers into a 64 bit long?

(fyi...the BitConverter class is paralyzingly slow and was removed because it isn't feasible)

Body:
5 days later and a question popped into my head while taking a shower...What if the time is being eaten up by moving the return value off the local stack into the calling procedure stack?  Turns out...it was.

The new method below takes the fastest method from above (method #3) and instead of returning the variable (which causes the "stack to stack" copy), I pass in a the return value as an "out" reference.  This allows the calculation to be performed directly into the resultant variable from the calling procedure.

Doing this...I can now encode faster than I can decode, which was the goal all along.  Below is the new routine and speed comparisons.

        public static void GetId7(int largeId, int x, int y, int z, out long id)
        {

            id = ((long)(largeId << 16 | x) << 32) | (y << 16 | z);

        }

Speed comparisons.  GetId7 shows the new results:

GetId1 = 2282ms
GetId2 = 1910ms
GetId3 = 1782ms
GetId4 = 2306ms
GetId5 = 2092ms
GetId6 = 1816ms
GetId7 = 831ms
GetCoord1 = 828ms
GetCoord2 = 930ms
Routine1: 71776849217913036   binary: 11111111000000001010101000000000101110110000000011001100
Routine2: 71776849217913036   binary: 11111111000000001010101000000000101110110000000011001100
Routine3: 71776849217913036   binary: 11111111000000001010101000000000101110110000000011001100
Routine4: 71776849217913036   binary: 11111111000000001010101000000000101110110000000011001100
Routine5: 71776849217913036   binary: 11111111000000001010101000000000101110110000000011001100
Routine6: 71776849217913036   binary: 11111111000000001010101000000000101110110000000011001100
Routine7: 71776849217913036   binary: 11111111000000001010101000000000101110110000000011001100
255, 170, 187, 204
255, 170, 187, 204

Not that it's needed, but I am curious if anyone can get it even faster.


问:
How can I "visualize"(observe) a thread exiting in iOS?
When learning thread and run loop, I notice that some articles say: "Generally, a thread just exits once it has done its work." So there is necessity sometimes to create a so-called "immortal thread"(?? I don't know the exact term in English) using NSRunloop.

The question is HOW can I prove the statement "just exits once it has done its work"? I code like this

- (void)doSomethingOnThread {
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        NSLog(@"I'm on thread %@", [NSThread currentThread]);
//    });

    NSThread *thread1 = [[NSThread alloc] initWithBlock:^{
        NSLog(@"I'm on thread %@", [NSThread currentThread]);
    }];
    thread1.name = @"thread1";
    [thread1 start];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(threadExitHandler:) name:NSThreadWillExitNotification object:nil];
}

- (void)threadExitHandler:(NSNotification *)noti {
    NSLog(@"Thread will exit: %@", noti);
}
```

Well, the notification handler is not called.

So, [1]: How can I prove a thread exiting? [2]: What kinds of threads behave so?(I know the main thread will never exit, what about other thread? GCD threads, for example？)

答:
If you want to visualize it, I might use the debugger. For example, I've set a breakpoint inside a NSThread subclass and I see the thread listed in the left panel in Xcode:

But if I have another breakpoint triggered one second after the main method finishes, I see the relevant “Thread will exit” message and my thread is no longer present :

Or you could add a NSLog statement inside the dealloc method for your NSThread subclass, and that also would demonstrate its deallocation. Or look for the subclass in the debug memory object graph.

Well, the notification handler is not called.

I'd suggest you add your observer for NSThreadWillExitNotification before you start your thread. Right now you have a race condition between the starting and exiting of this thread and the adding of the observer. FWIW, I do see the “Thread will exit” message.

Unrelated, while it’s great to learn about threads and runloops, it has little practical use nowadays. It might be more useful to master GCD which gets us out of the weeds of threads and offers performance optimizations and a richer API for writing robust multi-threaded code.

In regards to whether GCD creates persistent threads or not, the answer is yes, but we're abstracted away from this detail. But one of GCD’s performance optimizations is that it manages a “pool” of threads for us, not constantly spinning up new threads and destroying them constantly for every dispatched block of code.

You might want to watch WWDC 2016’s Concurrent Programming With GCD in Swift 3. It walks through the relationship between queues, threads, and runloops.

Body:
When learning thread and run loop, I notice that some articles say: "Generally, a thread just exits once it has done its work." So there is necessity sometimes to create a so-called "immortal thread"(?? I don't know the exact term in English) using NSRunloop.

The question is HOW can I prove the statement "just exits once it has done its work"? I code like this

- (void)doSomethingOnThread {
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        NSLog(@"I'm on thread %@", [NSThread currentThread]);
//    });

    NSThread *thread1 = [[NSThread alloc] initWithBlock:^{
        NSLog(@"I'm on thread %@", [NSThread currentThread]);
    }];
    thread1.name = @"thread1";
    [thread1 start];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(threadExitHandler:) name:NSThreadWillExitNotification object:nil];
}

- (void)threadExitHandler:(NSNotification *)noti {
    NSLog(@"Thread will exit: %@", noti);
}

Well, the notification handler is not called.

So, [1]: How can I prove a thread exiting? [2]: What kinds of threads behave so?(I know the main thread will never exit, what about other thread? GCD threads, for example？)


问:
how to extract a column from a matrix in python without using any package
I want to find a sum of a column in a matrix without using any package.

```<code>a = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
</code>```

If I want to extract a row I can write a[i] for ith row, but how to extract a particular column?

答:
So you can get the ith row with a[i] and you can get the nth value from row i with a[i][n] now if you want the column as a whole you will want something like this:

```<code>def getColumn(data,col):
    return [k[col] for k in data]
</code>```

Body:
I want to find a sum of a column in a matrix without using any package.

a = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]

If I want to extract a row I can write a[i] for ith row, but how to extract a particular column?

Body:
So you can get the ith row with a[i] and you can get the nth value from row i with a[i][n] now if you want the column as a whole you will want something like this:

def getColumn(data,col):
    return [k[col] for k in data]


问:
WPF/XAML Style set Property for child items?
I working on a XAML style for my controls.
The code below is for setting the color of a stackpanel. It works fine but there is something else I want to do. If the trigger is activated I want to set the font color for all child items inside the stackpanel.

At the moment I only have textblocks inside the stackpanel and I know I could easily create a separate style for a textbock. But if this style is triggered it will only affect ONE and not ALL textblocks.
But I want to change all items inside the stackpanel as soon as I got a mouseover trigger for the panel.

Is this even possible in XAML or do I have to code a regular event?

```<code><Style x:Key="XStack" TargetType="StackPanel">
    <Setter Property="Background">
        <Setter.Value>
            <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                <GradientStop Color="White" Offset="0"/>
                <GradientStop Color="SkyBlue" Offset="6"/>
            </LinearGradientBrush>
        </Setter.Value>
    </Setter>
    <!-- Trigger-->
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True" >
            <Setter Property="Background" Value="SkyBlue"/>
        </Trigger>
    </Style.Triggers>
</Style>
</code>```

答:
Add this to your trigger:

<Setter Property="TextElement.Foreground" Value="Blue"></Setter>

OwnerDisplayName: Holli

Body:
I working on a XAML style for my controls.
The code below is for setting the color of a stackpanel. It works fine but there is something else I want to do. If the trigger is activated I want to set the font color for all child items inside the stackpanel.

At the moment I only have textblocks inside the stackpanel and I know I could easily create a separate style for a textbock. But if this style is triggered it will only affect ONE and not ALL textblocks.
But I want to change all items inside the stackpanel as soon as I got a mouseover trigger for the panel.

Is this even possible in XAML or do I have to code a regular event?

</Style>

LastEditorDisplayName: Drew Noakes

OwnerDisplayName: Olle


问:
remove validation on name in laravel 6 on creating new user
I want to remove validation on the name in laravel 6 on creating a new user. The user is created successfully but when I enter a name with space or capital letters, the login page opens up. But if I remove all spaces from the name everything works fine with the following code.

```<code>protected function validator(array $data)
{
    return Validator::make($data, [
        'name'     => ['required', 'string', 'max:255'],
        'email'    => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => ['required', 'string', 'min:8', 'confirmed'],
    ]);
}

protected function create(array $data)
{
    $username = slugify($data['name']) . "-" . mt_rand(10000, 99999);

    return User::create([
        'name'     => $data['name'],
        'username' => $username,
        'email'    => $data['email'],
        'password' => Hash::make($data['password']),
    ]);
}
</code>```

blade.php code

https://codeshare.io/5e1kX7

答:
I did it by adding regex in the validation</p>

```<code>'name' => ['required', 'string','regex:/^[\pL\s\-]+$/u', 'max:255'],
</code>```

Body:
I want to remove validation on the name in laravel 6 on creating a new user. The user is created successfully but when I enter a name with space or capital letters, the login page opens up. But if I remove all spaces from the name everything works fine with the following code.

protected function validator(array $data)
{
    return Validator::make($data, [
        'name'     => ['required', 'string', 'max:255'],
        'email'    => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => ['required', 'string', 'min:8', 'confirmed'],
    ]);
}

protected function create(array $data)
{
    $username = slugify($data['name']) . "-" . mt_rand(10000, 99999);

    return User::create([
        'name'     => $data['name'],
        'username' => $username,
        'email'    => $data['email'],
        'password' => Hash::make($data['password']),
    ]);
}

blade.php code

https://codeshare.io/5e1kX7

Body:
I did it by adding regex in the validation

'name' => ['required', 'string','regex:/^[\pL\s\-]+$/u', 'max:255'],


问:
How to implement an unordered data structure using set?
I want to build an unordered set for my Face structure, that is

```<code>class myFace
{
public:
    //the three points
    int u;
    int v;
    int k;
    myFace() = default;
    myFace(int u, int v, int k) : u(u), v(v), k(k) {}

    bool operator< (const myFace& e) const
    {
        bool result = true;
        min(u, v, k);
        if ((u == e.u && v == e.v && k == e.k) ||
            (u == e.u && v == e.k && k == e.v) ||
            (u == e.v && v == e.u && k == e.k) ||
            (u == e.v && v == e.k && k == e.u) ||
            (u == e.k && v == e.u && k == e.v) ||
            (u == e.k && v == e.v && k == e.u))
        {
            result = false;
        }
        return result;
    }
};
</code>```

I want to make sure that:

```<code>set<myFace> con;
myFace f1(1,2,3);
myFace f2(2,3,1);
myFace f3(3,1,2);

con.insert(f1);
con.insert(f2);
con.insert(f3);
cout << con.size() << endl;

</code>```

the output should be 1.
Since f1,f2,f3 are same.

Or we can just say how to implement a set for 3 unordered elements, that is 123,132,213,231,312,321 are all same.

答:
The secret is, to use the correct Comparator for your class and give it to the set. I used a similar approach for sets here.

I adapted this solution and created the below example code:

```<code>#include <iostream>
#include <set>
#include <vector>
#include <algorithm>

struct myFace
{
    //the three points
    int u;
    int v;
    int k;
    myFace() = default;
    myFace(int u, int v, int k) : u(u), v(v), k(k) {}
};

struct Comparator {
    bool operator () (const myFace& lhs, const myFace& rhs) const {
        // Convert the structs to vectors
        std::vector<int> v1 = { lhs.u, lhs.v, lhs.k };
        std::vector<int> v2 = { rhs.u, rhs.v, rhs.k };
        // Sort them
        std::sort(v1.begin(), v1.end());
        std::sort(v2.begin(), v2.end());
        // Compare them
        return v1 < v2;
    }
};

int main() {
    std::set<myFace, Comparator> con;

    myFace f1(1, 2, 3);
    myFace f2(2, 3, 1);
    myFace f3(3, 1, 2);

    con.insert(f1);
    con.insert(f2);
    con.insert(f3);

    std::cout << con.size() << std::endl;

    return 0;
}

</code>```

Body:
I want to build an unordered set for my Face structure, that is

class myFace
{
public:
    //the three points
    int u;
    int v;
    int k;
    myFace() = default;
    myFace(int u, int v, int k) : u(u), v(v), k(k) {}

    bool operator< (const myFace& e) const
    {
        bool result = true;
        min(u, v, k);
        if ((u == e.u && v == e.v && k == e.k) ||
            (u == e.u && v == e.k && k == e.v) ||
            (u == e.v && v == e.u && k == e.k) ||
            (u == e.v && v == e.k && k == e.u) ||
            (u == e.k && v == e.u && k == e.v) ||
            (u == e.k && v == e.v && k == e.u))
        {
            result = false;
        }
        return result;
    }
};

I want to make sure that:

set<myFace> con;
myFace f1(1,2,3);
myFace f2(2,3,1);
myFace f3(3,1,2);

con.insert(f1);
con.insert(f2);
con.insert(f3);
cout << con.size() << endl;

the output should be 1.
Since f1,f2,f3 are same.

Or we can just say how to implement a set for 3 unordered elements, that is 123,132,213,231,312,321 are all same.

Body:
The secret is, to use the correct Comparator for your class and give it to the set. I used a similar approach for sets here.

I adapted this solution and created the below example code:

#include <iostream>
#include <set>
#include <vector>
#include <algorithm>

struct myFace
{
    //the three points
    int u;
    int v;
    int k;
    myFace() = default;
    myFace(int u, int v, int k) : u(u), v(v), k(k) {}
};

struct Comparator {
    bool operator () (const myFace& lhs, const myFace& rhs) const {
        // Convert the structs to vectors
        std::vector<int> v1 = { lhs.u, lhs.v, lhs.k };
        std::vector<int> v2 = { rhs.u, rhs.v, rhs.k };
        // Sort them
        std::sort(v1.begin(), v1.end());
        std::sort(v2.begin(), v2.end());
        // Compare them
        return v1 < v2;
    }
};

int main() {
    std::set<myFace, Comparator> con;

    myFace f1(1, 2, 3);
    myFace f2(2, 3, 1);
    myFace f3(3, 1, 2);

    con.insert(f1);
    con.insert(f2);
    con.insert(f3);

    std::cout << con.size() << std::endl;

    return 0;
}


问:
Laravel 6 Artisan make traits custom command not working
I want to make a trait using php artisan command but have no idea why it is not working.

app/Console/Stubs/trait.stub

```<code>namespace App\Traits;

trait DummyTrait
{

}
</code>```

app/Console/Commands/TraitMakeCommand.php

```<code>namespace App\Console\Commands;

use Illuminate\Console\Command;
use function app_path;

class TraitMakeCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'make:trait {name : Traits name you want to use.}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new trait';

    /**
     * The type of class being generated.
     *
     * @var string
     */
    protected $type = 'Trait';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        return $this->getStub();
    }

    /**
     * Get the stub file for the generator.
     *
     * @return string
     */
    protected function getStub()
    {
        return app_path('Console/Stubs/trait.stub');
    }

    /**
     * Get the default namespace for the class.
     *
     * @param string $rootNamespace
     *
     * @return string
     */
    protected function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace . '\Traits';
    }
}
</code>```

app/Console/Kernel.php

```<code>class Kernel extends ConsoleKernel
{

    ...

    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        Commands\TraitMakeCommand::class,
    ];

    ...
}
</code>```

Artisan output for: pa make:trait -h

```<code>Description:
  Create a new trait

Usage:
  make:trait <name>

Arguments:
  name                  Traits name you want to use.

Options:
  -h, --help            Display this help message
  -q, --quiet           Do not output any message
  -V, --version         Display this application version
      --ansi            Force ANSI output
      --no-ansi         Disable ANSI output
  -n, --no-interaction  Do not ask any interactive question
      --env[=ENV]       The environment the command should run under
  -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
</code>```

答:
You can use the GeneratorCommand to generate files for stubs. This base class implements most of the logic. All the custom settings can be achieved by overriding some methods. Checkout the example below:

app/Console/Commands/TraitMakeCommand.php

```<code>namespace App\Console\Commands;

use Illuminate\Console\GeneratorCommand;

class TraitMakeCommand extends GeneratorCommand
{
    protected $name = 'make:trait';
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new trait';
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'make:trait {name : Traits name you want to use.}';

    /**
     * The type of class being generated.
     *
     * @var string
     */
    protected $type = 'Trait';

    /**
     * Get the stub file for the generator.
     *
     * @return string
     */
    protected function getStub()
    {
        return app_path('Console/Stubs/trait.stub');
    }

    /**
     * Get the default namespace for the class.
     *
     * @param string $rootNamespace
     *
     * @return string
     */
    protected function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace . '\Traits';
    }
}
</code>```

and update the stub:

app\Console\Stubs\trait.stub

```<code><?php

namespace App\Traits;

trait DummyClass
{

}
</code>```

and then the usage would be:

```<code>php artisan make:trait Example
</code>```

which would result in the file: app/Traits/Example.php with the following content:

```<code><?php

namespace App\Traits;

trait Example
{

}
</code>```

Body:
I want to make a trait using php artisan command but have no idea why it is not working.

app/Console/Stubs/trait.stub

namespace App\Traits;

trait DummyTrait
{

}

app/Console/Commands/TraitMakeCommand.php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use function app_path;

class TraitMakeCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'make:trait {name : Traits name you want to use.}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new trait';

    /**
     * The type of class being generated.
     *
     * @var string
     */
    protected $type = 'Trait';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        return $this->getStub();
    }

    /**
     * Get the stub file for the generator.
     *
     * @return string
     */
    protected function getStub()
    {
        return app_path('Console/Stubs/trait.stub');
    }

    /**
     * Get the default namespace for the class.
     *
     * @param string $rootNamespace
     *
     * @return string
     */
    protected function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace . '\Traits';
    }
}

app/Console/Kernel.php

class Kernel extends ConsoleKernel
{

    ...

    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        Commands\TraitMakeCommand::class,
    ];

    ...
}

Artisan output for: pa make:trait -h

Description:
  Create a new trait

Usage:
  make:trait <name>

Arguments:
  name                  Traits name you want to use.

Options:
  -h, --help            Display this help message
  -q, --quiet           Do not output any message
  -V, --version         Display this application version
      --ansi            Force ANSI output
      --no-ansi         Disable ANSI output
  -n, --no-interaction  Do not ask any interactive question
      --env[=ENV]       The environment the command should run under
  -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Body:
You can use the GeneratorCommand to generate files for stubs. This base class implements most of the logic. All the custom settings can be achieved by overriding some methods. Checkout the example below:

app/Console/Commands/TraitMakeCommand.php

namespace App\Console\Commands;

use Illuminate\Console\GeneratorCommand;

class TraitMakeCommand extends GeneratorCommand
{
    protected $name = 'make:trait';
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new trait';
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'make:trait {name : Traits name you want to use.}';

    /**
     * The type of class being generated.
     *
     * @var string
     */
    protected $type = 'Trait';

    /**
     * Get the stub file for the generator.
     *
     * @return string
     */
    protected function getStub()
    {
        return app_path('Console/Stubs/trait.stub');
    }

    /**
     * Get the default namespace for the class.
     *
     * @param string $rootNamespace
     *
     * @return string
     */
    protected function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace . '\Traits';
    }
}

and update the stub:

app\Console\Stubs\trait.stub

<?php

namespace App\Traits;

trait DummyClass
{

}

and then the usage would be:

php artisan make:trait Example

which would result in the file: app/Traits/Example.php with the following content:

<?php

namespace App\Traits;

trait Example
{

}