问:
How to use SSL certificate in java http client to make request to server
I have a .crt file provided by some thirdparty. Now i have to call their API over TLS. Can someone tell me how to use this .crt in java code to make secure call. I am using windows machine and java 8</p>

答:
You can't. You need a key pair, produced by you, and a certificate, signed either by a third party in response to a CSR generated by you, or a self-signed certificate generated by you that the server trusts.

Or else you don't need the certificate at all, unless it is untrusted, which you don't state.


来源: stackexchange

问:
What is the better way of including a header file? #include<> followed by #include"" or the otherwise?

Possible Duplicates:

  what is the difference between #include <filename> and #include “filename”

  C/C++ include file order/best practices

In what order should the include statements in a header file and source file come in C++? #include <> followed by #include "" or the otherwise?

Also, should the header file of a source file precede all include statements in source file?

答:
I prefer to include in this order:

Standard libraries first.

Then third-party libraries.

Lastly, headers that I have written myself.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


问:
Appending columns to make a custom matrix
I am trying to make a matrix from a single column of values. Could you please give me an easy way to make it? Thanks in advance.
The first column is the original data. Here it goes. I want the yellow colored matrix

enter image description here

答:
Seems the images you provided earlier are now gone. If I remember them correctly you could try the following code.</p>

```<code>import numpy as np
i = [1,2,3,4,5]
i.reverse()
result=np.array([[g+x for g in i] for x in range(5)])
</code>```

Body:
Seems the images you provided earlier are now gone. If I remember them correctly you could try the following code.

import numpy as np
i = [1,2,3,4,5]
i.reverse()
result=np.array([[g+x for g in i] for x in range(5)])


问:
Querying on multiple LINKMAP items with OrientDB SQL
I have a class that contains a LINKMAP field called links. This class is used recursively to create arbitrary hierarchical groupings (something like the time-series example, but not with the fixed year/month/day structure).

A query like this:

```<code>select expand(links['2017'].links['07'].links['15'].links['10'].links) from data where key='AAA'
</code>```

Returns the actual records contained in the last layer of "links". This works exactly as expected.

But a query like this (note the 10,11 in the second to last layer of "links"):

```<code>select expand(links['2017'].links['07'].links['15'].links['10','11'].links) from data where key='AAA'
</code>```

Returns two rows of the last layer of "links" instead:

{"1000":"#23:0","1001":"#24:0","1002":"#23:1"}
{"1003":"#24:1","1004":"#23:2"}

Using unionAll or intersect (with or without UNWIND) results in this single record:

[{"1000":"#23:0","1001":"#24:0","1002":"#23:1"},{"1003":"#24:1","1004":"#23:2"}]

But nothing I've tried (including various attempts at "compound" SELECTs) will get the expand to work as it does with the original example (i.e. return the actual records represented in the last LINKMAP).

Is there a SQL syntax that will achieve this?

Note: Even this (slightly modified) example from the ODB docs does not result in a list of linked records:

```<code>select expand(records) from
(select unionAll(years['2017'].links['07'].links['15'].links['10'].links, years['2017'].links['07'].links['15'].links['11'].links) as records from data where key='AAA')
</code>```

Ref: https://orientdb.com/docs/2.2/Time-series-use-case.html

答:
I'm not sure of what you want to achieve, but I think it's worth trying with values():

```<code> select expand(links['2017'].links['07'].links['15'].links['10','11'].links.values()) from data where key='AAA'
</code>```

Body:
I have a class that contains a LINKMAP field called links. This class is used recursively to create arbitrary hierarchical groupings (something like the time-series example, but not with the fixed year/month/day structure).

A query like this:

select expand(links['2017'].links['07'].links['15'].links['10'].links) from data where key='AAA'

Returns the actual records contained in the last layer of "links". This works exactly as expected.

But a query like this (note the 10,11 in the second to last layer of "links"):

select expand(links['2017'].links['07'].links['15'].links['10','11'].links) from data where key='AAA'

Returns two rows of the last layer of "links" instead:

{"1000":"#23:0","1001":"#24:0","1002":"#23:1"}
{"1003":"#24:1","1004":"#23:2"}

Using unionAll or intersect (with or without UNWIND) results in this single record:

[{"1000":"#23:0","1001":"#24:0","1002":"#23:1"},{"1003":"#24:1","1004":"#23:2"}]

But nothing I've tried (including various attempts at "compound" SELECTs) will get the expand to work as it does with the original example (i.e. return the actual records represented in the last LINKMAP).

Is there a SQL syntax that will achieve this?

Note: Even this (slightly modified) example from the ODB docs does not result in a list of linked records:

select expand(records) from
(select unionAll(years['2017'].links['07'].links['15'].links['10'].links, years['2017'].links['07'].links['15'].links['11'].links) as records from data where key='AAA')

Ref: https://orientdb.com/docs/2.2/Time-series-use-case.html

Body:
I'm not sure of what you want to achieve, but I think it's worth trying with values():

 select expand(links['2017'].links['07'].links['15'].links['10','11'].links.values()) from data where key='AAA'


问:
MySQL Error #1071 - Specified key was too long; max key length is 767 bytes
When I executed the following command:

```<code>ALTER TABLE `mytable` ADD UNIQUE (
`column1` ,
`column2`
);
</code>```

I got this error message:

```<code>#1071 - Specified key was too long; max key length is 767 bytes
</code>```

Information about column1 and column2:

```<code>column1 varchar(20) utf8_general_ci
column2  varchar(500) utf8_general_ci
</code>```

I think varchar(20) only requires 21 bytes while varchar(500) only requires 501 bytes. So the total bytes are 522, less than 767. So why did I get the error message?

```<code>#1071 - Specified key was too long; max key length is 767 bytes
</code>```

答:
I found this query useful for detecting which columns had an index violating the max key length:</p>
```<code>SELECT
  c.TABLE_NAME As TableName,
  c.COLUMN_NAME AS ColumnName,
  c.DATA_TYPE AS DataType,
  c.CHARACTER_MAXIMUM_LENGTH AS ColumnLength,
  s.INDEX_NAME AS IndexName
FROM information_schema.COLUMNS AS c
INNER JOIN information_schema.statistics AS s
  ON s.table_name = c.TABLE_NAME
 AND s.COLUMN_NAME = c.COLUMN_NAME
WHERE c.TABLE_SCHEMA = DATABASE()
  AND c.CHARACTER_MAXIMUM_LENGTH > 191
  AND c.DATA_TYPE IN ('char', 'varchar', 'text')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When I executed the following command:

ALTER TABLE `mytable` ADD UNIQUE (
`column1` ,
`column2`
);

I got this error message:

#1071 - Specified key was too long; max key length is 767 bytes

Information about column1 and column2:

column1 varchar(20) utf8_general_ci
column2  varchar(500) utf8_general_ci

I think varchar(20) only requires 21 bytes while varchar(500) only requires 501 bytes. So the total bytes are 522, less than 767. So why did I get the error message?

#1071 - Specified key was too long; max key length is 767 bytes

Body:
I found this query useful for detecting which columns had an index violating the max key length:

SELECT
  c.TABLE_NAME As TableName,
  c.COLUMN_NAME AS ColumnName,
  c.DATA_TYPE AS DataType,
  c.CHARACTER_MAXIMUM_LENGTH AS ColumnLength,
  s.INDEX_NAME AS IndexName
FROM information_schema.COLUMNS AS c
INNER JOIN information_schema.statistics AS s
  ON s.table_name = c.TABLE_NAME
 AND s.COLUMN_NAME = c.COLUMN_NAME
WHERE c.TABLE_SCHEMA = DATABASE()
  AND c.CHARACTER_MAXIMUM_LENGTH > 191
  AND c.DATA_TYPE IN ('char', 'varchar', 'text')


问:
how to add system.diagnostics.process to bot framework
I am new for microsoft botframework, I have to redirect to google page and search for specific user input keyword. I used some vbscript for this google process and calling the file from c# process code like this.

```<code>public virtual async Task message2(IDialogContext context,IAwaitable<IMessageActivity> argument)
    {
          ProcessStartInfo ps = new ProcessStartInfo();
            ps.FileName = "cscript.exe";
            ps.Arguments = string.Format("\"{0}\" \"{1}\" , @"D:\democtrl.vbs","" );
            var process = Process.Start(ps);
            process.WaitForExit();
            process.Close();
            await context.PostAsync("Submitted Successfully");
            context.Wait(MessageReceivedAsync);
</code>```

}`

I am running the vbscript file from local machine. when I do it in emulator I can able to run the file. But after publishing to azure it was not working.. do anyone suggest me or help me with any documents to do this.

答:
Ya using button I can open the url but i have to enter user input in the google search box and also click on search button, How do i achieve that using c#?

Based on my understanding for your question, you want to use user's input for google search.

If so, to invoke google search in your Bot, a simple way is to configure google application and customize your search API. On Bot side, we can send Http request and get response for example like this:

```<code>private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> argument)
{
    var activity = await argument;
    if (activity.Text != "")
    {
        var input = activity.Text;
        string url = "http://example.com/search?q={input}"
        var request = WebRequest.Create("url");
        var response = await request.GetResponseAsync();
        //TODO:
    }
    context.Wait(MessageReceivedAsync);
}
</code>```

For the part of google search api, you may refer to Using REST to Invoke the API.

If I have any misunderstanding, please feel free to let me know.

Body:
I am new for microsoft botframework, I have to redirect to google page and search for specific user input keyword. I used some vbscript for this google process and calling the file from c# process code like this.

public virtual async Task message2(IDialogContext context,IAwaitable<IMessageActivity> argument)
    {
          ProcessStartInfo ps = new ProcessStartInfo();
            ps.FileName = "cscript.exe";
            ps.Arguments = string.Format("\"{0}\" \"{1}\" , @"D:\democtrl.vbs","" );
            var process = Process.Start(ps);
            process.WaitForExit();
            process.Close();
            await context.PostAsync("Submitted Successfully");
            context.Wait(MessageReceivedAsync);

}`

I am running the vbscript file from local machine. when I do it in emulator I can able to run the file. But after publishing to azure it was not working.. do anyone suggest me or help me with any documents to do this.

Body:
Ya using button I can open the url but i have to enter user input in the google search box and also click on search button, How do i achieve that using c#?

Based on my understanding for your question, you want to use user's input for google search.

If so, to invoke google search in your Bot, a simple way is to configure google application and customize your search API. On Bot side, we can send Http request and get response for example like this:

private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> argument)
{
    var activity = await argument;
    if (activity.Text != "")
    {
        var input = activity.Text;
        string url = "http://example.com/search?q={input}"
        var request = WebRequest.Create("url");
        var response = await request.GetResponseAsync();
        //TODO:
    }
    context.Wait(MessageReceivedAsync);
}

For the part of google search api, you may refer to Using REST to Invoke the API.

If I have any misunderstanding, please feel free to let me know.


问:
Nth max salary in Oracle
To find out the Nth max sal in oracle i'm using below query

```<code>SELECT DISTINCE sal
FROM emp a
WHERE (
       SELECT COUNT(DISTINCE sal)
       FROM emp b
       WHERE a.sal<=b.sal)=&n;
</code>```

But According to me by using the above query it will take more time to execute if table size is big.

i'm trying to use the below query

```<code>SELECT sal
FROM (
      SELECT DISTINCE sal
      FROM emp
           ORDER BY sal DESC )
WHERE rownum=3;
</code>```

but not getting output.. any suggetions please .. Please share any link on how to optimise queries and decrease the time for a query to execute.

答:
This will also work :</p>

```<code>with data as
(
select sal,rwid from (
select salary as sal,rowid as rwid from salary order by salary desc
)
where rownum < 5
)
select * from salary a
where rowid = (select min(rwid) from data)
</code>```

Title: Nth max salary in Oracle

Body:
To find out the Nth max sal in oracle i'm using below query

SELECT DISTINCE sal
FROM emp a
WHERE (
       SELECT COUNT(DISTINCE sal)
       FROM emp b
       WHERE a.sal<=b.sal)=&n;

But According to me by using the above query it will take more time to execute if table size is big.

i'm trying to use the below query

SELECT sal
FROM (
      SELECT DISTINCE sal
      FROM emp
           ORDER BY sal DESC )
WHERE rownum=3;

but not getting output.. any suggetions please .. Please share any link on how to optimise queries and decrease the time for a query to execute.

Body:
This will also work :

with data as
(
select sal,rwid from (
select salary as sal,rowid as rwid from salary order by salary desc
)
where rownum < 5
)
select * from salary a
where rowid = (select min(rwid) from data)


问:
Selecting arrays with specific element values
This is driving me nuts, I've been trying to figure out how to do this one thing for hours now.

What I want to do is select all array items that have a specific value. This is easiest to explain by example:

I have an array, called media[]. It holds ALL of the media in my media gallery. It has two properties of note: path and gallery, or media[x][0] and media[x][1].

I want to select all media objects that belong in a certain gallery, and then add them to that gallery. That's where I'm struggling and it's driving me mad.

Here are my fumbled attempts at trying to do this... this is some seriously messy code (and mostly pointless), I'm just providing it so you can get a sense of how clueless I am about this. Please note that NONE of the code I have right now actually tries to do anything; everything I've done so far ends up as a broken for or while loop that either does nothing or crashes Chrome.

```<code>// this function is meant to return an array of all media items
// that belong in a certain gallery... didn't get that far because
// the loops tripped me up
function getTheMedia (galNum) {
    var output = [];
    for (var i = 0; i < media.length; ++i) {
        // I tried using an if statement here to check if the
        // media[i][1] == galNum, and if so, add it to the output
        // but that didn't work
        output.push(media[i]);
    }
    return output;
}

// this function was actually my first attempt but I kept running into
// the same issue as above
function fillGal () {
    /*
    var output = [];
    for (var i = 0; i < Gallery.length; ++i) {
        output.push(Gallery[i]);
    }
    */
    var output = [];
    var i = 0;
    while (i < media.length) {
        output.push(i);
        i++;
    }
    console.log(output);
}
</code>```

Seeing as I'm kind of burnt out and frustrating with running in circles (...loops? aha...), all I'm really looking for is a way to select only those specific array items as specified above. Everything else (adding them to the Gallery, etc) I can figure out myself.

Otherwise I'm just going to have to go back to the old way: define separate media[]arrays for each "gallery" (mediaThisGallery, mediaThatGallery, etc), and then combine them all at the end to get "allMedia". Only reason I don't want to do that is because I want to be able to change which gallery a media item belongs to... this HAS to be possible, right?

Thanks in advance! Sorry for the scatter-brainedness. I also apologize if the title is a bit off.

EDIT:

```<code>var media = [];

media[0] = ['0.png', 0, 'index'];
media[1] = ['0.png', 0];

media[2] = ['new/316.png', 1, "316"];
media[3] = ['new/kitties.jpg', 1, "D'aww kitties!!"];
media[4] = ['new/home.jpg', 1, "\"I'm Going Home\""];
media[5] = ['new/3.mp4', 1, "Crucible Carnage"];
media[6] = ['new/942.jpg', 1, "this is straight for testing purposes like omg long ass title lol"];
media[7] = ['new/boom.mp4', 1, "Maximum Efficiency"];
media[8] = ['new/42.jpg', 1, "Moo"];

// this is only included as a quick fix so my working code doesn't break
// as my "production" code is using multiple arrays; Media is used
// to store only the selected array (current Gallery)
// in other words, ignore this
var Media = [];
Media = media;

var Gallery = [];
Gallery[0] = [mediaRoot, "index", media ];
Gallery[1] = [mediaRoot, "new", Media ];
</code>```

It's pretty arbitrary atm.

Note that the main reason I'm converting from multiple arrays to a single array is that eventually, I plan to expand this app and I thought it made more sense to store ALL media in a single "database".

答:
Try this implementation of your getTheMedia function

```<code>function getTheMedia (galNum) {
    return media.filter(function(item){return item && item[1] === galNum;});
}
</code>```

You may test it like this:

```<code>console.log('gal 0');
console.log(getTheMedia(0));
console.log('gal 1');
console.log(getTheMedia(1));
</code>```

Body:
This is driving me nuts, I've been trying to figure out how to do this one thing for hours now.

What I want to do is select all array items that have a specific value. This is easiest to explain by example:

I have an array, called media[]. It holds ALL of the media in my media gallery. It has two properties of note: path and gallery, or media[x][0] and media[x][1].

I want to select all media objects that belong in a certain gallery, and then add them to that gallery. That's where I'm struggling and it's driving me mad.

Here are my fumbled attempts at trying to do this... this is some seriously messy code (and mostly pointless), I'm just providing it so you can get a sense of how clueless I am about this. Please note that NONE of the code I have right now actually tries to do anything; everything I've done so far ends up as a broken for or while loop that either does nothing or crashes Chrome.

// this function is meant to return an array of all media items
// that belong in a certain gallery... didn't get that far because
// the loops tripped me up
function getTheMedia (galNum) {
    var output = [];
    for (var i = 0; i < media.length; ++i) {
        // I tried using an if statement here to check if the
        // media[i][1] == galNum, and if so, add it to the output
        // but that didn't work
        output.push(media[i]);
    }
    return output;
}

// this function was actually my first attempt but I kept running into
// the same issue as above
function fillGal () {
    /*
    var output = [];
    for (var i = 0; i < Gallery.length; ++i) {
        output.push(Gallery[i]);
    }
    */
    var output = [];
    var i = 0;
    while (i < media.length) {
        output.push(i);
        i++;
    }
    console.log(output);
}

Seeing as I'm kind of burnt out and frustrating with running in circles (...loops? aha...), all I'm really looking for is a way to select only those specific array items as specified above. Everything else (adding them to the Gallery, etc) I can figure out myself.

Otherwise I'm just going to have to go back to the old way: define separate media[]arrays for each "gallery" (mediaThisGallery, mediaThatGallery, etc), and then combine them all at the end to get "allMedia". Only reason I don't want to do that is because I want to be able to change which gallery a media item belongs to... this HAS to be possible, right?

Thanks in advance! Sorry for the scatter-brainedness. I also apologize if the title is a bit off.

EDIT:

var media = [];

media[0] = ['0.png', 0, 'index'];
media[1] = ['0.png', 0];

media[2] = ['new/316.png', 1, "316"];
media[3] = ['new/kitties.jpg', 1, "D'aww kitties!!"];
media[4] = ['new/home.jpg', 1, "\"I'm Going Home\""];
media[5] = ['new/3.mp4', 1, "Crucible Carnage"];
media[6] = ['new/942.jpg', 1, "this is straight for testing purposes like omg long ass title lol"];
media[7] = ['new/boom.mp4', 1, "Maximum Efficiency"];
media[8] = ['new/42.jpg', 1, "Moo"];

// this is only included as a quick fix so my working code doesn't break
// as my "production" code is using multiple arrays; Media is used
// to store only the selected array (current Gallery)
// in other words, ignore this
var Media = [];
Media = media;

var Gallery = [];
Gallery[0] = [mediaRoot, "index", media ];
Gallery[1] = [mediaRoot, "new", Media ];

It's pretty arbitrary atm.

Note that the main reason I'm converting from multiple arrays to a single array is that eventually, I plan to expand this app and I thought it made more sense to store ALL media in a single "database".

Body:
Try this implementation of your getTheMedia function

function getTheMedia (galNum) {
    return media.filter(function(item){return item && item[1] === galNum;});
}

You may test it like this:

console.log('gal 0');
console.log(getTheMedia(0));
console.log('gal 1');
console.log(getTheMedia(1));


答: This matters about as much as whether you put opening curly braces on their own line. I would suggest that you pick whichever one you like better, and be consistent.</p>

Title: What is the better way of including a header file? #include<> followed by #include"" or the otherwise?

Body:
Possible Duplicates:

  what is the difference between #include <filename> and #include “filename”

  C/C++ include file order/best practices

In what order should the include statements in a header file and source file come in C++? #include <> followed by #include "" or the otherwise?

Also, should the header file of a source file precede all include statements in source file?


问:
How to get unique values in List
I have 2 text files with data. I am reading these files with BufferReader and putting the data of one column per file in a List<String>.

I have duplicated data in each one, but I need to have unique data in the first List to confront with the duplicated data in the second List.

How can I get unique values from a List?

答:
In Java 8:

```<code>     // List with duplicates
     List<String> listAll = Arrays.asList("A", "A", "B", "C", "D", "D");

     // filter the distinct
     List<String> distinctList = listAll.stream()
                     .distinct()
                     .collect(Collectors.toList());

    System.out.println(distinctList);// prints out: [A, B, C, D]
</code>```

this will also work with objects, but you will probably have to adapt your equals method.

Title: How to get unique values in List

Body:
In Java 8:

     // List with duplicates
     List<String> listAll = Arrays.asList("A", "A", "B", "C", "D", "D");

     // filter the distinct
     List<String> distinctList = listAll.stream()
                     .distinct()
                     .collect(Collectors.toList());

    System.out.println(distinctList);// prints out: [A, B, C, D]

this will also work with objects, but you will probably have to adapt your equals method.


问:
Facebook App Invites is deprecated
As the latest release of Facebook SDK version 4.28.0 - November 7, 2017, App Invites is deprecated.
https://developers.facebook.com/docs/app-invites/android/

With the release of the Facebook SDK version 4.28.0, App Invites is
  deprecated. It will be supported until February 5, 2018.

It makes the AppInviteDialog not working as expected (show white screen instead of list friends - Facebook app is not installed in the device), even I decreased Facebook SDK version to 4.27.0 or lower).
I tried to find out more information at offical docs but no luck.
Anyone have a solution for this trouble ?

答:
I was just trying to add invites for the first time and struggled for a long time until I realized that I need to do the following:

1 - Use Game Requests ( i.e. apprequests)

2 - Enable "Deep Linking" in Basic Settings page on Facebook developer portal for each platform, you won't see the option unless you also enable "Single Sign On".

Now the notifications open directly into app store if app not installed or into the game directly if it is installed.

The great thing is you don't need an App Link!!

Title: Facebook App Invites is deprecated


问:
How to iterate a child object angular 4?
Already have a service that passes objects to the DOM.

```<code>@Injectable()
export class DbService {
    db:Database[] = [
        {
        "id":0,
        "img":"../../../assets/img/logo/gro.png",
        "name":"Company,
        "type":"company type",
        "hours": "9:00AM-9:00PM",
        "number": 9999999,
        "email": 'info@company.com',
        "items": [
                    {'Beverage':['Bigga', 'Soda', 'Wata', 'Sprite']},
                    {'Canned':['Mackerel', 'Corn Beef', 'Tuna']}

                ]
        }...
</code>```

Made it iterate here...

```<code>        <div class="storeDoor col-md-4 " *ngFor="let butt of db" [routerLink]="['/store', butt.name]">
            <div class="row">
                <div class="col-md-5">
                    <img src="{{butt.img}}" width="70%">
                </div>
                <div class="col-md-7">
                   <h3 class=" ">
                      {{butt.name}}
                   </h3>
                   <h6>
                      {{butt.type}}
                   </h6>
               </div>
            </div>
        </div>
</code>```

And this opened the store front dynamically ...

```<code>                <div class="">
                        <h2 id="name" class="">{{store[0].name}}</h2>
                        <p style="color:grey; font-size: 16px"> Open Hours: {{store[0].hours}}</p>
                        <hr>

                </div>
                <div class="info">
                    <h5 class="badge badge-info">10/10</h5>
                    <h5>999 rating</h5>
                    <h5><i class="fa fa-phone fa-lg"></i> {{store[0].number}}</h5>
                    <h5>{{store[0].email}}</h5>

                    <button class="btn">Create Group Order</button>
                </div>
</code>```

But now while the store is open, I am lost in how to iterate the items object, displaying only the  key of the child object (Beverage, Canned)...

```<code>    <div class="aisle" >
        <a class="w3-bar-item" href="#" ></a>

    </div>
</code>```

答:
In your component

```<code>objectKeys = Object.keys;
</code>```

Then in html

```<code>  <div *ngFor="let item of store[0].items">
   <div *ngFor="let key of objectKeys (item)">Key : {{key}} Value: {{item[key]}}</div>
  </div>
</code>```

Body:
Already have a service that passes objects to the DOM.

@Injectable()
export class DbService {
    db:Database[] = [
        {
        "id":0,
        "img":"../../../assets/img/logo/gro.png",
        "name":"Company,
        "type":"company type",
        "hours": "9:00AM-9:00PM",
        "number": 9999999,
        "email": 'info@company.com',
        "items": [
                    {'Beverage':['Bigga', 'Soda', 'Wata', 'Sprite']},
                    {'Canned':['Mackerel', 'Corn Beef', 'Tuna']}

                ]
        }...

Made it iterate here...

                      {{butt.name}}

                      {{butt.type}}

And this opened the store front dynamically ...

{{store[0].name}}

 Open Hours: {{store[0].hours}}

10/10

999 rating

 {{store[0].number}}

{{store[0].email}}

                    <button class="btn">Create Group Order</button>

But now while the store is open, I am lost in how to iterate the items object, displaying only the  key of the child object (Beverage, Canned)...

Body:
In your component

objectKeys = Object.keys;

Then in html

  <div *ngFor="let item of store[0].items">
   <div *ngFor="let key of objectKeys (item)">Key : {{key}} Value: {{item[key]}}</div>
  </div>


问:
R: how to install from internet repos the dependencies of a package we install from local folder
I have developped a R package and added some dependant CRAN package in the description file.
I then install it using install.packages

Is there a way to ensure that its dependencies are fetched at this moment from internet?

答:
In your DESCRIPTION file you  should add the lines:

```<code>Depends:
   package1 (>= 1.0.1),
   package2
</code>```

The (>= 1.0.1) is for specifying minimal version.

More infos here: http://r-pkgs.had.co.nz/description.html

Body:
In your DESCRIPTION file you  should add the lines:

Depends:
   package1 (>= 1.0.1),
   package2

The (>= 1.0.1) is for specifying minimal version.

More infos here: http://r-pkgs.had.co.nz/description.html


问:
MySQL - How to change value in column?
I have a OpenCart store with more than 23000 products and I need to change one option (Requeres Shipping) for all of my products. I need to change that option in my database. I have a table n0v_product with with column shipping with value 0. I need to change shipping value to 1 for all products. How to update the value in the column with phpMyAdmin?

答:
You can use a UPDATE command to change all values on column shipping to 1 on n0v_product:

```<code>UPDATE `n0v_product` SET `shipping` = 1
</code>```

If you only want to set the value if shipping is 0 you can use the following:

```<code>UPDATE `n0v_product` SET `shipping` = 1 WHERE `shipping` = 0
</code>```

You should check the rows before UPDATE to make sure you really want to UPDATE these rows:

```<code>-- all rows of table n0v_product
SELECT `shipping`, * FROM `n0v_product`

-- only rows with shipping = 0
SELECT `shipping`, * FROM `n0v_product` WHERE `shipping` = 0
</code>```

Title: MySQL - How to change value in column?

Body:
You can use a UPDATE command to change all values on column shipping to 1 on n0v_product:

UPDATE `n0v_product` SET `shipping` = 1

If you only want to set the value if shipping is 0 you can use the following:

UPDATE `n0v_product` SET `shipping` = 1 WHERE `shipping` = 0

You should check the rows before UPDATE to make sure you really want to UPDATE these rows:

-- all rows of table n0v_product
SELECT `shipping`, * FROM `n0v_product`

-- only rows with shipping = 0
SELECT `shipping`, * FROM `n0v_product` WHERE `shipping` = 0


问:
Example encoding video using FFMPEG for Android
I am working on an Android app, that needs to do the following:
- capture a (animated) view to video including audio (from a mp3 file)
- encode the captured video (probably a bunch of raw image buffers) and audio to avi.

After searching, FFMPEG seems the most suitable. Does anybody have a sample code to accomplish what I need. I would really appreciate.

Whyhow

答: if u are building your app for android then u can use .avi writer code. You can get this code from "Koders website". Search for "Koders site" on google .you will get the link. I have tested the .avi file writer code and its working fine.</p>


问:
How to set a configuration parameter at DB level in PostgreSQL permanently?
I am aware of the below command:

```<code>ALTER DATABASE name SET configuration_parameter { TO | = } { value | DEFAULT }
</code>```

On server restart, will these be overwritten by the parameter set in postgresql.conf

答:
The order of settings is like this:

If there is a user setting, take that.

If there is a database setting but no user setting, take that.

Else, take the default setting.

Body:
I am aware of the below command:

ALTER DATABASE name SET configuration_parameter { TO | = } { value | DEFAULT }

On server restart, will these be overwritten by the parameter set in postgresql.conf


问:
Can't switch context with Appium for Cordova hybrid app on Android 7
[Appium 1.7.1] [Android 7.0] [Java] [Hybrid App] [Cordova]
I tried with following logic to switch context, it's working with another Android OS like 5.1.1 but it's not useful for android 7.0. I am not able to focus on native app after context from webview.

```<code>Set<String> availableContexts = driver.getContextHandles();

// switch to Web-view
   for(String context : availableContexts) {
     if(context.contains("WEBVIEW")){
        logger.info("Context Name is " + context);
        driver.context(context);
        break;
     }
   }

// switch to Native app
    for(String context : availableContexts) {
        if(context.contains("NATIVE")){
            logger.info("We are Back to " + context);
            driver.context(context);
            logger.info("Context Switched");
        }
    }
</code>```

答:
There is not much to say without seeing appium server logs.

When you face such kind of issues (stopped working with new OS version update, new Appium server release, etc.) I recommend to print output of driver.getContextHandles() and see what you get.

Its not the first issue with Appium+Cordova and not available to switch context. If you will find out that you don't get NAVIVE_APP context, then you better report issue to appium server project

Body:
[Appium 1.7.1] [Android 7.0] [Java] [Hybrid App] [Cordova]
I tried with following logic to switch context, it's working with another Android OS like 5.1.1 but it's not useful for android 7.0. I am not able to focus on native app after context from webview.

Set<String> availableContexts = driver.getContextHandles();

// switch to Web-view
   for(String context : availableContexts) {
     if(context.contains("WEBVIEW")){
        logger.info("Context Name is " + context);
        driver.context(context);
        break;
     }
   }

// switch to Native app
    for(String context : availableContexts) {
        if(context.contains("NATIVE")){
            logger.info("We are Back to " + context);
            driver.context(context);
            logger.info("Context Switched");
        }
    }


问:
Zoom with animation in current location when map loads in IOS
I have used map in my view controller but when the maps loads it shows me view of the whole country. I want to show my current location view when maps loads, for that I have used didUpdateUserLocation method and set delegate for it.

My code is this:

```<code>-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
   [self.mapView setRegion:MKCoordinateRegionMake(_userLocation.coordinate, MKCoordinateSpanMake(0.1f, 0.1f)) animated:YES];
}
</code>```

Now when my map loads it animate and zoom but in wrong location. It is taking me to any location in sea when map loads , but my current location is different.

I have also tested it in real device but it does not show my location.

The maps looks like that when loads:

ViewController class code:

```<code>@property BOOL updateUserLocation;
@property(strong,nonatomic) CLLocation *userLocation;

@property (nonatomic, retain) MKPolyline *routeLine;

@property (nonatomic, retain) MKPolylineView *routeLineView;

@property (nonatomic,retain) NSString *latitude;

@property (nonatomic,retain) NSString *longitude;
- (void)viewDidLoad {
[super viewDidLoad];
 [[self navigationController] setNavigationBarHidden:YES animated:YES];
_AlertView.hidden=YES;
_distanceView.hidden=YES;
self.mapView.zoomEnabled=YES;

locationManager = [[CLLocationManager alloc]init];
locationManager.delegate = self;
[locationManager startUpdatingLocation];

[self.mapView setShowsUserLocation:YES];
[self.mapView setDelegate:self];

}

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
[self.mapView setRegion:MKCoordinateRegionMake(_userLocation.coordinate, MKCoordinateSpanMake(0.1f, 0.1f)) animated:YES];
}
</code>```

答:
Add these lines in the viewDidLoad:

```<code>self.mapView.showsUserLocation = YES;
</code>```

if you want to center the map to the user location add this:

```<code>[self.mapView setCenterCoordinate:mapView.userLocation.location.coordinate animated:YES];
</code>```

EDIT:

ViewController example:

```<code>#import "ViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>

@interface ViewController () <CLLocationManagerDelegate>
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) CLLocation *location;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [[self mapView] setShowsUserLocation:YES];

    self.locationManager = [[CLLocationManager alloc] init];

    // we have to setup the location manager with permission in later iOS versions
    if ([[self locationManager] respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        [[self locationManager] requestWhenInUseAuthorization];
    }

    [[self locationManager] setDelegate:self];
    [[self locationManager] setDesiredAccuracy:kCLLocationAccuracyBest];
    [[self locationManager] startUpdatingLocation];
}

-(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    // Stop updating location, when you want to restart update use [[self locationManager] startUpdatingLocation];
    [manager stopUpdatingLocation];

    self.location = locations.lastObject;

    // zoom the map into the users current location
    MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance
        (self.location.coordinate, 2, 2);
    [[self mapView] setRegion:viewRegion animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
</code>```

I've only added the IBOutlet on the storyboard and the NSLocationWhenInUseUsageDescription key in the plist.

If you change the location on the simulator you can see the maps change location.

If you want I can upload the complete example project.

NEW EDIT:

There is an error in you code!

When you use [self.mapView setRegion:MKCoordinateRegionMake(_userLocation.coordinate, MKCoordinateSpanMake(0.1f, 0.1f)) animated:YES], you use _userLocation that is your CLLocation variable! You must use userLocation that is the value that you receive from the method.

I recommend you to change the CCLocation variable name and use the userLocation name only for the variable used in the didUpdateUserLocation method.

Body:
I have used map in my view controller but when the maps loads it shows me view of the whole country. I want to show my current location view when maps loads, for that I have used didUpdateUserLocation method and set delegate for it.

My code is this:

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
   [self.mapView setRegion:MKCoordinateRegionMake(_userLocation.coordinate, MKCoordinateSpanMake(0.1f, 0.1f)) animated:YES];
}

Now when my map loads it animate and zoom but in wrong location. It is taking me to any location in sea when map loads , but my current location is different.

I have also tested it in real device but it does not show my location.

The maps looks like that when loads:

ViewController class code:

@property BOOL updateUserLocation;
@property(strong,nonatomic) CLLocation *userLocation;

@property (nonatomic, retain) MKPolyline *routeLine;

@property (nonatomic, retain) MKPolylineView *routeLineView;

@property (nonatomic,retain) NSString *latitude;

@property (nonatomic,retain) NSString *longitude;
- (void)viewDidLoad {
[super viewDidLoad];
 [[self navigationController] setNavigationBarHidden:YES animated:YES];
_AlertView.hidden=YES;
_distanceView.hidden=YES;
self.mapView.zoomEnabled=YES;

locationManager = [[CLLocationManager alloc]init];
locationManager.delegate = self;
[locationManager startUpdatingLocation];

[self.mapView setShowsUserLocation:YES];
[self.mapView setDelegate:self];

}

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
[self.mapView setRegion:MKCoordinateRegionMake(_userLocation.coordinate, MKCoordinateSpanMake(0.1f, 0.1f)) animated:YES];
}

Body:
Add these lines in the viewDidLoad:

self.mapView.showsUserLocation = YES;

if you want to center the map to the user location add this:

[self.mapView setCenterCoordinate:mapView.userLocation.location.coordinate animated:YES];

EDIT:

ViewController example:

#import "ViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>

@interface ViewController () <CLLocationManagerDelegate>
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) CLLocation *location;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [[self mapView] setShowsUserLocation:YES];

    self.locationManager = [[CLLocationManager alloc] init];

    // we have to setup the location manager with permission in later iOS versions
    if ([[self locationManager] respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        [[self locationManager] requestWhenInUseAuthorization];
    }

    [[self locationManager] setDelegate:self];
    [[self locationManager] setDesiredAccuracy:kCLLocationAccuracyBest];
    [[self locationManager] startUpdatingLocation];
}

-(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    // Stop updating location, when you want to restart update use [[self locationManager] startUpdatingLocation];
    [manager stopUpdatingLocation];

    self.location = locations.lastObject;

    // zoom the map into the users current location
    MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance
        (self.location.coordinate, 2, 2);
    [[self mapView] setRegion:viewRegion animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

I've only added the IBOutlet on the storyboard and the NSLocationWhenInUseUsageDescription key in the plist.

If you change the location on the simulator you can see the maps change location.

If you want I can upload the complete example project.

NEW EDIT:

There is an error in you code!

When you use [self.mapView setRegion:MKCoordinateRegionMake(_userLocation.coordinate, MKCoordinateSpanMake(0.1f, 0.1f)) animated:YES], you use _userLocation that is your CLLocation variable! You must use userLocation that is the value that you receive from the method.

I recommend you to change the CCLocation variable name and use the userLocation name only for the variable used in the didUpdateUserLocation method.


问:
Why are only final variables accessible in anonymous class?

a can only be final here.  Why?  How can I reassign a in onClick() method without keeping it as private member?

```<code>private void f(Button b, final int a){
    b.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
            int b = a*5;

        }
    });
}
</code>```

How can I return the 5 * a when it clicked? I mean,

```<code>private void f(Button b, final int a){
    b.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
             int b = a*5;
             return b; // but return type is void
        }
    });
}
</code>```

答:
Well, in Java, a variable can be final not just as a parameter, but as a class-level field, like

```<code>public class Test
{
 public final int a = 3;
</code>```

or as a local variable, like

```<code>public static void main(String[] args)
{
 final int a = 3;
</code>```

If you want to access and modify a variable from an anonymous class, you might want to make the variable a class-level variable in the enclosing class.

```<code>public class Test
{
 public int a;
 public void doSomething()
 {
  Runnable runnable =
   new Runnable()
   {
    public void run()
    {
     System.out.println(a);
     a = a+1;
    }
   };
 }
}
</code>```

You can't have a variable as final and give it a new value. final means just that: the value is unchangeable and final.

And since it's final, Java can safely copy it to local anonymous classes. You're not getting some reference to the int (especially since you can't have references to primitives like int in Java, just references to Objects).

It just copies over the value of a into an implicit int called a in your anonymous class.

Body:
a can only be final here.  Why?  How can I reassign a in onClick() method without keeping it as private member?

private void f(Button b, final int a){
    b.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
            int b = a*5;

        }
    });
}

How can I return the 5 * a when it clicked? I mean,

private void f(Button b, final int a){
    b.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
             int b = a*5;
             return b; // but return type is void
        }
    });
}

Body:
Well, in Java, a variable can be final not just as a parameter, but as a class-level field, like

public class Test
{
 public final int a = 3;

or as a local variable, like

public static void main(String[] args)
{
 final int a = 3;

If you want to access and modify a variable from an anonymous class, you might want to make the variable a class-level variable in the enclosing class.

public class Test
{
 public int a;
 public void doSomething()
 {
  Runnable runnable =
   new Runnable()
   {
    public void run()
    {
     System.out.println(a);
     a = a+1;
    }
   };
 }
}

You can't have a variable as final and give it a new value. final means just that: the value is unchangeable and final.

And since it's final, Java can safely copy it to local anonymous classes. You're not getting some reference to the int (especially since you can't have references to primitives like int in Java, just references to Objects).

It just copies over the value of a into an implicit int called a in your anonymous class.


问:
Override Tooltip for List Mode = Delete
I have a List with the mode Delete. Is there a way to override the tooltip for the delete button?

答:
This is where the magic happens: sap.m.ListBase.prototype.getDeleteControl

You could easily override this and change the tooltip to sth. else. Don't forget to keep calling the original method for future compatibility:

```<code>var fnOriginal = sap.m.ListItemBase.prototype.getDeleteControl
sap.m.ListItemBase.prototype.getDeleteControl = function() {
  var oDelIcon = fnOriginal.apply(this, arguments);
  oDelIcon.setTooltip("My fancy tooltip");
  return oDelIcon;
}
</code>```

Disclaimer: Be aware that this API is PRIVATE and can be subject to future change which will potentialy break your code. The least that could happen is that your tooltip stops working.

HF Chris

Title: Override Tooltip for List Mode = Delete

Body:
This is where the magic happens: sap.m.ListBase.prototype.getDeleteControl

You could easily override this and change the tooltip to sth. else. Don't forget to keep calling the original method for future compatibility:

var fnOriginal = sap.m.ListItemBase.prototype.getDeleteControl
sap.m.ListItemBase.prototype.getDeleteControl = function() {
  var oDelIcon = fnOriginal.apply(this, arguments);
  oDelIcon.setTooltip("My fancy tooltip");
  return oDelIcon;
}

Disclaimer: Be aware that this API is PRIVATE and can be subject to future change which will potentialy break your code. The least that could happen is that your tooltip stops working.

HF Chris


问:
form serialize javascript (no framework)
Wondering is there a function in javascript without jquery or any framework that allows me to serialize the form and access the serialized version?</p>

答:
I've grabbed the  entries() method of formData from @moison answer and from MDN it's said that :

The FormData.entries() method returns an iterator allowing to go
  through all key/value pairs contained in this object. The key of each
  pair is a USVString object; the value either a USVString, or a Blob.

but the only issue is that mobile browser (android and safari are not supported ) and IE and Safari desktop too

but basically here is my approach :

```<code>let theForm =  document.getElementById("contact");

theForm.onsubmit = function(event) {
    event.preventDefault();

    let rawData = new FormData(theForm);
    let data = {};

   for(let pair of rawData.entries()) {
     data[pair[0]] = pair[1];
    }
    let contactData = JSON.stringify(data);
    console.warn(contactData);
    //here you can send a post request with content-type :'application.json'

};
</code>```

the code can be found here

Body:
I've grabbed the  entries() method of formData from @moison answer and from MDN it's said that :

The FormData.entries() method returns an iterator allowing to go
  through all key/value pairs contained in this object. The key of each
  pair is a USVString object; the value either a USVString, or a Blob.

but the only issue is that mobile browser (android and safari are not supported ) and IE and Safari desktop too

but basically here is my approach :

let theForm =  document.getElementById("contact");

theForm.onsubmit = function(event) {
    event.preventDefault();

    let rawData = new FormData(theForm);
    let data = {};

   for(let pair of rawData.entries()) {
     data[pair[0]] = pair[1];
    }
    let contactData = JSON.stringify(data);
    console.warn(contactData);
    //here you can send a post request with content-type :'application.json'

};

the code can be found here


问:
How to invoke a script on some action on ticket on bmc remedy?
The requirement is to invoke a shell script/.bat file on some action done on BMC remedy's incidents.
After some research, it looks filter is the answer. But, on BMC remedy GUI, can't find any link to create a filter.

Update:
BMC Doc link

Where is the link to create filter on BMC GUI ?? Have logged in as admin too.

答:
If the link is right, you are using Remedy 8.1 version. You need the BMC Remedy Developer Studio tool to create a filter. </p>

<p>Then in the filter you have to add an "run process" action with the unix or window command that runs the script. </p>

Body:
If the link is right, you are using Remedy 8.1 version. You need the BMC Remedy Developer Studio tool to create a filter.

Then in the filter you have to add an "run process" action with the unix or window command that runs the script.


问:
Firefox does not render <input> element inside JQuery modal dialog
I have tried to search for any clues but have not discovered any. Take a look at the following page:

http://jqtest.encorephoenix.com/withinput.aspx (JQuery modal popup with <input>)

Popup is renders correctly in IE, Chrome, Safari and Opera. Firefox 3.6.13 does not render the popup with  correctly. You can view withoutinput.aspx at the same URL to see that Firefox renders it correctly, since this page does not have <input> element. I have tried the following with no resolution to this peculiar problem:

Changed doctype

Used  to enclose <input>

Used  to enclose <input>

Used all possible CSS display attributes for <input>

Any suggestions would be greatly appreciated.

答:
The div is positioned on top of page. For now I was able to get the display by adding margin-top of 100px to class

```<code>.ui-dialog .ui-dialog-titlebar
{
margin-top:100px;
}
</code>```

I am exploring more on it. But others can try on it
The pop up is also not working properly on IE9.

Body:
The div is positioned on top of page. For now I was able to get the display by adding margin-top of 100px to class

.ui-dialog .ui-dialog-titlebar
{
margin-top:100px;
}

I am exploring more on it. But others can try on it
The pop up is also not working properly on IE9.

OwnerDisplayName: Sreedhar K


问:
How to avoid claims transformation for certain requests in Asp.NET Core
At the API level, I have some identity claims coming from Identity-Server for authorizing the current user and I could use some for first level of authorization. But in a next step, for additional permissions checks, these claims are not enough, I'll have to retrieve more data from database.

My idea was to create a custom ClaimsPrincipal where I attach all the permissions from database, but I don't want to call database more than once per request.

So, I thought of having my own implementation of Microsoft.AspNetCore.Authentication.IClaimsTransformer which I added to the pipeline like so:

```<code>app.UseClaimsTransformation(new ClaimsTransformationOptions()
{
   Transformer = new MyClaimsTransformer()
});
</code>```

and my current transformation method:

```<code>public Task<ClaimsPrincipal> TransformAsync(ClaimsTransformationContext context)
{
    if (context.Principal.Identity.IsAuthenticated)
    {
        var principal = new MyClaimsPrincipal(context.Principal);
        principal.Permissions = /* load from db */;
        return Task.FromResult<ClaimsPrincipal>(principal);
     }
     return Task.FromResult(context.Principal);
}
</code>```

I already noticed that claims transformation method is called every time, with each request. So, I would like to have control over it, to avoid calling the database when there is no authenticated user or no authorization required (case of AllowAnonymous attribute) and when there is no need for extra permissions check (ideally).

I feel that the claims transformation should be bound to Identity Server's authorization or something, but no idea how.

Any thoughts on this? Thank you!

Edit I found here that I could hook the claims transformation to OnTokenValidated part of JwtBearerEvents from IdentityServer4.AccessTokenValidation. Unfortunately, there is another unknown middleware overwriting MyClaimsPrincipal. I am puzzled on how this works..

答:
You can use the following check in your ClaimsTransformer to test for anonymous access.

```<code>using System.Security.Claims;
using System.Web;
using System.Web.Security;

private bool IsAnonymousAccessAllowed => UrlAuthorizationModule.CheckUrlAccessForPrincipal(
    HttpContext.Current.Request.Path,
    AnonymousClaimsPrincipal,
    HttpContext.Current.Request.RequestType
);
</code>```

with AnonymousClaimsPrincipal as

```<code>ClaimsPrincipal AnonymousClaimsPrincipal => new ClaimsPrincipal(
    (IIdentity) new ClaimsIdentity(
        (IEnumerable<Claim>) new List<Claim>() {
             new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "")
        }
    )
);
</code>```

Change the logic in the ClaimsTransformer to skip transformation for anonymous access:

```<code>if (!IsAnonymousAccessAllowed && context.Principal.Identity.IsAuthenticated) { /* ... */ }
</code>```

(This code is from a MVC5 project, I hope it also works in .net core.)

Body:
At the API level, I have some identity claims coming from Identity-Server for authorizing the current user and I could use some for first level of authorization. But in a next step, for additional permissions checks, these claims are not enough, I'll have to retrieve more data from database.

My idea was to create a custom ClaimsPrincipal where I attach all the permissions from database, but I don't want to call database more than once per request.

So, I thought of having my own implementation of Microsoft.AspNetCore.Authentication.IClaimsTransformer which I added to the pipeline like so:

app.UseClaimsTransformation(new ClaimsTransformationOptions()
{
   Transformer = new MyClaimsTransformer()
});

and my current transformation method:

public Task<ClaimsPrincipal> TransformAsync(ClaimsTransformationContext context)
{
    if (context.Principal.Identity.IsAuthenticated)
    {
        var principal = new MyClaimsPrincipal(context.Principal);
        principal.Permissions = /* load from db */;
        return Task.FromResult<ClaimsPrincipal>(principal);
     }
     return Task.FromResult(context.Principal);
}

I already noticed that claims transformation method is called every time, with each request. So, I would like to have control over it, to avoid calling the database when there is no authenticated user or no authorization required (case of AllowAnonymous attribute) and when there is no need for extra permissions check (ideally).

I feel that the claims transformation should be bound to Identity Server's authorization or something, but no idea how.

Any thoughts on this? Thank you!

Edit I found here that I could hook the claims transformation to OnTokenValidated part of JwtBearerEvents from IdentityServer4.AccessTokenValidation. Unfortunately, there is another unknown middleware overwriting MyClaimsPrincipal. I am puzzled on how this works..

Body:
You can use the following check in your ClaimsTransformer to test for anonymous access.

using System.Security.Claims;
using System.Web;
using System.Web.Security;

private bool IsAnonymousAccessAllowed => UrlAuthorizationModule.CheckUrlAccessForPrincipal(
    HttpContext.Current.Request.Path,
    AnonymousClaimsPrincipal,
    HttpContext.Current.Request.RequestType
);

with AnonymousClaimsPrincipal as

ClaimsPrincipal AnonymousClaimsPrincipal => new ClaimsPrincipal(
    (IIdentity) new ClaimsIdentity(
        (IEnumerable<Claim>) new List<Claim>() {
             new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "")
        }
    )
);

Change the logic in the ClaimsTransformer to skip transformation for anonymous access:

if (!IsAnonymousAccessAllowed && context.Principal.Identity.IsAuthenticated) { /* ... */ }

(This code is from a MVC5 project, I hope it also works in .net core.)


问:
Positionning button from bottom screen
I am doing some XML for an android app.

I have images, text, and button in my view.

I used a Linear layout, but I think it's not what I need.

I would like to set my last button to 80 dp from the bottom screen. Regardless the smartphone and the size of the screen.
I want my button to be at 80 dp from the bottom of all device.

I have no idea how to do it if someone can help me it could be cool!

I tried with a LinearLayout but i think i can't do it.

Now I'm trying with a constraintLayout but I'm not sure it will work.

Thanks

答:
I finally found a solution with constraint layout.

I'm using  app:layout_constraintBottom_toBottomOf to align my button to the bottom of my screen then i use a marginBottom. Thanks for all for your response, i will try it with a relative layout :)

Title: Positionning button from bottom screen


问:
Creating a custom JSON string from a PHP array
I have a PHP array which outputs as follows:

```<code>Array ( [0] => email@email.com [1] => email@email.com [2] => email@email.com [3] => email@email.com [4] => email@email.com [5] => email@email.com )
</code>```

This array houses a list of email addresses, which I need to output as a custom JSON string, which matches the following:

```<code>{ "email@email.com": {"id":1}, "email@email.com": {"id": 2}, "email@email.com": {"id": 3}, "email@email.com": {"id": 4}, "email@email.com": {"id": 5}, "email@email.com": {"id": 6} }
</code>```

Is anyone able to point me in the right direction? I have tried using json_encode, without success.

答:
You can do like this,

```<code><?php
  $a = Array("email@email.com","email@email.com","email@email.com");

  $arr = array();
  $i = 0;
  foreach($a as $single){
   $arr[][$single]['id'] = $i;
   $i++;
  }
  print_r(json_encode($arr));
 ?>
</code>```

Demo is here, Demo

Body:
I have a PHP array which outputs as follows:

Array ( [0] => email@email.com [1] => email@email.com [2] => email@email.com [3] => email@email.com [4] => email@email.com [5] => email@email.com )

This array houses a list of email addresses, which I need to output as a custom JSON string, which matches the following:

{ "email@email.com": {"id":1}, "email@email.com": {"id": 2}, "email@email.com": {"id": 3}, "email@email.com": {"id": 4}, "email@email.com": {"id": 5}, "email@email.com": {"id": 6} }

Is anyone able to point me in the right direction? I have tried using json_encode, without success.

Body:
You can do like this,

<?php
  $a = Array("email@email.com","email@email.com","email@email.com");

  $arr = array();
  $i = 0;
  foreach($a as $single){
   $arr[][$single]['id'] = $i;
   $i++;
  }
  print_r(json_encode($arr));
 ?>

Demo is here, Demo


问:
How to plot a column from a csv file against a column that doesn't exist in the file?
So I am pretty new to python and matplotlib using csvfiles. My question is trying to plot the following graph. I'm having an issue with creating the x variable that I need to plot against y, 'doors'. More specifically, I want to be able to plot the number of 'doors' against the car id which can be assumed to be 0,1,2,3,4,5,6,7... and so on with respect to the entries in the 'doors' columns. Without a specific column already dedicated to car id, how would I go about this?</p>

```<code>import matplotlib.pyplot as plt
import csv

x = []
y = []

with open('9car.data.csv','r') as csvfile:
    plots = csv.reader(csvfile, delimiter=',')
</code>```

答:
From the pyplot.plot documentation

For example, each of the following is legal:

```plot(x, y)        # plot x and y using default line style and color
plot(x, y, 'bo')  # plot x and y using blue circle markers <b>
plot(y)           # plot y using x as index array 0..N-1</b> ```

Hence something like this would work

```<code>import matplotlib.pyplot as plt
import csv

with open('data/estimated.csv','r') as csvfile:
    plots = csv.reader(csvfile, delimiter=',')
    y = [float(row[1]) for row in plots]

plt.plot(y)

plt.show()
</code>```

Or even better, using numpy

```<code>import matplotlib.pyplot as plt
import numpy as np
x,y = np.loadtxt('data/estimated.csv', delimiter=',',unpack=True)

plt.plot(y)

plt.show()
</code>```

Body:
So I am pretty new to python and matplotlib using csvfiles. My question is trying to plot the following graph. I'm having an issue with creating the x variable that I need to plot against y, 'doors'. More specifically, I want to be able to plot the number of 'doors' against the car id which can be assumed to be 0,1,2,3,4,5,6,7... and so on with respect to the entries in the 'doors' columns. Without a specific column already dedicated to car id, how would I go about this?

import matplotlib.pyplot as plt
import csv

x = []
y = []

with open('9car.data.csv','r') as csvfile:
    plots = csv.reader(csvfile, delimiter=',')

Body:
From the pyplot.plot documentation

For example, each of the following is legal:

plot(x, y)        # plot x and y using default line style and color
plot(x, y, 'bo')  # plot x and y using blue circle markers
plot(y)           # plot y using x as index array 0..N-1

Hence something like this would work

import matplotlib.pyplot as plt
import csv

with open('data/estimated.csv','r') as csvfile:
    plots = csv.reader(csvfile, delimiter=',')
    y = [float(row[1]) for row in plots]

plt.plot(y)

plt.show()

Or even better, using numpy

import matplotlib.pyplot as plt
import numpy as np
x,y = np.loadtxt('data/estimated.csv', delimiter=',',unpack=True)

plt.plot(y)

plt.show()


问:
Slide finger on keyboard area to print a key
i just need to create an edit box with keyboard below..Below keyboard,,there should be an Slide finger on the keyboard link area while looking at the keyboard.As the finger slides, the key corresponding to the location of the finger on the keyboard link area is highlighted.And when i click on dragger,the corresponding letter should be printed on edittext.How could i do this.?.Thanks..</p>

答:
As I have figured out, you need to have a mechanism where you let the users draw letters on a surface, and then you put them in the EditText by detecting what it latter was.

As a concept, you can do this:

Below the EditText, have a Canvas area, where people can draw letters.

Since I haven't tried many of Canvas things myself, you'll have to do the R&D, sorry.
but listen for press and move events.
record each pixel where the user is moving their fingers, and when the user lifts the finger up, perform detection.

For detection, you will have to have a database which tells you which drawing pattern corresponds to which letter. For this, develop a base where you store which pixel traversal path refers to which letter, and allow a threshold level. then put this info in the database.

when the user finishes drawing, and you have collected all the pixels user had traversed on, compare the set with the database to recognise which letter it was.

I know it might become complex, and requires you to evolve your own data structures (sadly, i don't have any structure in mind for this purpose as of now) for this, but it will be extremely interesting, and time taking too! ;-)

Just disable the keyboard for EditText when you're about to implement it.


问:
Vaadin expand ratio for Label with potentially empty value
In one of our pages I've created a detail screen with some information divided in blocks. I've used HorizontalLayouts with setExpandRatio for this. Here is how this is divided (all values made black for privacy reasons):

The final Label of the second row (now containing ---) should actually be empty instead. All the blocks are basically Vaadin Labels, with values in it. However, these values can sometimes be null, in which case I don't want to show anything in the Label.

When I use an empty String however instead of ---, it will look like this:

As you can see at the final Label of the second row, it is now missing it's border (and possible other styles we might add in the future), because Vaadin automatically put the expandRatio of Labels with an empty input to 0, turning the width to 0px.

I know you can set the actual width of a Label as filler, but in this case it's simply a question whether the value that's supposed to be in that Label is or isn't null.

I've also tried a space as value, but it just ignores it and behaves the same as the empty value. And when I " " as value (without setting the Label to HTML-mode), it outputs this literally as   on the screen.

Is there any value I could use for the Label when the value is null to still show the style with borders, but without value?

EDIT: Hmm, when I use   and set the ContentMode of the Label to HTML it seems to work. Is this the intended work-around for this issue (which means I'll have to set ContentMode to HTML for all Labels with the potential of containing an empty value), or is there another workaround by changing this 'empty' value alone?

答: Ok, I ended up using my solution provided in the EDIT. For all these Labels I had already created a BorderedLabel class, so I simply added setContentMode(ContentMode.HTML); to it, and used   when the value is null in our util helper class.

Body: Ok, I ended up using my solution provided in the EDIT. For all these Labels I had already created a BorderedLabel class, so I simply added setContentMode(ContentMode.HTML); to it, and used &nbsp; when the value is null in our util helper class.


问:
SearchView: when click Done button nothing happens
Here snippet:

```<code> searchViewEditText.setImeOptions(EditorInfo.IME_ACTION_DONE);
        searchViewEditText.setSingleLine(true);
</code>```

As result when keyboard open, the button Done is show.
OK.

Here result:

But when I click on button Done nothing happen. I expect that keyboard will be hide.

答:
You can use this (sets a special listener to be called when an action is performed on the EditText), it works both for DONE and RETURN:</p>

```<code>max.setOnEditorActionListener(new OnEditorActionListener() {
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) {
            Log.i(TAG,"Enter pressed");
        }
        return false;
    }
});
</code>```

Body:
Here snippet:

 searchViewEditText.setImeOptions(EditorInfo.IME_ACTION_DONE);
        searchViewEditText.setSingleLine(true);

As result when keyboard open, the button Done is show.
OK.

Here result:

But when I click on button Done nothing happen. I expect that keyboard will be hide.

Body:
You can use this (sets a special listener to be called when an action is performed on the EditText), it works both for DONE and RETURN:

max.setOnEditorActionListener(new OnEditorActionListener() {
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) {
            Log.i(TAG,"Enter pressed");
        }
        return false;
    }
});


问:
Union vs Unionwith in HashSet
What the difference between  HashSet.Union  vs HashSet.Unionwith  when i combine 2 hashsets.

I am trying to combine like this:

```<code>HashSet<EngineType> enginesSupportAll = _filePolicyEvaluation.EnginesSupportAll;
        enginesSupportAll = enginesSupportAll != null ? new HashSet<EngineType>(engines.Union(enginesSupportAll)) : enginesSupportAll;
</code>```

what is the best method for this example and why?

答:
Given HashSet<T> A and HashSet<T> B there are four ways to A ∪ B:

new HashSet<t>(A.Union(B))

 (see HashSet<T&>(IEnumerable<T>) and
Enumerable.Union<T>(IEnumerable<T>, IEnumerable<T>))

A.UnionWith(B)

HashSet<T> C = new HashSet<T>(A); C.UnionWith(B);

new HashSet<t>(A.Concat(B))

(see Enumerable.Concat<T>(IEnumerable<T>, IEnumerable<T>))

Each has its advantages and disadvantages:

1 and 4 are expressions that results in a HashSet whereas 2 and 3 are statements or statement blocks.

Expression 1 and 4 can be used in more places than 2 and 3. For example, using 2 or 3 in a linq query syntax expression is cumbersome:

from x in setofSetsA as IEnumerable<HashSet<T>>
from y in setOfSetsB as IEnumerable<HashSet<T>>
select x.UnionWith(y) will not work since UnionWith returns void.

1, 3, and 4 preserve A and B as they are and return a fresh set whereas 2 modifies A.

There are situations where modifying one of the original sets is bad and there are situations where at least one of the original sets can be modified without negative consequences.

Computational cost:

A.UnionWith(B)

(≈ O((log(|A∪B|) - log(|A|)) * |A∪B|) + O(|B|))

≤

HashSet<T> C = new HashSet<T>(A); C.UnionWith(B);

(≈ O((log(|A∪B|) - log(|A|)) * |A∪B|) + O(|A| + |B|))

≤

HashSet<T>(A.Concat(B))

(≈ O(log(|A∪B|) * |A∪B|) + O(|A| + |B|))

≤

HashSet<T>(A.Union(B))

(≈ 2 * O(log(|A∪B|) * |A∪B|) + O(|A| + |B| + |A∪B|))

The next section delves into the reference source to see the basis of these performance estimates.

Performance

HashSet<T>

In union option 1, 3, and 4 the constructor HashSet<T>(IEnumerable<T>, IEqualityComparer<T>) is used to create a HashSet<T> from an IEnumerable<T>.
If the passed IEnumerable<T> has a Count property —i.e. if it is an ICollection<T>—, this property is used to set the size of the new HashSet:

```<code>int suggestedCapacity = 0;
ICollection<T> coll = collection as ICollection<T>;
if (coll != null) {
    suggestedCapacity = coll.Count;
}
Initialize(suggestedCapacity);
</code>```

-- HashSet.cs line 136–141

The [Count()][10] method is never called.  So if the IEnumerable's count can be retrieved without effort it is used to reserve capacity; otherwise the HashSet grows and reallocates when new elements are added.

In option 1 A.Union(B) and option 4 A.Concat(B) are not ICollection<T> therefore the created HashSet will grow and reallocate a few (≈ log(|A∪B|)) times.  Option 3 can use the Count of A.

The constructor calls UnionWith to fill the new empty HashSet:

```<code>this.UnionWith(collection);
</code>```

-- HashSet.cs line 143

UnionWith(IEnumerable<T>) iterates over the elements in the IEnumerable<T> passed as argument and calls AddIfNotPresent(T) for each.

AddIfNotPresent(T) inserts elements and ensures that duplicates are never inserted into the set.

HashSet<T> is implemented as an array of slots, m_slots, and an array of buckets, m_buckets.  A bucket contains just an int index into the m_slots array.  Per bucket the Slots in m_slots form a linked list with an index to the next Slot in m_slots.

AddIfNotPresent(T) jumps to the correct bucket and then traverses its linked list to check if the element is already present:

```<code>for (int i = m_buckets[hashCode % m_buckets.Length] - 1; i >= 0; i = m_slots[i].next) {
    if (m_slots[i].hashCode == hashCode && m_comparer.Equals(m_slots[i].value, value)) {
        return false;
    }
}
</code>```

-- HashSet.cs line 968–975

Next a free index is found and a slot is reserved.  First the list of free slots, m_freelist, is checked.  When there are no slots in the freelist, the next empty slot in the m_slots array is used.  More capacity is reserved (via IncreaseCapacity()) if there are no slots in the freelist and no empty slots:

```<code>int index;
if (m_freeList >= 0) {
    index = m_freeList;
    m_freeList = m_slots[index].next;
}
else {
    if (m_lastIndex == m_slots.Length) {
        IncreaseCapacity();
        // this will change during resize
        bucket = hashCode % m_buckets.Length;
    }
    index = m_lastIndex;
    m_lastIndex++;
}
</code>```

-- HashSet.cs line 977–990

AddIfNotPresent(T) has three operations that demand some computation: the call to object.GetHashCode(), calling object.Equals(object) when there is a collision, and IncreaseCapacity().  The actual adding of an element only incurs the cost of setting some pointers and some ints.

When the HashSet<T> needs to IncreaseCapacity() the capacity is at least doubled.  Therefore we can conclude that on average a HashSet<T> is filled for 75%.  If the hashes are evenly distributed, the expectancy of a hash collision is also 75%.

SetCapacity(int, bool), called by IncreaseCapacity(), is the most expensive: it allocates new arrays, it copies the old slot array to the new array, and it recalculates the bucket lists:

```<code>Slot[] newSlots = new Slot[newSize];
if (m_slots != null) {
    Array.Copy(m_slots, 0, newSlots, 0, m_lastIndex);
}

...

int[] newBuckets = new int[newSize];
for (int i = 0; i < m_lastIndex; i++) {
    int bucket = newSlots[i].hashCode % newSize;
    newSlots[i].next = newBuckets[bucket] - 1;
    newBuckets[bucket] = i + 1;
}
m_slots = newSlots;
m_buckets = newBuckets;
</code>```

-- HashSet.cs line 929–949

Option 1 and 4 (new HashSet<T>(A.Union(B))) will result in slightly more calls to IncreaseCapacity().  The cost —without the cost of A.Union(B) or A.Concat(B)— is approximately O(log(|A∪B|) * |A∪B|).

Whereas when using option 2 (A.UnionWith(B)) or option 3 (HashSet<T> C = new HashSet<T>(A); C.UnionWith(B)) we get a 'discount' of log(|A|) on the cost: O((log(|A∪B|) - log(|A|)) * |A∪B|).  It pays (slightly) to use the largest set as the target into witch the other is merged.

Enumerable<T>.Union(IEnumerable<T>)

Enumerable<T>.Union(IEnumerable<T>) is implemented via UnionIterator<T>(IEnumerable<T>, IEnumerable<T>, IEqualityComparer<T>).

The UnionIterator uses Set<T> —an internal class in Enumerable.cs— that is very similar to HashSet<T>.  UnionIterator lazily Add(T)s items from A and B to this Set<T> and yields the elements if they could be added.  The work is done in Find(T, bool) which is similar to HashSet<T>.AddIfNotPresent(T).  Check if the element is already present:

```<code>int hashCode = InternalGetHashCode(value);
for (int i = buckets[hashCode % buckets.Length] - 1; i >= 0; i = slots[i].next) {
    if (slots[i].hashCode == hashCode && comparer.Equals(slots[i].value, value)) return true;
}
</code>```

-- Enumerable.cs line 2423–2426

Find a free index and reserve a slot:

```<code>int index;
if (freeList >= 0) {
    index = freeList;
    freeList = slots[index].next;
}
else {
    if (count == slots.Length) Resize();
    index = count;
    count++;
}
int bucket = hashCode % buckets.Length;
slots[index].hashCode = hashCode;
slots[index].value = value;
slots[index].next = buckets[bucket] - 1;
buckets[bucket] = index + 1;
</code>```

-- Enumerable.cs line 2428–2442

Resize() is similar to IncreaseCapacity().  The biggest difference between the two is that Resize() does not use a prime number for the number of buckets, so with bad GetHashCode() there is a slightly higher chance for collisions.  Code of Resize():

```<code>int newSize = checked(count * 2 + 1);
int[] newBuckets = new int[newSize];
Slot[] newSlots = new Slot[newSize];
Array.Copy(slots, 0, newSlots, 0, count);
for (int i = 0; i < count; i++) {
    int bucket = newSlots[i].hashCode % newSize;
    newSlots[i].next = newBuckets[bucket] - 1;
    newBuckets[bucket] = i + 1;
}
buckets = newBuckets;
slots = newSlots;
</code>```

-- Enumerable.cs line 2448–2458

The performance cost of A.Union(B) is not significantly different from that of HashSet<T> C = new HashSet<T>(); C.UnionWith(A); C.UnionWith(B);.  In option 1 (new HashSet<T>(A.Union(B))) the same HashSet is created twice resulting in a very costly 2 * O(log(|A∪B|) * (|A∪B|)).  Option 4 results from knowing how HashSet<T>(IEnumerable<T>) and Enumerable.Union(IEnumerable<T>, IEnumerable<T>) are implemented.  It avoids the redundant A.Union(B) leading to a cost of O(log(|A∪B|) * |A∪B|).

Title: Union vs Unionwith in HashSet

Body:
What the difference between  HashSet.Union  vs HashSet.Unionwith  when i combine 2 hashsets.

I am trying to combine like this:

HashSet<EngineType> enginesSupportAll = _filePolicyEvaluation.EnginesSupportAll;
        enginesSupportAll = enginesSupportAll != null ? new HashSet<EngineType>(engines.Union(enginesSupportAll)) : enginesSupportAll;

what is the best method for this example and why?

Body:
Given HashSet<T> A and HashSet<T> B there are four ways to A ∪ B:

new HashSet<t>(A.Union(B))

 (see HashSet<T&>(IEnumerable<T>) and
Enumerable.Union<T>(IEnumerable<T>, IEnumerable<T>))

A.UnionWith(B)

HashSet<T> C = new HashSet<T>(A); C.UnionWith(B);

new HashSet<t>(A.Concat(B))

(see Enumerable.Concat<T>(IEnumerable<T>, IEnumerable<T>))

Each has its advantages and disadvantages:

1 and 4 are expressions that results in a HashSet whereas 2 and 3 are statements or statement blocks.

Expression 1 and 4 can be used in more places than 2 and 3. For example, using 2 or 3 in a linq query syntax expression is cumbersome:

from x in setofSetsA as IEnumerable<HashSet<T>>
from y in setOfSetsB as IEnumerable<HashSet<T>>
select x.UnionWith(y) will not work since UnionWith returns void.

1, 3, and 4 preserve A and B as they are and return a fresh set whereas 2 modifies A.

There are situations where modifying one of the original sets is bad and there are situations where at least one of the original sets can be modified without negative consequences.

Computational cost:

A.UnionWith(B)

(≈ O((log(|A∪B|) - log(|A|)) * |A∪B|) + O(|B|))

≤

HashSet<T> C = new HashSet<T>(A); C.UnionWith(B);

(≈ O((log(|A∪B|) - log(|A|)) * |A∪B|) + O(|A| + |B|))

≤

HashSet<T>(A.Concat(B))

(≈ O(log(|A∪B|) * |A∪B|) + O(|A| + |B|))

≤

HashSet<T>(A.Union(B))

(≈ 2 * O(log(|A∪B|) * |A∪B|) + O(|A| + |B| + |A∪B|))

The next section delves into the reference source to see the basis of these performance estimates.

Performance

HashSet<T>

In union option 1, 3, and 4 the constructor HashSet<T>(IEnumerable<T>, IEqualityComparer<T>) is used to create a HashSet<T> from an IEnumerable<T>.
If the passed IEnumerable<T> has a Count property —i.e. if it is an ICollection<T>—, this property is used to set the size of the new HashSet:

int suggestedCapacity = 0;
ICollection<T> coll = collection as ICollection<T>;
if (coll != null) {
    suggestedCapacity = coll.Count;
}
Initialize(suggestedCapacity);

-- HashSet.cs line 136–141

The [Count()][10] method is never called.  So if the IEnumerable's count can be retrieved without effort it is used to reserve capacity; otherwise the HashSet grows and reallocates when new elements are added.

In option 1 A.Union(B) and option 4 A.Concat(B) are not ICollection<T> therefore the created HashSet will grow and reallocate a few (≈ log(|A∪B|)) times.  Option 3 can use the Count of A.

The constructor calls UnionWith to fill the new empty HashSet:

this.UnionWith(collection);

-- HashSet.cs line 143

UnionWith(IEnumerable<T>) iterates over the elements in the IEnumerable<T> passed as argument and calls AddIfNotPresent(T) for each.

AddIfNotPresent(T) inserts elements and ensures that duplicates are never inserted into the set.

HashSet<T> is implemented as an array of slots, m_slots, and an array of buckets, m_buckets.  A bucket contains just an int index into the m_slots array.  Per bucket the Slots in m_slots form a linked list with an index to the next Slot in m_slots.

AddIfNotPresent(T) jumps to the correct bucket and then traverses its linked list to check if the element is already present:

for (int i = m_buckets[hashCode % m_buckets.Length] - 1; i >= 0; i = m_slots[i].next) {
    if (m_slots[i].hashCode == hashCode && m_comparer.Equals(m_slots[i].value, value)) {
        return false;
    }
}

-- HashSet.cs line 968–975

Next a free index is found and a slot is reserved.  First the list of free slots, m_freelist, is checked.  When there are no slots in the freelist, the next empty slot in the m_slots array is used.  More capacity is reserved (via IncreaseCapacity()) if there are no slots in the freelist and no empty slots:

int index;
if (m_freeList >= 0) {
    index = m_freeList;
    m_freeList = m_slots[index].next;
}
else {
    if (m_lastIndex == m_slots.Length) {
        IncreaseCapacity();
        // this will change during resize
        bucket = hashCode % m_buckets.Length;
    }
    index = m_lastIndex;
    m_lastIndex++;
}

-- HashSet.cs line 977–990

AddIfNotPresent(T) has three operations that demand some computation: the call to object.GetHashCode(), calling object.Equals(object) when there is a collision, and IncreaseCapacity().  The actual adding of an element only incurs the cost of setting some pointers and some ints.

When the HashSet<T> needs to IncreaseCapacity() the capacity is at least doubled.  Therefore we can conclude that on average a HashSet<T> is filled for 75%.  If the hashes are evenly distributed, the expectancy of a hash collision is also 75%.

SetCapacity(int, bool), called by IncreaseCapacity(), is the most expensive: it allocates new arrays, it copies the old slot array to the new array, and it recalculates the bucket lists:

Slot[] newSlots = new Slot[newSize];
if (m_slots != null) {
    Array.Copy(m_slots, 0, newSlots, 0, m_lastIndex);
}

...

int[] newBuckets = new int[newSize];
for (int i = 0; i < m_lastIndex; i++) {
    int bucket = newSlots[i].hashCode % newSize;
    newSlots[i].next = newBuckets[bucket] - 1;
    newBuckets[bucket] = i + 1;
}
m_slots = newSlots;
m_buckets = newBuckets;

-- HashSet.cs line 929–949

Option 1 and 4 (new HashSet<T>(A.Union(B))) will result in slightly more calls to IncreaseCapacity().  The cost —without the cost of A.Union(B) or A.Concat(B)— is approximately O(log(|A∪B|) * |A∪B|).

Whereas when using option 2 (A.UnionWith(B)) or option 3 (HashSet<T> C = new HashSet<T>(A); C.UnionWith(B)) we get a 'discount' of log(|A|) on the cost: O((log(|A∪B|) - log(|A|)) * |A∪B|).  It pays (slightly) to use the largest set as the target into witch the other is merged.

Enumerable<T>.Union(IEnumerable<T>)

Enumerable<T>.Union(IEnumerable<T>) is implemented via UnionIterator<T>(IEnumerable<T>, IEnumerable<T>, IEqualityComparer<T>).

The UnionIterator uses Set<T> —an internal class in Enumerable.cs— that is very similar to HashSet<T>.  UnionIterator lazily Add(T)s items from A and B to this Set<T> and yields the elements if they could be added.  The work is done in Find(T, bool) which is similar to HashSet<T>.AddIfNotPresent(T).  Check if the element is already present:

int hashCode = InternalGetHashCode(value);
for (int i = buckets[hashCode % buckets.Length] - 1; i >= 0; i = slots[i].next) {
    if (slots[i].hashCode == hashCode && comparer.Equals(slots[i].value, value)) return true;
}

-- Enumerable.cs line 2423–2426

Find a free index and reserve a slot:

int index;
if (freeList >= 0) {
    index = freeList;
    freeList = slots[index].next;
}
else {
    if (count == slots.Length) Resize();
    index = count;
    count++;
}
int bucket = hashCode % buckets.Length;
slots[index].hashCode = hashCode;
slots[index].value = value;
slots[index].next = buckets[bucket] - 1;
buckets[bucket] = index + 1;

-- Enumerable.cs line 2428–2442

Resize() is similar to IncreaseCapacity().  The biggest difference between the two is that Resize() does not use a prime number for the number of buckets, so with bad GetHashCode() there is a slightly higher chance for collisions.  Code of Resize():

int newSize = checked(count * 2 + 1);
int[] newBuckets = new int[newSize];
Slot[] newSlots = new Slot[newSize];
Array.Copy(slots, 0, newSlots, 0, count);
for (int i = 0; i < count; i++) {
    int bucket = newSlots[i].hashCode % newSize;
    newSlots[i].next = newBuckets[bucket] - 1;
    newBuckets[bucket] = i + 1;
}
buckets = newBuckets;
slots = newSlots;

-- Enumerable.cs line 2448–2458

The performance cost of A.Union(B) is not significantly different from that of HashSet<T> C = new HashSet<T>(); C.UnionWith(A); C.UnionWith(B);.  In option 1 (new HashSet<T>(A.Union(B))) the same HashSet is created twice resulting in a very costly 2 * O(log(|A∪B|) * (|A∪B|)).  Option 4 results from knowing how HashSet<T>(IEnumerable<T>) and Enumerable.Union(IEnumerable<T>, IEnumerable<T>) are implemented.  It avoids the redundant A.Union(B) leading to a cost of O(log(|A∪B|) * |A∪B|).


问:
PHP Laravel 5 elseif not behaving as expected
I have 2 variables that can either be filled with a value, be 'all' or be 'null'

Variable 1 is $type and variable 2 is $brand.

So if the user selects a type and a brand I want to query the cars accordingly. If the users selects nothing then the value is 'null' if the user selects 'all' then the value is 'all' obviously.

I've wrote the 4 scenario's out in commented code as follows:

```<code>//brand                 and type                -> get cars of brand and type
//brand = all or null   and type = all or null  -> get all cars
//brand                 and type = all or null  -> get cars of all types and brand
//brand = all or null   and type                -> get cars of all brands and type
</code>```

this is my if structure:

```<code>if ($brand && $type) {
            $cars = Cars::where([
                ['cost', '<=', $budget],
                ['brand', '=', $brand],
                ['type', '=', $type]
            ])->get();
} elseif($brand == 'all' || $brand === null && $type == 'all' || $type === null) {
            $cars = Cars::where('cost', '<=', $budget)
                ->get();
} elseif($brand && $type == 'all' || $type === null) {
            $cars = Cars::where([
                ['cost', '<=', $budget],
                ['brand', '=', $brand],
            ])->get();
} elseif ($brand == 'all' || $brand === null && $type) {
            $cars = Cars::where([
                ['cost', '<=', $budget],
                ['type', '=', $type]
            ])->get();
}
</code>```

Now when I check the value of $brand it's filled with Audi and $type is null.

Can someone please explain to me why I get the result of the first elseif?
So my code thinks this is the case:

elseif($brand == 'all' || $brand === null && $type == 'all' || $type === null) {

Which is weird because $brand is neither 'all' or 'null' since it's 'Audi'

Hope it's clear.

答:
Because the way you wrote the condition is pretty wrong as I can understand!

'null' is not same as false or ''.'null' is an object.

Therefore, you can use it like:

$brand && $type
if(!empty($brand) && !empty($type))

Body:
I have 2 variables that can either be filled with a value, be 'all' or be 'null'

Variable 1 is $type and variable 2 is $brand.

So if the user selects a type and a brand I want to query the cars accordingly. If the users selects nothing then the value is 'null' if the user selects 'all' then the value is 'all' obviously.

I've wrote the 4 scenario's out in commented code as follows:

//brand                 and type                -> get cars of brand and type
//brand = all or null   and type = all or null  -> get all cars
//brand                 and type = all or null  -> get cars of all types and brand
//brand = all or null   and type                -> get cars of all brands and type

this is my if structure:

if ($brand && $type) {
            $cars = Cars::where([
                ['cost', '<=', $budget],
                ['brand', '=', $brand],
                ['type', '=', $type]
            ])->get();
} elseif($brand == 'all' || $brand === null && $type == 'all' || $type === null) {
            $cars = Cars::where('cost', '<=', $budget)
                ->get();
} elseif($brand && $type == 'all' || $type === null) {
            $cars = Cars::where([
                ['cost', '<=', $budget],
                ['brand', '=', $brand],
            ])->get();
} elseif ($brand == 'all' || $brand === null && $type) {
            $cars = Cars::where([
                ['cost', '<=', $budget],
                ['type', '=', $type]
            ])->get();
}

Now when I check the value of $brand it's filled with Audi and $type is null.

Can someone please explain to me why I get the result of the first elseif?
So my code thinks this is the case:

elseif($brand == 'all' || $brand === null && $type == 'all' || $type === null) {

Which is weird because $brand is neither 'all' or 'null' since it's 'Audi'

Hope it's clear.


问:
How can i get vCard from command line in Ejabberd 16.03
Recently i have updated my ejabberd version from 2.1.13 to 16.03. Now i have a problem, How can i get vCard from the Linux command terminal?

We have a module mod_ctlextra for this in previous versions of ejabberd (from 1.x.x to 2.13.x).

I have done many R&D but i get nothing for ejabberd latest version.

If there is any other module for this or the same module is still available for the latest version too, then please tell me.

答:
From ejabberdctl command line utility I can see

```<code>get_vcard user host name
    Get content from a vCard field

get_vcard2 user host name subname
    Get content from a vCard field

get_vcard2_multi user host name subname
    Get multiple contents from a vCard field
</code>```

But you need to have mod_admin_extra module enabled in your configuration file.

Body:
From ejabberdctl command line utility I can see

get_vcard user host name
    Get content from a vCard field

get_vcard2 user host name subname
    Get content from a vCard field

get_vcard2_multi user host name subname
    Get multiple contents from a vCard field

But you need to have mod_admin_extra module enabled in your configuration file.


问:
MySQL Select User id based on multiple AND conditions on same table
I want to select a userid from a single table based on multiple and condition.

```<code>UserID   FieldID  Value
-----------------------------------
1        51         Yes
1        6          Dog
2        6          Cat
1        68         TX
1        69         78701
2        68         LA
</code>```

What I'm trying to get in simple words:

if user search for texas or 78701,
Select userId where (68 = TX OR 69=78701) AND (51=yes) AND (6=Dog)

This should return user id 1.

This is what I tried, but returns null.

```<code>SELECT user_id FROM `metadata`
WHERE ( (`field_id` = '68' AND value LIKE '%TX%')
   OR (`field_id` = '69' AND value LIKE '%78701%') )
   AND `field_id` = '51' AND value = 'Yes'
   AND `field_id` = '6' AND value = 'Dog'
</code>```

答:
This approach is typically slower than simply LEFT JOINing that table on each criterion, but it can make the problem simpler to comprehend...

```<code>SELECT userid
     , MAX(CASE WHEN fieldid = 51 THEN value END) smoker
     , MAX(CASE WHEN fieldid =  6 THEN value END) favourite_pet
     , MAX(CASE WHEN fieldid = 68 THEN value END) state
     , MAX(CASE WHEN fieldid = 69 THEN value END) zip
  FROM eav
 GROUP
    BY userid;
</code>```

You can use HAVING, or bundle this into a subquery to get the desired results.

Body:
I want to select a userid from a single table based on multiple and condition.

UserID   FieldID  Value
-----------------------------------
1        51         Yes
1        6          Dog
2        6          Cat
1        68         TX
1        69         78701
2        68         LA

What I'm trying to get in simple words:

if user search for texas or 78701,
Select userId where (68 = TX OR 69=78701) AND (51=yes) AND (6=Dog)

This should return user id 1.

This is what I tried, but returns null.

SELECT user_id FROM `metadata`
WHERE ( (`field_id` = '68' AND value LIKE '%TX%')
   OR (`field_id` = '69' AND value LIKE '%78701%') )
   AND `field_id` = '51' AND value = 'Yes'
   AND `field_id` = '6' AND value = 'Dog'

Body:
This approach is typically slower than simply LEFT JOINing that table on each criterion, but it can make the problem simpler to comprehend...

SELECT userid
     , MAX(CASE WHEN fieldid = 51 THEN value END) smoker
     , MAX(CASE WHEN fieldid =  6 THEN value END) favourite_pet
     , MAX(CASE WHEN fieldid = 68 THEN value END) state
     , MAX(CASE WHEN fieldid = 69 THEN value END) zip
  FROM eav
 GROUP
    BY userid;

You can use HAVING, or bundle this into a subquery to get the desired results.


问:
Why is it a bad idea to manually wire OSGi services?
In order to favor certain service implementations over others, I wrote a customizable version of java.util.ServiceLoader (adds priority and enabled/disabled flag to implementations via preference files for non-OSGi code).

The client was pleased and wanted the same customization for OSGi service implementations.
The devised solution is based on calling getServiceReferences(Class<S> clazz, String filter) on BundleContext and uses a null filter to retrieve all implementations.

Nevertheless, fiddling around with OSGi on such a low level leaves a bad taste. There's much boilerplate code (e.g. mandatory subtypes of BundleActivator) and the used approach will also hinder an smooth upgrade to declarative services and some point in time.

I also read about the SERVICE_RANKING property, but compared to the preference files from the approach above, it has the drawback that each implementation sets its own ranking property and it's not possible to change the ranking afterwards.

So my question is: What are good arguments against this low-level approach? Why should declarative services be used instead?

答:
At the core OSGi is a dynamic environment. Bundles and services can come and go at every moment (theoretically). So the only way to cope with this environment is to react on changes compared to waiting for something to happen.

For example a declarative services component will come up once all its mandatory services are present and will vanish if one goes away.
A solution based on service loader or similar will actively get the services that are available if such a service is mandatory then you will have to block until it is available. This can easily lead to deadlocks in the application.

Of course in practice the application is normally not so dynamic. In most cases this only affects the startup of the application. So in many cases the blocking behaviour can work but it will produce an application that is inherently fragile.

On the other hand if you have the problem that your application needs to run inside and outside of OSGi then DS is problematic as it relies on OSGi to be present.
Typical examples are Aapache CXF and Apache Camel. Both do not use DS and instead invented different abstractions for usage in OSGi and both sometimes have problems in OSGi exactly because of this. Still it would be difficult to improve this as they need to work outside of OSGi too.


问:
Implementing the IComparable Interface
I'm reading the book c#6.0 in a Nutshell now, the code below is on topic "Implementing the IComparable Interfaces".

I don't get a few things:

Why the IComparable.CompareTo is implemented explicitly there ?

What if it would be just another implicit overload of CompareTo (one implicit
int CompareTo (Note other), another one implicit int CompareTo (object other) ?

public struct Note : IComparable<Note>, IEquatable<Note>, IComparable
{
   int _semitonesFromA;
   public int SemitonesFromA { get { return _semitonesFromA; } }

   public Note (int semitonesFromA)
   {
     _semitonesFromA = semitonesFromA;
   }

   public int CompareTo (Note other) // Generic IComparable<T>
   {
   if (Equals (other)) return 0; // Fail-safe check
   return _semitonesFromA.CompareTo (other._semitonesFromA);
   }

   int IComparable.CompareTo (object other) // Nongeneric IComparable
   {
   if (!(other is Note))
   throw new InvalidOperationException ("CompareTo: Not a note");
   return CompareTo ((Note) other);
   }

   public static bool operator < (Note n1, Note n2)
     => n1.CompareTo (n2) < 0;

   public static bool operator > (Note n1, Note n2)
     => n1.CompareTo (n2) > 0;

   public bool Equals (Note other) // for IEquatable<Note>
     => _semitonesFromA == other._semitonesFromA;

   public override bool Equals (object other)
   {
   if (!(other is Note)) return false;
   return Equals ((Note) other);
   }

   public override int GetHashCode() => _semitonesFromA.GetHashCode();
   public static bool operator == (Note n1, Note n2) => n1.Equals (n2);
   public static bool operator != (Note n1, Note n2) => !(n1 == n2);
}
```

答:
You could implement IComparable implicitly, yes. But fundamentally you want to try to discourage users from comparing a Note with anything other than another Note. You may have legacy usages if IComparable, but if anything knows about the Note class directly, you don't want to allow:

```<code>Note note = new Note();
Other other = new Other();
int result = note.CompareTo(other);
</code>```

You know that that's always going to throw an exception, so why allow it at all? Basically, regard the non-generic IComparable interface as "somewhat legacy" (there are valid uses, but...) and discourage anyone from using it by implementing it explicitly.

Title: Implementing the IComparable Interface

Body:
You could implement IComparable implicitly, yes. But fundamentally you want to try to discourage users from comparing a Note with anything other than another Note. You may have legacy usages if IComparable, but if anything knows about the Note class directly, you don't want to allow:

Note note = new Note();
Other other = new Other();
int result = note.CompareTo(other);

You know that that's always going to throw an exception, so why allow it at all? Basically, regard the non-generic IComparable interface as "somewhat legacy" (there are valid uses, but...) and discourage anyone from using it by implementing it explicitly.


问:
How to set a default entity property value with Hibernate
How do I set a default value in Hibernate field?</p>

答: Use @ColumnDefault() annotation. This is hibernate only though.