问:
Apply operations on groupBy result of stream
I have a List of fruit which contains name and ID

```<code>List<Fruit> fruitList = Arrays.asList(new Fruit("apple", 1), new Fruit("orange", 2), new Fruit("orange", 3));
</code>```

I want to rename the fruit name with name_Id only if duplicate fruit name exists like in case of my list orange will rename to orange_2 and orange_3 but the apple will remain apple..
How can I do it in single stream expression.

The solution that I came up with is

```<code>Map<String, List<Fruit>> fruitMap = fruitList.stream().collect(Collectors.groupingBy(Fruit::getName));

        Set<Entry<String, List<Fruit>>> entry = fruitMap.entrySet();

        for (Entry<String, List<Fruit>> en : entry) {
            List<Fruit> fruit = en.getValue();
            if (fruit.size() > 1) {
                fruit.stream().map(d -> {
                    d.setName(d.getName() + "_" + d.getId());
                    return d;
                }).collect(Collectors.toList());
            }
        }
    }
</code>```

but this is way more than one stream expression.

答:
Below is the code I came up with, but it is still in 2 expression</p>

```<code>Map<String, Long> fruitMap = fruitList.stream()
                .collect(Collectors.groupingBy(Fruit::getName, Collectors.counting()));

        fruitList.forEach(f -> {
            if (fruitMap.get(f.getName()) > 1) {
                f.setName(f.getName() + "_" + f.getId());
            }
        });
</code>```

Body:
I have a List of fruit which contains name and ID

List<Fruit> fruitList = Arrays.asList(new Fruit("apple", 1), new Fruit("orange", 2), new Fruit("orange", 3));

I want to rename the fruit name with name_Id only if duplicate fruit name exists like in case of my list orange will rename to orange_2 and orange_3 but the apple will remain apple..
How can I do it in single stream expression.

The solution that I came up with is

Map<String, List<Fruit>> fruitMap = fruitList.stream().collect(Collectors.groupingBy(Fruit::getName));

        Set<Entry<String, List<Fruit>>> entry = fruitMap.entrySet();

        for (Entry<String, List<Fruit>> en : entry) {
            List<Fruit> fruit = en.getValue();
            if (fruit.size() > 1) {
                fruit.stream().map(d -> {
                    d.setName(d.getName() + "_" + d.getId());
                    return d;
                }).collect(Collectors.toList());
            }
        }
    }

but this is way more than one stream expression.

Body:
Below is the code I came up with, but it is still in 2 expression

Map<String, Long> fruitMap = fruitList.stream()
                .collect(Collectors.groupingBy(Fruit::getName, Collectors.counting()));

        fruitList.forEach(f -> {
            if (fruitMap.get(f.getName()) > 1) {
                f.setName(f.getName() + "_" + f.getId());
            }
        });


来源: stackexchange

问:
Why is goto poor practise?

This question is a duplicate of  Goto Still Considered Harmful. If you wish to discuss this further please use the original question.

Why exactly is GOTO poor programming practise? It makes sense on some occasions to use it.

答: It can rapidly lead to spaghetti code.</p>

ContentLicense: CC BY-SA 2.5

Title: Why is goto poor practise?

LastEditorDisplayName: Rich B

Body: It can rapidly lead to spaghetti code.

OwnerDisplayName: Richard E


问:
Jquery accordion
I have set up jQuery accordion in my page as

```<code>$(document).ready(function() {
        $("#MGH").accordion('activate', 1);
    });
</code>```

Now inside this div I have one button onclick of which I will validate and show some alert.
My problem is whenever I am clicking ok in the alert this accordion is getting fired.How to prevent this?

答: Sounds like you need event.stopPropagation</p>

ContentLicense: CC BY-SA 3.0

Title: Jquery accordion

Body:
I have set up jQuery accordion in my page as

$(document).ready(function() {
        $("#MGH").accordion('activate', 1);
    });

Now inside this div I have one button onclick of which I will validate and show some alert.
My problem is whenever I am clicking ok in the alert this accordion is getting fired.How to prevent this?


问:
Programmatically bill PayPal for a recurring payment
How to programmatically (not manually with our PayPal dashboard) bill (every month) a PayPal subscriber of our service for a non-fixed-amount Automatic Billing?

答:
I would recommend PayPal's Reference Transactions to achieve your purpose. Please check below link for its details.

https://developer.paypal.com/docs/classic/express-checkout/integration-guide/ECReferenceTxns/


问:
Selected row to column
I have following Table :

but need to select following result ,Also be notice that may items are not fixed!!

答:
One solution, continue to N :

```<code>select distinct f1.parentfk, f2.Quantity  , f3.Quantity, f4.Quantity, f5.Quantity
from mytable f1
left outer join mytable f2 on f1.parentfk=f2.parentfk and f2.itemfk=1
left outer join mytable f3 on f1.parentfk=f3.parentfk and f3.itemfk=2
left outer join mytable f4 on f1.parentfk=f4.parentfk and f4.itemfk=3
left outer join mytable f5 on f1.parentfk=f5.parentfk and f5.itemfk=4
</code>```

Or try this dynamic query :

```<code>DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX);

SET @columns = N'';

SELECT @columns += N', p.' + QUOTENAME(itemfk) FROM (SELECT distinct f2.itemfk FROM Mytable f2) AS x;

SET @sql = N'
SELECT j.ParentFk, ' + STUFF(@columns, 1, 2, '') + '
FROM
(
  SELECT ParentFk, Quantity, itemfk FROM Mytable
) AS j
PIVOT
(
  Sum(Quantity) FOR itemfk IN ('
  + STUFF(REPLACE(@columns, ', p.[', ',['), 1, 1, '')
  + ')
) AS p;';

PRINT @sql;

EXEC sp_executesql @sql;
</code>```

Title: Selected row to column

Body:
One solution, continue to N :

select distinct f1.parentfk, f2.Quantity  , f3.Quantity, f4.Quantity, f5.Quantity
from mytable f1
left outer join mytable f2 on f1.parentfk=f2.parentfk and f2.itemfk=1
left outer join mytable f3 on f1.parentfk=f3.parentfk and f3.itemfk=2
left outer join mytable f4 on f1.parentfk=f4.parentfk and f4.itemfk=3
left outer join mytable f5 on f1.parentfk=f5.parentfk and f5.itemfk=4

Or try this dynamic query :

DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX);

SET @columns = N'';

SELECT @columns += N', p.' + QUOTENAME(itemfk) FROM (SELECT distinct f2.itemfk FROM Mytable f2) AS x;

SET @sql = N'
SELECT j.ParentFk, ' + STUFF(@columns, 1, 2, '') + '
FROM
(
  SELECT ParentFk, Quantity, itemfk FROM Mytable
) AS j
PIVOT
(
  Sum(Quantity) FOR itemfk IN ('
  + STUFF(REPLACE(@columns, ', p.[', ',['), 1, 1, '')
  + ')
) AS p;';

PRINT @sql;

EXEC sp_executesql @sql;


问:
HTML Table Sort Customised Column Sort
I have a table where I want to sort a column "BugId".

The inbuilt bootstrap sorting sorts in a particular fashion where ID-1 is followed by ID-11,then ID-12 and so on,(in an alphabetic fashion) whereas I want ID-1 to be followed by ID-2, then ID-3 ....ID-11 and so on.(in a numerical fashion)

This is how my table looks:

```<code><table id="myTable" class="footable table table-striped toggle-arrow-tiny m-xxs" data-page-size="1000">
 <thead>
  <tr>
     <th >Bug ID</th>
     <th>Component</th>
     <th data-sort-ignore="true">Report Date</th>
  </tr>
</thead>
<tbody></tbody>
</table>
</code>```

Can I change the sorting for only one column in this fashion?

答:
```<code><table data-toggle="table" id="myTable" class="footable table table-striped toggle-arrow-tiny m-xxs" data-page-size="1000">
 <thead>
  <tr>
     <th data-field="bugid" data-sortable="true" data-sort-name="_bugid_data" data-sorter="bugidsorter" >Bug ID</th>
     <th data-field="component" data-sortable="true"  >Component</th>
     <th data-sort-ignore="true">Report Date</th>
  </tr>

</thead>
<tbody><tr>
      <td data-bugid="1">id-1</td>
      <td >x</td>
      <td>11/12/2015</td>
    </tr>
      <tr>
      <td data-bugid="2" >id-2</td>
      <td >a</td>
      <td>11/12/2015</td>
    </tr>
    <tr>
      <td data-bugid="3">id-3</td>
      <td >b</td>
      <td>11/12/2015</td>
    </tr>
    <tr>
      <td data-bugid="4">id-4</td>
      <td >c</td>
      <td>11/12/2015</td>
    </tr>
    <tr>
      <td data-bugid="5">id-5</td>
      <td >d</td>
      <td>11/12/2015</td>
    </tr>
    <tr>
      <td data-bugid="6">id-6</td>
      <td >e</td>
      <td>11/12/2015</td>
    </tr>
      <tr>
      <td data-bugid="10">id-10</td>
      <td >e</td>
      <td>11/12/2015</td>
    </tr>
    </tbody>
</table>
</code>```

sorting function

```<code>function bugidsorter(a, b) {
console.log(a);
    if (a.bugid < b.bugid) return -1;
    if (a.bugid > b.bugid) return 1;
    return 0;
}
</code>```

fiddle

Title: HTML Table Sort Customised Column Sort

Body:
I have a table where I want to sort a column "BugId".

The inbuilt bootstrap sorting sorts in a particular fashion where ID-1 is followed by ID-11,then ID-12 and so on,(in an alphabetic fashion) whereas I want ID-1 to be followed by ID-2, then ID-3 ....ID-11 and so on.(in a numerical fashion)

This is how my table looks:

     Bug ID
     Component
     Report Date

Can I change the sorting for only one column in this fashion?

Body:
<table data-toggle="table" id="myTable" class="footable table table-striped toggle-arrow-tiny m-xxs" data-page-size="1000">
 <thead>
  <tr>
     <th data-field="bugid" data-sortable="true" data-sort-name="_bugid_data" data-sorter="bugidsorter" >Bug ID</th>
     <th data-field="component" data-sortable="true"  >Component</th>
     <th data-sort-ignore="true">Report Date</th>
  </tr>

</thead>
<tbody><tr>
      <td data-bugid="1">id-1</td>
      <td >x</td>
      <td>11/12/2015</td>
    </tr>
      <tr>
      <td data-bugid="2" >id-2</td>
      <td >a</td>
      <td>11/12/2015</td>
    </tr>
    <tr>
      <td data-bugid="3">id-3</td>
      <td >b</td>
      <td>11/12/2015</td>
    </tr>
    <tr>
      <td data-bugid="4">id-4</td>
      <td >c</td>
      <td>11/12/2015</td>
    </tr>
    <tr>
      <td data-bugid="5">id-5</td>
      <td >d</td>
      <td>11/12/2015</td>
    </tr>
    <tr>
      <td data-bugid="6">id-6</td>
      <td >e</td>
      <td>11/12/2015</td>
    </tr>
      <tr>
      <td data-bugid="10">id-10</td>
      <td >e</td>
      <td>11/12/2015</td>
    </tr>
    </tbody>
</table>

sorting function

function bugidsorter(a, b) {
console.log(a);
    if (a.bugid < b.bugid) return -1;
    if (a.bugid > b.bugid) return 1;
    return 0;
}

fiddle


问:
how to associate vibration with a button click
I have to following code

```<code>-(IBAction)doVibrate{
    [self vibrate];
}
-(void)vibrate{
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
</code>```

both doVibrate and vibrate are is same class .but when i am clicking the button associated to the doVibrate it device not vibrating .
I have imported the AudioToolbox/AudioToolbox.h and AVFoundation/AVFoundation.

Can some one tell me where i am wrong.
Thanks

答:
IBActions are usually of the following form:

```<code>- (IBAction)vibrate:(id)sender;
</code>```

Note that the following 3 methods are all different:

```<code>- (IBAction)vibrate:(id)sender;
- (IBAction)vibrate; // no sender argument
- (void)doVibrate;
</code>```

Here is what I would do. In your .h file, define the following method:

```<code>- (IBAction)vibrate:(id)sender;
// - (IBAction)vibrate;  comment out this method
</code>```

In your .m file, do the following:

```<code>- (IBAction)vibrate:(id)sender {
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
</code>```

Now, when you save your .h and .m files, and switch back to your nib/xib file in Interface Builder, it may show a yellow warning message that "'vibrate' is no longer defined in "your class name here'. That's okay, as the following should remove that error. Control-click (or right-click) on the button and drag to your controller class and choose "vibrate:" as the method name to call (note the colon, :, in the method name).

Body:
I have to following code

-(IBAction)doVibrate{
    [self vibrate];
}
-(void)vibrate{
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}

both doVibrate and vibrate are is same class .but when i am clicking the button associated to the doVibrate it device not vibrating .
I have imported the AudioToolbox/AudioToolbox.h and AVFoundation/AVFoundation.

Can some one tell me where i am wrong.
Thanks

Body:
IBActions are usually of the following form:

- (IBAction)vibrate:(id)sender;

Note that the following 3 methods are all different:

- (IBAction)vibrate:(id)sender;
- (IBAction)vibrate; // no sender argument
- (void)doVibrate;

Here is what I would do. In your .h file, define the following method:

- (IBAction)vibrate:(id)sender;
// - (IBAction)vibrate;  comment out this method

In your .m file, do the following:

- (IBAction)vibrate:(id)sender {
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}

Now, when you save your .h and .m files, and switch back to your nib/xib file in Interface Builder, it may show a yellow warning message that "'vibrate' is no longer defined in "your class name here'. That's okay, as the following should remove that error. Control-click (or right-click) on the button and drag to your controller class and choose "vibrate:" as the method name to call (note the colon, :, in the method name).


问:
How to show the image name as the title of the window in matlab
How to get the name of the image as the title of the window when using imshow in matlab.

Eg: I use the following code as to show the original image and the skeletonized image.

```<code>figure
subplot(1,2,1)
imshow(BW_Original)
subplot(1,2,2)
imshow(BW_Thinned)
</code>```

I want to show the image name as the title of the window that pop ups. Can someone help me with this. Thank you.

答:
You can set the name of the figure when calling figure

```<code>figure('name', 'BW comparison image name here')
subplot(1,2,1); imshow(BW_Original);
subplot(1,2,2); imshow(BW_Thinned);
</code>```

Gnovice also mentions that you might want to remove the figure number from the name, this can be done when calling figure too:

```<code>figure('name', 'BW comparison image name here', 'numbertitle', 'off')
</code>```

Body:
How to get the name of the image as the title of the window when using imshow in matlab.

Eg: I use the following code as to show the original image and the skeletonized image.

figure
subplot(1,2,1)
imshow(BW_Original)
subplot(1,2,2)
imshow(BW_Thinned)

I want to show the image name as the title of the window that pop ups. Can someone help me with this. Thank you.

Body:
You can set the name of the figure when calling figure

figure('name', 'BW comparison image name here')
subplot(1,2,1); imshow(BW_Original);
subplot(1,2,2); imshow(BW_Thinned);

Gnovice also mentions that you might want to remove the figure number from the name, this can be done when calling figure too:

figure('name', 'BW comparison image name here', 'numbertitle', 'off')


问:
Message: unlink(/tmp/ci_session0189a7f1c86eb18fb70afcfedc2d5040e9c23146): Operation not permitted
I am getting error not regularly but after time intervals:

Message:
  unlink(/tmp/ci_session0189a7f1c86eb18fb70afcfedc2d5040e9c23146):
  Operation not permitted

In config I tried:

```<code>$config['sess_save_path'] = sys_get_temp_dir();
</code>```

Also tried:-

In config:

```<code>$config['sess_save_path'] = BASE_URL.'application/temp/';
</code>```

also changed the permission of it (755 & 777)

Though not getting resolved..

答:
Use FCPATH or APPPATH

Location application > temp

```<code>$config['sess_save_path'] = APPPATH . 'temp/';
</code>```

OR

```<code>$config['sess_save_path'] = FCPATH . 'application/temp/';
</code>```

Folder permission for sessions 0700

```<code>EXT: The PHP file extension
FCPATH: Path to the front controller (this file) (root of CI)
SELF: The name of THIS file (index.php)
BASEPATH: Path to the system folder
APPPATH: The path to the "application" folder
</code>```

Body:
I am getting error not regularly but after time intervals:

Message:
  unlink(/tmp/ci_session0189a7f1c86eb18fb70afcfedc2d5040e9c23146):
  Operation not permitted

In config I tried:

$config['sess_save_path'] = sys_get_temp_dir();

Also tried:-

In config:

$config['sess_save_path'] = BASE_URL.'application/temp/';

also changed the permission of it (755 & 777)

Though not getting resolved..

Body:
Use FCPATH or APPPATH

Location application > temp

$config['sess_save_path'] = APPPATH . 'temp/';

OR

$config['sess_save_path'] = FCPATH . 'application/temp/';

Folder permission for sessions 0700

EXT: The PHP file extension
FCPATH: Path to the front controller (this file) (root of CI)
SELF: The name of THIS file (index.php)
BASEPATH: Path to the system folder
APPPATH: The path to the "application" folder


问:
Jest returns "Network Error" when doing an authenticated request with axios
This seems a bit weird to me. I'm trying to test an actual (ie. real network) request with Jest.

These are the tested scenarios:

Test an external API (fixer.io) with no headers   <--- This works

Test a local API server with headers   <--- This does NOT work

Test same local API with headers from node terminal  <--- This works

What could be the reason behind this behavior? And what is the solution?

```<code>//This WORKS
test('testing no headers', () => {
  return axios.get('http://api.fixer.io/latest')
        .then( res => console.log(res) )
});

//This DOES NOT work
test('testing no headers', () => {
  return axios.get('http://localhost:3000/users/4/profile',
                      {headers:{authorization:`Bearer ${mytoken}`}})
        .then( res => console.log(res) )
});

//...

//Node Terminal
//This WORKS
> axios.get('http://localhost:3000/users/4/profile',
                   {headers:{authorization:`Bearer ${mytoken}`}})
        .then( res => console.log(res) )
</code>```

答:
It can be a Jest configuration issue. I solved forcing "node" as jest environment in package.json:

"jest": {
    "testEnvironment": "node"
  }

see docs: https://facebook.github.io/jest/docs/configuration.html#testenvironment-string

ContentLicense: CC BY-SA 4.0

Body:
This seems a bit weird to me. I'm trying to test an actual (ie. real network) request with Jest.

These are the tested scenarios:

Test an external API (fixer.io) with no headers   <--- This works

Test a local API server with headers   <--- This does NOT work

Test same local API with headers from node terminal  <--- This works

What could be the reason behind this behavior? And what is the solution?

//This WORKS
test('testing no headers', () => {
  return axios.get('http://api.fixer.io/latest')
        .then( res => console.log(res) )
});

//This DOES NOT work
test('testing no headers', () => {
  return axios.get('http://localhost:3000/users/4/profile',
                      {headers:{authorization:`Bearer ${mytoken}`}})
        .then( res => console.log(res) )
});

//...

//Node Terminal
//This WORKS
> axios.get('http://localhost:3000/users/4/profile',
                   {headers:{authorization:`Bearer ${mytoken}`}})
        .then( res => console.log(res) )


问:
Multiple BackgroundWorker throws timeout exception
If I keep two FileDownload (find code in below link) in Pause mode and if I start 3rd third instance of Filedownload, I am getting timeout error.

I am working on a WPF application where I need to download multiple .zip files from a CDN server. I am using following code to download file.

https://www.codeproject.com/Articles/35954/C-NET-Background-File-Downloader?msg=5402177#xx5402177xx

In my case I have to download multiple files simultaneously and to show progress for each file downloading. I am creating an instance of FileDownloader (find code in below link) class each time when user downloads a file.

I am facing operation timeout error, when I am keeping two instances of FileDownloader on Puase mode and when I start 3rd instance. The 3rd instance continuously waiting at webResp = (HttpWebResponse)webReq.GetResponse(); and after sometime it throws operation timeout error.

If I try to download same zip files through chrome browser, and if keep first to on pause still the 3rd file getting downloaded.

Any suggestions, how to resolve the issue?

答:
Resolved the issue, by default the number of connection an application can open are 2 but with below line of code you can set it to higher number. It can also be done in app.config

https://msdn.microsoft.com/en-us/library/fb6y0fyc(v=vs.110).aspx

```<code>ServicePointManager.DefaultConnectionLimit = 65000;
</code>```

Body:
Resolved the issue, by default the number of connection an application can open are 2 but with below line of code you can set it to higher number. It can also be done in app.config

https://msdn.microsoft.com/en-us/library/fb6y0fyc(v=vs.110).aspx

ServicePointManager.DefaultConnectionLimit = 65000;


问:
How to package my android app with a database
I've already created an android application that has got an already existing sqlite 3 database within it's asset's folder. I designed the application to copy the database on to the mobile when the app is launched for the first time. My question is how can I ship the database and the app so that users can easily install the app?

thanks

答:
The method I'm going to show you takes
  your own SQLite database file from the
  "assets" folder and copies into the
  system database path of your
  application so the SQLiteDatabase API
  can open and access it normally.

Have a look here : Using your own sqlite database in your Android applications


问:
error trying to set up basic chat app with node.js
I am trying to set up a basic chat app with node.js/express/socket.io but for some reason when the client sends message (this works, another client will get the message) it also refreshes the client and the url goes from localhost:3000 to localhost:3000/? (adds /? to end, i don't know what this means). I cant find anything wrong in my code after looking at it for hours. I have:

server.js:

```<code>let app = require('express')();
let http = require('http').Server(app);
let io = require('socket.io')(http);
let port = process.env.PORT || 3000;

app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html') });

http.listen(port,() => { console.log('listening on *:' + port) });

    io.on('connection', socket => {
        socket.on('chat', text => {
        io.sockets.emit('chat', `<p>${text}</p>`);
    });

});
</code>```

index.html:

```<code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<style>
    .chat_view{
        height: 300px;
        width: 200px;
        border: 5px ridge black;
        overflow-y: scroll;
    }
</style>
</head>
<body>
<div class="chat" id="chat">
    <div class="chat_view" id="chat_view">
    </div>
    <form id="chat_form">
        <input type="text" title="chat_input" id="chat_input" style="width: 206px">
    </form>
</div>
<script>
let socket = io();

$('#chat_form').submit( () => {
    let text = $('#chat_input').val();
    socket.emit('chat', text);
});

socket.on('chat', text => {
    let chat_view = document.getElementById('chat_view');
        chat_view.innerHTML += text;
        chat_view.scrollTop = chat_view.scrollHeight;
});

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

and package.json:

```<code>{
  "name": "RatScrew",
  "version": "0.0.1",
  "dependencies": {
    "express": "^4.15.3",
    "socket.io": "^2.0.2"
  }
}
</code>```

答:
Change your code to:

```<code>$('#chat_form').submit((event)=>{
    event.preventDefault();
    let text = $('#chat_input').val();
    socket.emit('chat', text);
});
</code>```

The default method used when submiting the form is the GET method, which makes the server send index.html again and the page refreshes.

You may want to have a look at https://www.w3.org/TR/html401/interact/forms.html

Body:
I am trying to set up a basic chat app with node.js/express/socket.io but for some reason when the client sends message (this works, another client will get the message) it also refreshes the client and the url goes from localhost:3000 to localhost:3000/? (adds /? to end, i don't know what this means). I cant find anything wrong in my code after looking at it for hours. I have:

server.js:

let app = require('express')();
let http = require('http').Server(app);
let io = require('socket.io')(http);
let port = process.env.PORT || 3000;

app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html') });

http.listen(port,() => { console.log('listening on *:' + port) });

    io.on('connection', socket => {
        socket.on('chat', text => {
        io.sockets.emit('chat', `<p>${text}</p>`);
    });

});

index.html:

<!DOCTYPE html>

<meta charset="UTF-8">

    <form id="chat_form">
        <input type="text" title="chat_input" id="chat_input" style="width: 206px">
    </form>

and package.json:

{
  "name": "RatScrew",
  "version": "0.0.1",
  "dependencies": {
    "express": "^4.15.3",
    "socket.io": "^2.0.2"
  }
}

Body:
Change your code to:

$('#chat_form').submit((event)=>{
    event.preventDefault();
    let text = $('#chat_input').val();
    socket.emit('chat', text);
});

The default method used when submiting the form is the GET method, which makes the server send index.html again and the page refreshes.

You may want to have a look at https://www.w3.org/TR/html401/interact/forms.html


问:
maven install shows error but when i execute maven -X install build success
I have a java maven application when i execute the command mvn install it shows compilation error stating that the particular user defined package is not found. When i execute build maven from eclipse by passing -X clean install in goals it passes.

I am passing an User-defined Java object to the method as parameters(I am using the same process for different method with the same object it worked) but wen i create a new method it fails.
maven 3.5 version

any help would be appreciated

答:
i found the issue was with the pom.xml where they build two different goals one to compile the main files and the other is to compile class files. I wrongly added the test beans to main project rather than it must be in test side. So, at the time of compilation first it compiles the main files these test beans binaries would not be available in the heap so it fails.
now the issue has been resolved. Thanks for the help @DarsanMetha and @khmarbaise</p>


问:
How to interactively add files in Perforce (equivalent of `git add -p`)
Is there something in Perforce that works like git add -p?

I'd like to diff my local file against the depot, and then choose which parts of the diff will end up in the changelist.

(My goal here is to take multiple changes I've made to a file and commit them in two separate changelists, since they're not conceptually related. But you could also use this to not commit debug code but still leave it in locally).

答:
Perforce does not have git's concept of a staging area, so an equivalent of git add -p doesn't really make sense (where do you want the non-added edits to go?  Into a shelved change?)

Personally I use git-p4 and to create a git mirror of a Perforce tree, and then I can actually use git add -p. (You alternatively might want to look into Perforce's Git Fusion system.)


问:
Why is the ajax function not executing when I click on the 'like' image?
I have a picture of a like button, when clicked, should update the score by 1.
I am using ajax to execute this.
However, when I click the image nothing happens. When I hover my mouse on the image, the pointer does not even change to a hand.

index.php

```<code><!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="css/style.css"></link>
        <script src="js/jquery-1.11.3.min.js"></script>
        <script src="js/script.js"></script>
    </head>
<body>

    Welcome: <?php
        // Start the session
        session_start();
        //Use session variable created in login.php
        echo $_SESSION['username'];
    ?>

    <div class="friend">
    <?php
        while($row = $res->fetch_assoc())
        {
            echo "<image class='img' src='images/" .$row['image'] . "'></image>";
            echo "<div class='info'>";
            echo $row['name'] . "<br>";
            echo $row['surname'] . "<br>";
            echo "SCORE: " . ($row['likes'] - $row['dislikes']);
            echo "</div>";

        }
    ?>

    <div class='friend_actions'>
            <image class='button' id='likes' src='images/like.jpg'></image><br>
            <image class='button' id='dislikes' src='images/dislike.jpg'></image>
    </div>

</body>
</code>```

script.js

```<code>$(document).ready(function () {

    $('#likes').click(function() {
        $.ajax({
            url: 'likes.php',
            type:'post',
            data: {id: $('#id').val()},
            success: function (result)
            {
                //Reload the current document
                location.reload();
            }

        });

});
</code>```

likes.php

```<code><?php
    require "php/conn.php";

    $db->query("UPDATE friends_list SET likes = likes + 1 WHERE id = 1");
?>
</code>```

答:
```<code>Here syntax error in script writing check
this your code
$(document).ready(function () {
$('#likes').click(function() {
    $.ajax({
        url: 'likes.php',
        type:'post',
        data: {id: $('#id').val()},
        success: function (result)
        {
            //Reload the current document
            location.reload();
        }
});  //this end of ajax
}); //end of like event function
 where is document end ?
 you can not complete document '});' so complete document function
</code>```

Body:
I have a picture of a like button, when clicked, should update the score by 1.
I am using ajax to execute this.
However, when I click the image nothing happens. When I hover my mouse on the image, the pointer does not even change to a hand.

index.php

<!DOCTYPE html>

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

    Welcome: <?php
        // Start the session
        session_start();
        //Use session variable created in login.php
        echo $_SESSION['username'];
    ?>

    <?php
        while($row = $res->fetch_assoc())
        {
            echo "<image class='img' src='images/" .$row['image'] . "'></image>";
            echo "
";
            echo $row['name'] . "
";
            echo $row['surname'] . "
";
            echo "SCORE: " . ($row['likes'] - $row['dislikes']);
            echo "
";

        }
    ?>

            <image class='button' id='likes' src='images/like.jpg'></image>

            <image class='button' id='dislikes' src='images/dislike.jpg'></image>

script.js

$(document).ready(function () {

    $('#likes').click(function() {
        $.ajax({
            url: 'likes.php',
            type:'post',
            data: {id: $('#id').val()},
            success: function (result)
            {
                //Reload the current document
                location.reload();
            }

        });

});

likes.php

<?php
    require "php/conn.php";

    $db->query("UPDATE friends_list SET likes = likes + 1 WHERE id = 1");
?>


问:
Find indexes of nonuniform sample with np.random.choice
Let's say I have a positions information in the form a two large 1D arrays X and Y. I want to sample non-uniformly positions from these arrays.
I thought I could do this with np.random.choice, but since it only accepts 1D arrays and I cannot do:

Xsample = np.random.choice(X, n, p)

Ysample = np.random.choice(Y, n, p)

with n number of points in the sample, and p a probability array, since this will sample different points for Xsample and Ysample, I am left with finding a way to obtain the indexes of one sampling. The problem is that there is no guarantee that the numbers in the lists are unique so cannot quite use np.where.

Any thoughts?

答:
Doh, I can just sample from the indexes.
Here's a working example:</p>

```<code>X = np.array([1, 2, 3, 4, 5])
Y = np.array([11, 12, 13, 14, 15])
p = [0.25, 0., 0.5, 0.25]

sample_idxs = np.random.choice(arange(len(X)), 2, p)
# can also be
# sample_idxs = np.random.choice(len(X), 2, p)
sample_idxs
> array([2, 4])

X[sample_idxs]
> array([3, 5])

Y[sample_idxs]
> array([13, 15])
</code>```

Body:
Doh, I can just sample from the indexes.
Here's a working example:

X = np.array([1, 2, 3, 4, 5])
Y = np.array([11, 12, 13, 14, 15])
p = [0.25, 0., 0.5, 0.25]

sample_idxs = np.random.choice(arange(len(X)), 2, p)
# can also be
# sample_idxs = np.random.choice(len(X), 2, p)
sample_idxs
> array([2, 4])

X[sample_idxs]
> array([3, 5])

Y[sample_idxs]
> array([13, 15])


问:
Angular-js datepicker flowing out of the form window
I have added a date-picker in my webpage but when i click on the calendar icon the date-picker is flowing out of the window, it looks odd to see. tried to reduce width, its not working. I have added the CSS file also.

```<!DOCTYPE html>

    <title></title>
    <meta charset="utf-8" />

                Status! {{ObjStatus}}

                <button type="button" class="btn btn-success pull-right" style="margin:1em" ng-click="editObj()" value="Edit" ng-show="Complete">Edit</button>
                <button type="button" class="btn btn-info pull-right" style="margin:1em" ng-click="requestReview()" value="Submit" ng-hide="Review">Submit</button>
                <button type="button" class="btn btn-success pull-right"style="margin:1em" ng-click="saveAllObj()" value="Save" ng-hide="Review">Save</button>

                    <button type="button" id="menuTab1" class="btn btn-default  btn-primary active" ng-click="tab1()" href="#tab1" data-toggle="tab">

Focus on Customer

                    </button>

                    <button type="button" id="menuTab2" class="btn btn-default" ng-click="tab2()" href="#tab2" data-toggle="tab">

Focus on Growth

                    </button>

                    <button type="button" id="menuTab3" class="btn btn-default" ng-click="tab3()" href="#tab3" data-toggle="tab">

Focus on Performance

                    </button>

                                            <input type="button" class="btn btn-primary pull-right" ng-click="saveObj()" value="Save">

                                                    <input type="checkbox" ng-model="selectedAllObj" ng-click="checkAllObj()" />
                                                    Individual Objectives
                                                    Measurable Outcomes
                                                    Priority %
                                                    Key Activities
                                                    Completed By

                                                    Individual Objectives
                                                    Measurable Outcomes
                                                    Priority %
                                                    Key Activities
                                                    Completed By

                                                        <input type="checkbox" ng-model="objectivesDetail.selected" />

                                                        <textarea class="form-control" rows="5" id="Individualid" ng-model="objectivesDetail.Individual" ></textarea>

                                                        <textarea class="form-control" rows="5"  id="Measurableid" ng-model="objectivesDetail.Measurable" ></textarea>

                                                        <textarea class="form-control" rows="1" cols="1" id="Priorityid" ng-model="objectivesDetail.Priority" ></textarea>

                                                        <textarea class="form-control" rows="5" id="Keyid" ng-model="objectivesDetail.Key" ></textarea>

                                                            <input type="text" size="1" class="form-control" datepicker-popup="{{format}}" ng-model="objectivesDetail.Completed" is-open="objectivesDetail.opened" datepicker-options="dateOptions" date-disabled="disabled(date, mode)" ng-required="true" close-text="Close"/>

                                                                <button type="button" class="btn btn-default" ng-click="open($event,objectivesDetail)"></button>

                                                        {{objectivesDetail.Individual}}

                                                        {{objectivesDetail.Measurable}}

                                                        {{objectivesDetail.Priority}}

                                                        {{objectivesDetail.Key}}

                                                        {{objectivesDetail.Completed | date :  "dd-MMM-yyyy"}}

                                            <button ng-hide="!objectivesDetails.length" style="margin:1em" type="button" class="btn btn-danger pull-right" ng-click="removeObj()" value="Remove">Remove</button>
                                            <button type="button" class="btn btn-primary addnew pull-right" style="margin:1em" ng-click="addNewObj(objectivesDetails)" value="Add New" ng-disabled="objectivesDetails.length>employeeCount">Add New</button>

                                            <input type="button" class="btn btn-primary pull-right" ng-click="saveObjGro()" value="Save">

                                                    <input type="checkbox" ng-model="selectedAllObjGro" ng-click="checkAllObjGro()" />
                                                    Individual Objectives
                                                    Measurable Outcomes
                                                    Priority %
                                                    Key Activities
                                                    Completed By

                                                    Individual Objectives
                                                    Measurable Outcomes
                                                    Priority %
                                                    Key Activities
                                                    Completed By

                                                        <input type="checkbox" ng-model="objectivesDetailGro.selected" />

                                                        <textarea class="form-control" rows="5" id="IndividualGroid" ng-model="objectivesDetailGro.IndividualGro"></textarea>

                                                        <textarea class="form-control" rows="5" id="MeasurableGroid" ng-model="objectivesDetailGro.MeasurableGro"></textarea>

                                                        <textarea class="form-control" rows="1" cols="1" id="PriorityGroid" ng-model="objectivesDetailGro.PriorityGro"></textarea>

                                                        <textarea class="form-control" rows="5" id="KeyGroid" ng-model="objectivesDetailGro.KeyGro"></textarea>

                                                            <input type="text" size="1" class="form-control" datepicker-popup="{{format}}" ng-model="objectivesDetailGro.CompletedGro" is-open="objectivesDetailGro.opened" datepicker-options="dateOptions" />

                                                                <button type="button" class="btn btn-default" ng-click="open($event,objectivesDetailGro)"></button>

                                                        {{objectivesDetailGro.IndividualGro}}

                                                        {{objectivesDetailGro.MeasurableGro}}

                                                        {{objectivesDetailGro.PriorityGro}}

                                                        {{objectivesDetailGro.KeyGro}}

                                                        {{objectivesDetailGro.CompletedGro | date :  "dd-MMM-yyyy"}}

                                            <button ng-hide="!objectivesGroDetails.length" type="button" style="margin:1em" class="btn btn-danger pull-right" ng-click="removeObjGro()" value="Remove">Remove</button>
                                            <button type="button" class="btn btn-primary addnew pull-right" style="margin:1em" ng-click="addNewObjGro(objectivesGroDetails)" value="Add New" ng-disabled="objectivesGroDetails.length>employeeCount">Add New</button>

                                            <input type="button" class="btn btn-primary pull-right" ng-click="saveObjPre()" value="Save">

                                                    <input type="checkbox" ng-model="selectedAllObjPre" ng-click="checkAllObjPre()" />
                                                    Individual Objectives
                                                    Measurable Outcomes
                                                    Priority %
                                                    Key Activities
                                                    Completed By

                                                    Individual Objectives
                                                    Measurable Outcomes
                                                    Priority %
                                                    Key Activities
                                                    Completed By

                                                        <input type="checkbox" ng-model="objectivesDetailPer.selected" />

                                                        <textarea class="form-control" rows="5" id="IndividualPreid" ng-model="objectivesDetailPer.IndividualPre"></textarea>

                                                        <textarea class="form-control" rows="5" id="MeasurablePreid" ng-model="objectivesDetailPer.MeasurablePre"></textarea>

                                                        <textarea class="form-control" rows="1" cols="1" id="PriorityPreid" ng-model="objectivesDetailPer.PriorityPre"></textarea>

                                                        <textarea class="form-control" rows="5" id="KeyPreid" ng-model="objectivesDetailPer.KeyPre"></textarea>

                                                            <input type="text" size="1" class="form-control" datepicker-popup="{{format}}" ng-model="objectivesDetailPer.CompletedPre" is-open="objectivesDetailPer.opened" datepicker-options="dateOptions" />

                                                                <button type="button" class="btn btn-default" ng-click="open($event,objectivesDetailPer)"></button>

                                                        {{objectivesDetailPer.IndividualPre}}

                                                        {{objectivesDetailPer.MeasurablePre}}

                                                        {{objectivesDetailPer.PriorityPre}}

                                                        {{objectivesDetailPer.KeyPre}}

                                                        {{objectivesDetailPer.CompletedPre | date :  "dd-MMM-yyyy"}}

                                            <button ng-hide="!objectivesPreDetails.length" style="margin:1em" type="button" class="btn btn-danger pull-right" ng-click="removeObjPre()" value="Remove">Remove</button>
                                            <button type="button" class="btn btn-primary addnew pull-right" style="margin:1em" ng-click="addNewObjPre(objectivesPreDetails)" value="Add New" ng-disabled="objectivesPreDetails.length>employeeCount">Add New</button>

```

答:
This you tried </p>

```<code>    .form-control {
    height: 10px;
    width:10px;
    padding: 11px;
}
      .my-datepicker{
    height: 10px;
    width:auto;
}
</code>```

Body:
I have added a date-picker in my webpage but when i click on the calendar icon the date-picker is flowing out of the window, it looks odd to see. tried to reduce width, its not working. I have added the CSS file also.

<!DOCTYPE html>

    <title></title>
    <meta charset="utf-8" />

                Status! {{ObjStatus}}

                <button type="button" class="btn btn-success pull-right" style="margin:1em" ng-click="editObj()" value="Edit" ng-show="Complete">Edit</button>
                <button type="button" class="btn btn-info pull-right" style="margin:1em" ng-click="requestReview()" value="Submit" ng-hide="Review">Submit</button>
                <button type="button" class="btn btn-success pull-right"style="margin:1em" ng-click="saveAllObj()" value="Save" ng-hide="Review">Save</button>

                    <button type="button" id="menuTab1" class="btn btn-default  btn-primary active" ng-click="tab1()" href="#tab1" data-toggle="tab">

Focus on Customer

                    </button>

                    <button type="button" id="menuTab2" class="btn btn-default" ng-click="tab2()" href="#tab2" data-toggle="tab">

Focus on Growth

                    </button>

                    <button type="button" id="menuTab3" class="btn btn-default" ng-click="tab3()" href="#tab3" data-toggle="tab">

Focus on Performance

                    </button>

                                            <input type="button" class="btn btn-primary pull-right" ng-click="saveObj()" value="Save">

                                                    <input type="checkbox" ng-model="selectedAllObj" ng-click="checkAllObj()" />
                                                    Individual Objectives
                                                    Measurable Outcomes
                                                    Priority %
                                                    Key Activities
                                                    Completed By

                                                    Individual Objectives
                                                    Measurable Outcomes
                                                    Priority %
                                                    Key Activities
                                                    Completed By

                                                        <input type="checkbox" ng-model="objectivesDetail.selected" />

                                                        <textarea class="form-control" rows="5" id="Individualid" ng-model="objectivesDetail.Individual" ></textarea>

                                                        <textarea class="form-control" rows="5"  id="Measurableid" ng-model="objectivesDetail.Measurable" ></textarea>

                                                        <textarea class="form-control" rows="1" cols="1" id="Priorityid" ng-model="objectivesDetail.Priority" ></textarea>

                                                        <textarea class="form-control" rows="5" id="Keyid" ng-model="objectivesDetail.Key" ></textarea>

                                                            <input type="text" size="1" class="form-control" datepicker-popup="{{format}}" ng-model="objectivesDetail.Completed" is-open="objectivesDetail.opened" datepicker-options="dateOptions" date-disabled="disabled(date, mode)" ng-required="true" close-text="Close"/>

                                                                <button type="button" class="btn btn-default" ng-click="open($event,objectivesDetail)"></button>

                                                        {{objectivesDetail.Individual}}

                                                        {{objectivesDetail.Measurable}}

                                                        {{objectivesDetail.Priority}}

                                                        {{objectivesDetail.Key}}

                                                        {{objectivesDetail.Completed | date :  "dd-MMM-yyyy"}}

                                            <button ng-hide="!objectivesDetails.length" style="margin:1em" type="button" class="btn btn-danger pull-right" ng-click="removeObj()" value="Remove">Remove</button>
                                            <button type="button" class="btn btn-primary addnew pull-right" style="margin:1em" ng-click="addNewObj(objectivesDetails)" value="Add New" ng-disabled="objectivesDetails.length>employeeCount">Add New</button>

                                            <input type="button" class="btn btn-primary pull-right" ng-click="saveObjGro()" value="Save">

                                                    <input type="checkbox" ng-model="selectedAllObjGro" ng-click="checkAllObjGro()" />
                                                    Individual Objectives
                                                    Measurable Outcomes
                                                    Priority %
                                                    Key Activities
                                                    Completed By

                                                    Individual Objectives
                                                    Measurable Outcomes
                                                    Priority %
                                                    Key Activities
                                                    Completed By

                                                        <input type="checkbox" ng-model="objectivesDetailGro.selected" />

                                                        <textarea class="form-control" rows="5" id="IndividualGroid" ng-model="objectivesDetailGro.IndividualGro"></textarea>

                                                        <textarea class="form-control" rows="5" id="MeasurableGroid" ng-model="objectivesDetailGro.MeasurableGro"></textarea>

                                                        <textarea class="form-control" rows="1" cols="1" id="PriorityGroid" ng-model="objectivesDetailGro.PriorityGro"></textarea>

                                                        <textarea class="form-control" rows="5" id="KeyGroid" ng-model="objectivesDetailGro.KeyGro"></textarea>

                                                            <input type="text" size="1" class="form-control" datepicker-popup="{{format}}" ng-model="objectivesDetailGro.CompletedGro" is-open="objectivesDetailGro.opened" datepicker-options="dateOptions" />

                                                                <button type="button" class="btn btn-default" ng-click="open($event,objectivesDetailGro)"></button>

                                                        {{objectivesDetailGro.IndividualGro}}

                                                        {{objectivesDetailGro.MeasurableGro}}

                                                        {{objectivesDetailGro.PriorityGro}}

                                                        {{objectivesDetailGro.KeyGro}}

                                                        {{objectivesDetailGro.CompletedGro | date :  "dd-MMM-yyyy"}}

                                            <button ng-hide="!objectivesGroDetails.length" type="button" style="margin:1em" class="btn btn-danger pull-right" ng-click="removeObjGro()" value="Remove">Remove</button>
                                            <button type="button" class="btn btn-primary addnew pull-right" style="margin:1em" ng-click="addNewObjGro(objectivesGroDetails)" value="Add New" ng-disabled="objectivesGroDetails.length>employeeCount">Add New</button>

                                            <input type="button" class="btn btn-primary pull-right" ng-click="saveObjPre()" value="Save">

                                                    <input type="checkbox" ng-model="selectedAllObjPre" ng-click="checkAllObjPre()" />
                                                    Individual Objectives
                                                    Measurable Outcomes
                                                    Priority %
                                                    Key Activities
                                                    Completed By

                                                    Individual Objectives
                                                    Measurable Outcomes
                                                    Priority %
                                                    Key Activities
                                                    Completed By

                                                        <input type="checkbox" ng-model="objectivesDetailPer.selected" />

                                                        <textarea class="form-control" rows="5" id="IndividualPreid" ng-model="objectivesDetailPer.IndividualPre"></textarea>

                                                        <textarea class="form-control" rows="5" id="MeasurablePreid" ng-model="objectivesDetailPer.MeasurablePre"></textarea>

                                                        <textarea class="form-control" rows="1" cols="1" id="PriorityPreid" ng-model="objectivesDetailPer.PriorityPre"></textarea>

                                                        <textarea class="form-control" rows="5" id="KeyPreid" ng-model="objectivesDetailPer.KeyPre"></textarea>

                                                            <input type="text" size="1" class="form-control" datepicker-popup="{{format}}" ng-model="objectivesDetailPer.CompletedPre" is-open="objectivesDetailPer.opened" datepicker-options="dateOptions" />

                                                                <button type="button" class="btn btn-default" ng-click="open($event,objectivesDetailPer)"></button>

                                                        {{objectivesDetailPer.IndividualPre}}

                                                        {{objectivesDetailPer.MeasurablePre}}

                                                        {{objectivesDetailPer.PriorityPre}}

                                                        {{objectivesDetailPer.KeyPre}}

                                                        {{objectivesDetailPer.CompletedPre | date :  "dd-MMM-yyyy"}}

                                            <button ng-hide="!objectivesPreDetails.length" style="margin:1em" type="button" class="btn btn-danger pull-right" ng-click="removeObjPre()" value="Remove">Remove</button>
                                            <button type="button" class="btn btn-primary addnew pull-right" style="margin:1em" ng-click="addNewObjPre(objectivesPreDetails)" value="Add New" ng-disabled="objectivesPreDetails.length>employeeCount">Add New</button>

Body:
This you tried

    .form-control {
    height: 10px;
    width:10px;
    padding: 11px;
}
      .my-datepicker{
    height: 10px;
    width:auto;
}


问:
how to run two version of odoo simultaneously using eclipse?
I need help regarding odoo.
How to run two different version of odoo run simultaneously using eclipse.
Both odoo version work on different port.</p>

答:
Create a configuration file for both projects like the following in odoo_server.conf file. With different port numbers.

```<code>[options]
; This is the password that allows database operations:
; admin_passwd = admin
db_host = localhost
db_port = 5433
db_user = openerp
db_password = openerp
addons_path = F:\Francis\Workspace\studica\addons
xmlrpc_port=7070
pg_path = E:\santhosh\upsynth_Postgres\bin
</code>```

then create Run configuration in Eclipse for both projects

Then add the configuration file path in the Arguments tab for both projects.

Now you will be able to Run 2 projects with different source code at the same time.

You can see the Logs for both like the following

Same procedure for both Windows and Linux version of Eclipse

Body:
Create a configuration file for both projects like the following in odoo_server.conf file. With different port numbers.

[options]
; This is the password that allows database operations:
; admin_passwd = admin
db_host = localhost
db_port = 5433
db_user = openerp
db_password = openerp
addons_path = F:\Francis\Workspace\studica\addons
xmlrpc_port=7070
pg_path = E:\santhosh\upsynth_Postgres\bin

then create Run configuration in Eclipse for both projects

Then add the configuration file path in the Arguments tab for both projects.

Now you will be able to Run 2 projects with different source code at the same time.

You can see the Logs for both like the following

Same procedure for both Windows and Linux version of Eclipse


问:
Why are these templates ambiguous?
The book C++ Templates : The Complete Guide has an example on page 275 that I'm having trouble wrapping my head around.

Quoting excerpts from the book...

```<code>template <typename T>
class Promotion<T,T> {
  public:
    typdef T ResultT;
};

template<typename T1, typename T2>
class Promotion<Array<T1>, Array<T2> > {
  public:
    typedef Array<typename Promotion<T1,T2>::ResultT> ResultT;
};

template<typename T>
class Promotion<Array<T>, Array<T> > {
  public:
    typedef Array<typename Promotion<T,T>::ResultT> ResultT;
};
</code>```

Unfortunately, the partial specialization Promotion<Array<T1>, Array<T2> > is
  neither more nor less specialized than the partial specialization
  Promotion<T,T>. To avoid template selection ambiguity, the last partial
  specialization was added. It is more specialized than either of the previous
  two partial specializations.

Why are the first two templates ambiguous, and why does the last template solve the ambiguity issue? When I try to apply the rules I either can't figure out how it comes up with an ambiguity, or if I think I have a way for it to happen I don't know why the last template solves the problem.

答:
Look at what the specializations do on a conceptual level.

The first one says "This is what we should do specifically if T1 and T2 are the same."

The second one says "This is what we should do specifically if T1 and T2 are both Array templates".

OK, so... let's say T1 and T2 are both the same array template. Which one should we use? There is no good way to argue that one of them is more specifically tailored to this situation than the other.

We resolve this by adding a third template specialization specifically for that situation: "This is what we should do specifically if T1 and T2 are both the same Array template".

Title: Why are these templates ambiguous?

Body:
The book C++ Templates : The Complete Guide has an example on page 275 that I'm having trouble wrapping my head around.

Quoting excerpts from the book...

template <typename T>
class Promotion<T,T> {
  public:
    typdef T ResultT;
};

template<typename T1, typename T2>
class Promotion<Array<T1>, Array<T2> > {
  public:
    typedef Array<typename Promotion<T1,T2>::ResultT> ResultT;
};

template<typename T>
class Promotion<Array<T>, Array<T> > {
  public:
    typedef Array<typename Promotion<T,T>::ResultT> ResultT;
};

Unfortunately, the partial specialization Promotion<Array<T1>, Array<T2> > is
  neither more nor less specialized than the partial specialization
  Promotion<T,T>. To avoid template selection ambiguity, the last partial
  specialization was added. It is more specialized than either of the previous
  two partial specializations.

Why are the first two templates ambiguous, and why does the last template solve the ambiguity issue? When I try to apply the rules I either can't figure out how it comes up with an ambiguity, or if I think I have a way for it to happen I don't know why the last template solves the problem.


问:
Set spinner title when activity is created
I have a spinner whose elements set by an arrayList.this arraylist gets data by calling an api. I have set title at 0th position of  arrayList .the problem is i want to show this title as activity is created. but this will set only when api calling is successful .it takes some time to load data. can anyone give me better idea to set title to spinner. </p>

答:
If data comes from api then you can add dialog on screen and hide title until api call success.. when you get response true then show titleview and add title from api. and api response is false then show error.. so user will get better view..

Thanks


问:
Why isn't Unity allowing me to apply certain changes to a prefab?
I have a prefab called square in the asset tray, I drag it into the scene to create an instance of the square prefab (in the hierarchy it is highlighted blue and has the select, revert and apply buttons in the properties). If I move/resize the instance and then press apply, the changes are applied to the prefab.

However, the square prefab has a script with a public game object. I drag the game object from the hierarchy into the slot in the instance's properties tab and is shows that the script is now referencing the actual gameobject. However, when I press apply this change isn't applied to the prefab (the prefab's script still isn't referencing any actual gameobject). All other changes to the prefab are applied.

I have tried dragging the instance into the asset tray to create a new prefab with the changes, but, as soon as I do, the script no longer references the game object.

I shouldn't have to create an entirely new prefab every time I add a public variable to a script so why can't I apply this change?

答: Solved: Prefabs can only reference other prefabs since there might not be an instance. Made the actual gameobject into an instance of a prefab and applied the prefab to the script</p>


问:
.gitignore not ignoring .cs.meta files
All I want is for for git to ignore files that end in .cs.meta.

My .gitignore file includes just this:

```<code># ignore all .cs.meta files
*.cs.meta
</code>```

How can ignore only files that end in .cs.meta?

答:
To ignore ignore all .cs.meta files you just need to add

```<code>*.cs.meta
</code>```

in your .gitignore file.

You did it! Maybe is not working because you added them to .gitignore after  their repository addition. You now need to remove them from the git repository:

```<code>git rm file.cs.meta
</code>```

and then commit again.

Title: .gitignore not ignoring .cs.meta files

Body:
All I want is for for git to ignore files that end in .cs.meta.

My .gitignore file includes just this:

# ignore all .cs.meta files
*.cs.meta

How can ignore only files that end in .cs.meta?

Body:
To ignore ignore all .cs.meta files you just need to add

*.cs.meta

in your .gitignore file.

You did it! Maybe is not working because you added them to .gitignore after  their repository addition. You now need to remove them from the git repository:

git rm file.cs.meta

and then commit again.


问:
Make image larger onclick
hello i need to achieve this --->Make image larger onclick.  After different image is selected previous image gets on the size it was before the click and selected image becomes larger

This work's only after image is clicked again

```<code>$(document).ready(function () {
    var small={width: "127px",height: "128px"};
    var large={width: "200px",height: "201px"};
    var count=1;
    $("#weekly").css(small).on('click',function () {
        $(this).animate((count==1)?large:small);
        count = 1-count;
    });
});
</code>```

need to achieve that it makes image smaller after another is selected

答:
Do like below:-

$(document).ready(function () {
    var small={width: "127px",height: "128px",background:"green"};//background added to show you that it's working
    var large={width: "200px",height: "201px",background:"green"};
    $(".weekly").css(small).on('click',function () {
        $(this).animate(large);
        $('.weekly').not($(this)).animate(small);
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.weekly{
cursor:pointer; /* for cursor */
}</code>```

if images are inside div

Or images are directly there

```

Title: Make image larger onclick

Body:
hello i need to achieve this --->Make image larger onclick.  After different image is selected previous image gets on the size it was before the click and selected image becomes larger

This work's only after image is clicked again

$(document).ready(function () {
    var small={width: "127px",height: "128px"};
    var large={width: "200px",height: "201px"};
    var count=1;
    $("#weekly").css(small).on('click',function () {
        $(this).animate((count==1)?large:small);
        count = 1-count;
    });
});

need to achieve that it makes image smaller after another is selected

Body:
Do like below:-

$(document).ready(function () {
    var small={width: "127px",height: "128px",background:"green"};//background added to show you that it's working
    var large={width: "200px",height: "201px",background:"green"};
    $(".weekly").css(small).on('click',function () {
        $(this).animate(large);
        $('.weekly').not($(this)).animate(small);
    });
});

.weekly{
cursor:pointer; /* for cursor */
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h1>if images are inside div</h1><br>

<div class="weekly"><img src="https://www.fusemail.com/wp-content/uploads/2014/02/industry-compliance.png?x12193"></div><br>
<div class="weekly"><img src="https://www.fusemail.com/wp-content/uploads/2014/02/industry-compliance.png?x12193"></div><br>
<div class="weekly"><img src="https://www.fusemail.com/wp-content/uploads/2014/02/industry-compliance.png?x12193"></div><br>

<h1>Or images are directly there</h1><br>

<img class="weekly" src="https://www.fusemail.com/wp-content/uploads/2014/02/industry-compliance.png?x12193">
<img class="weekly" src="https://www.fusemail.com/wp-content/uploads/2014/02/industry-compliance.png?x12193">
<img class="weekly" src="https://www.fusemail.com/wp-content/uploads/2014/02/industry-compliance.png?x12193">


问:
Create multiple files based on user input in python
i am new to python and I've written a code which create configuration files for my application. I've created the code which works for 2 IP's but it may happen that user may input more IP's and for each increase in Ip the config file will be changed. There are authentication servers and they can be either 1 or 2 only.

I am passing input to python code by a file name "inputfile", below is how it look like:

```<code>EnterIp_list: ip_1 ip_2
authentication_server: as_1 as_2
</code>```

Below is how the final configuration files are created:

```<code>configfile1:                  configfile2:
App_ip: ip_1                  App_ip: ip_2
app_number: 1                 app_number: 2
authen_server: as_1           authen_server: as_2
</code>```

Below is how python3 code looks:

```<code>def createconfig(filename, app_ip, app_number, authen_server)
     with open(filename, 'w') as inf:
          inf.write("App_ip=" + app_ip + "\n")
          inf.write("app_numbber=" + app_number)
          inf.write("authen_server="+ authen_server)

with open("inputfile") as f:
     for line in f:
       if EnterIP_list in line:
          a= line.split("=")
          b = a[1].split()
       if authentiation_server in line:
          c= line.split("=")
          d=c[1].split()

createconfig(configfile1, b[0], 1, d[0])
createconfig(configfile2, b[1], 2, d[1])
</code>```

Users has freedom to input as many IP's as they wish for. Can someone please suggest what need to be done to make code more generic and robust so that it will work for any number of input ip's ??? also value for app_number increases with each new ip added.

There will always be two authentication server and they go in round robin e.g. the third app ip will be associated to "as_1" again.

答:
A not so great way of doing it without modifying so much of your code would be to remove the last two createconfig() calls and instead do it in a loop once you have b as follows:</p>

```<code>with open("inputfile") as f:
 for line in f:
    a= line.split("=")
    b = a[1].split()

for app_number in b:
    createconfig("configfile{}".format(app_number), b[app_number], app_number)
</code>```

Body:
i am new to python and I've written a code which create configuration files for my application. I've created the code which works for 2 IP's but it may happen that user may input more IP's and for each increase in Ip the config file will be changed. There are authentication servers and they can be either 1 or 2 only.

I am passing input to python code by a file name "inputfile", below is how it look like:

EnterIp_list: ip_1 ip_2
authentication_server: as_1 as_2

Below is how the final configuration files are created:

configfile1:                  configfile2:
App_ip: ip_1                  App_ip: ip_2
app_number: 1                 app_number: 2
authen_server: as_1           authen_server: as_2

Below is how python3 code looks:

def createconfig(filename, app_ip, app_number, authen_server)
     with open(filename, 'w') as inf:
          inf.write("App_ip=" + app_ip + "\n")
          inf.write("app_numbber=" + app_number)
          inf.write("authen_server="+ authen_server)

with open("inputfile") as f:
     for line in f:
       if EnterIP_list in line:
          a= line.split("=")
          b = a[1].split()
       if authentiation_server in line:
          c= line.split("=")
          d=c[1].split()

createconfig(configfile1, b[0], 1, d[0])
createconfig(configfile2, b[1], 2, d[1])

Users has freedom to input as many IP's as they wish for. Can someone please suggest what need to be done to make code more generic and robust so that it will work for any number of input ip's ??? also value for app_number increases with each new ip added.

There will always be two authentication server and they go in round robin e.g. the third app ip will be associated to "as_1" again.

Body:
A not so great way of doing it without modifying so much of your code would be to remove the last two createconfig() calls and instead do it in a loop once you have b as follows:

with open("inputfile") as f:
 for line in f:
    a= line.split("=")
    b = a[1].split()

for app_number in b:
    createconfig("configfile{}".format(app_number), b[app_number], app_number)


问:
Java generic understanding Type
I am learning Java generic from: https://docs.oracle.com/javase/tutorial/java/generics/bounded.html and I have some doubts on the code sample below:

```<code>public class Box<T> {

    private T t;

    public void set(T t) {
        this.t = t;
    }

    public T get() {
        return t;
    }

    public <U extends Number> void inspect(U u) {
        System.out.println("T: " + t.getClass().getName());
        System.out.println("U: " + u.getClass().getName());
    }

    public static void main(String[] args) {
        Box<Integer> integerBox = new Box<Integer>();
        integerBox.set(new Integer(10));
        integerBox.inspect("some text"); // error: this is still String!
    }
}
</code>```

Why wasnt the inspect() method to be written as shown below instead it was ?

```<code> public <T extends Number> void inspect(T t) { }
</code>```

There are some other code samples which has the following syntax. What does the 1st pair  stands for?

```<code>public <K,V> SomeClass<K,V>
</code>```

What does static  stands for?

```<code>public static <T> int countGreaterThan(T[] anArray, T elem)
</code>```

答:
Yes. Freedev answer is correct.
Try</p>

```<code>public static void main(String[] args) {
    Test1<Integer> integerBox = new Test1<Integer>();
    integerBox.set(new Integer(10));
    integerBox.inspect(78); //  inspect method expect a interger value
}
</code>```

Title: Java generic understanding Type

Body:
I am learning Java generic from: https://docs.oracle.com/javase/tutorial/java/generics/bounded.html and I have some doubts on the code sample below:

public class Box<T> {

    private T t;

    public void set(T t) {
        this.t = t;
    }

    public T get() {
        return t;
    }

    public  void inspect(U u) {
        System.out.println("T: " + t.getClass().getName());
        System.out.println("U: " + u.getClass().getName());
    }

    public static void main(String[] args) {
        Box<Integer> integerBox = new Box<Integer>();
        integerBox.set(new Integer(10));
        integerBox.inspect("some text"); // error: this is still String!
    }
}

Why wasnt the inspect() method to be written as shown below instead it was ?

 public <T extends Number> void inspect(T t) { }

There are some other code samples which has the following syntax. What does the 1st pair  stands for?

public <K,V> SomeClass<K,V>

What does static  stands for?

public static <T> int countGreaterThan(T[] anArray, T elem)

Body:
Yes. Freedev answer is correct.
Try

public static void main(String[] args) {
    Test1<Integer> integerBox = new Test1<Integer>();
    integerBox.set(new Integer(10));
    integerBox.inspect(78); //  inspect method expect a interger value
}


问:
get sql query result in xml format?
Hello i am trying the getting result in xml format in the sql server but i don't get propare xml format many data it's repeat in xml format. i have write this query in the sql server but not a getting propare data. any one know where is my mistake then please let me know how can do that.

Here i have write this query :

```<code>select * from (

    SELECT SSCF.SubSubCategoryId AS InterestId,c.FeedId,c.Description,u.UserId,u.Email,u.UserName,u.ProfileImage,u.Name,
           ISNULL(SSCL.SubSubCategory,SSC.SubSubCategory) AS Interest,
           1 AS [Type]
    FROM SubSubCategoryFollowers SSCF
    LEFT JOIN SubSubCategories SSC ON SSCF.SubSubCategoryId = SSC.SubSubCategoryId
    INNER JOIN Feed c on c.FeedId = SSC.FeedId
    inner join Users u on u.UserId = SSCF.UserId
    WHERE u.Email is not null

    UNION ALL

    SELECT  SCF.SubCategoryId AS InterestId,c.FeedId,c.Description,u.UserId,u.Email,u.UserName,u.ProfileImage,u.Name,
           ISNULL(SCL.SubCategory,SC.SubCategory) AS Interest,
           2 AS [Type]
    FROM SubCategoryFollowers SCF
    LEFT JOIN SubCategories SC ON SCF.SubCategoryId = SC.SubCategoryId
    INNER JOIN Feed c on c.FeedId = SC.FeedId
    inner join Users u on u.UserId = SCF.UserId
    WHERE u.Email is not null

 )as res

group by res.UserId,res.InterestId,res.FeedId,res.Description,res.Email,res.Interest,res.Type,res.UserName,res.ProfileImage,res.Name
order by res.FeedId
OFFSET 1   ROWS
FETCH NEXT  50000   ROWS ONLY
FOR XML PATH('User'), ROOT ('Users')
</code>```

this is my current op =>

```<code> <Users>
  <User>
    <UserId>1660</UserId>
    <Email>xyz.com</Email>
    <UserName>xyz</UserName>
    <ProfileImage>20160717035320958.jpeg</ProfileImage>
    <InterestId>15</InterestId>
    <FeedId>4689</FeedId>
    <Description>Test</Description>
    <Interest>Event</Interest>
    <Type>2</Type>
</User>
<User>
     <UserId>1660</UserId>
    <Email>xyz.com</Email>
    <UserName>xyz</UserName>
    <ProfileImage>20160717035320958.jpeg</ProfileImage>
    <InterestId>16</InterestId>
    <FeedId>4689</FeedId>
    <Description>Test</Description>
    <Interest>Party</Interest>
    <Type>2</Type>
</User>
<User>
    <UserId>1660</UserId>
    <Email>xyz.com</Email>
    <UserName>xyz</UserName>
    <ProfileImage>20160717035320958.jpeg</ProfileImage>
    <InterestId>21</InterestId>
    <FeedId>4689</FeedId>
    <Description>Test</Description>
    <Interest>Club</Interest>
    <Type>2</Type>
</User>
<User>
<UserId>1661</UserId>
<Email>abc.com</Email>
<UserName>abc</UserName>
<ProfileImage>20160717035320959.jpeg</ProfileImage>
<InterestId>15</InterestId>
<FeedId>4690</FeedId>
<Description>Test1</Description>
<Interest>Cricket</Interest>
<Type>1</Type>
</code>```

My expected o/p =>

```<code><Users>
 <User>
 <UserId>1660</UserId>
<Email>xyz.com</Email>
<UserName>xyz</UserName>
 <ProfileImage>20160717035320958.jpeg</ProfileImage>

<InterestId>15</InterestId>
<FeedId>4689</FeedId>
<Description>Test</Description>
<Interest>Event</Interest>
<Type>2</Type>

<InterestId>16</InterestId>
<FeedId>4689</FeedId>
<Description>Test</Description>
<Interest>Party</Interest>
<Type>2</Type>

<InterestId>21</InterestId>
<FeedId>4689</FeedId>
<Description>Test</Description>
<Interest>Club</Interest>
<Type>2</Type>
</User>
<User>
<UserId>1661</UserId>
<Email>abc.com</Email>
<UserName>abc</UserName>
<ProfileImage>20160717035320959.jpeg</ProfileImage>

<InterestId>15</InterestId>
<FeedId>4690</FeedId>
<Description>Test1</Description>
<Interest>Cricket</Interest>
<Type>1</Type>
</code>```

i want like this data in xml format any one know please let me know.

答:
I have an example for your case.
You could use TYPE to get nested xml

```<code>DECLARE @SampleData AS TABLE
(
    UserId INT,
    Email varchar(200),
    UserName varchar(200),
    InterestId int,
    Description varchar(200)
)

INSERT INTO @SampleData
(
    UserId,
    Email,
    UserName,
    InterestId,
    Description
)
VALUES
(1,'1@abc.xyz','User1', 100, 'Description 100'),
(1,'1@abc.xyz','User1', 101, 'Description 101'),
(1,'1@abc.xyz','User1', 102, 'Description 102'),
(1,'1@abc.xyz','User1', 103, 'Description 103')

SELECT  sd.UserId,
       sd.Email,
       sd.UserName,
       (
          SELECT sd2.InterestId,
                sd2.Description
          FROM @SampleData sd2
          WHERE sd2.UserId = sd.UserId
          FOR XML PATH (''), TYPE
       )
FROM
(   select DISTINCT sd.UserId, sd.Email, sd.UserName
    FROM @SampleData sd
) sd
FOR XML PATH('User') ,ROOT('Users')
</code>```

Returns

```<code><Users>
  <User>
    <UserId>1</UserId>
    <Email>1@abc.xyz</Email>
    <UserName>User1</UserName>
    <InterestId>100</InterestId>
    <Description>Description 100</Description>
    <InterestId>101</InterestId>
    <Description>Description 101</Description>
    <InterestId>102</InterestId>
    <Description>Description 102</Description>
    <InterestId>103</InterestId>
    <Description>Description 103</Description>
  </User>
</Users>
</code>```

Demo link: http://rextester.com/KKEHCR86171

Title: get sql query result in xml format?

Body:
Hello i am trying the getting result in xml format in the sql server but i don't get propare xml format many data it's repeat in xml format. i have write this query in the sql server but not a getting propare data. any one know where is my mistake then please let me know how can do that.

Here i have write this query :

select * from (

    SELECT SSCF.SubSubCategoryId AS InterestId,c.FeedId,c.Description,u.UserId,u.Email,u.UserName,u.ProfileImage,u.Name,
           ISNULL(SSCL.SubSubCategory,SSC.SubSubCategory) AS Interest,
           1 AS [Type]
    FROM SubSubCategoryFollowers SSCF
    LEFT JOIN SubSubCategories SSC ON SSCF.SubSubCategoryId = SSC.SubSubCategoryId
    INNER JOIN Feed c on c.FeedId = SSC.FeedId
    inner join Users u on u.UserId = SSCF.UserId
    WHERE u.Email is not null

    UNION ALL

    SELECT  SCF.SubCategoryId AS InterestId,c.FeedId,c.Description,u.UserId,u.Email,u.UserName,u.ProfileImage,u.Name,
           ISNULL(SCL.SubCategory,SC.SubCategory) AS Interest,
           2 AS [Type]
    FROM SubCategoryFollowers SCF
    LEFT JOIN SubCategories SC ON SCF.SubCategoryId = SC.SubCategoryId
    INNER JOIN Feed c on c.FeedId = SC.FeedId
    inner join Users u on u.UserId = SCF.UserId
    WHERE u.Email is not null

 )as res

group by res.UserId,res.InterestId,res.FeedId,res.Description,res.Email,res.Interest,res.Type,res.UserName,res.ProfileImage,res.Name
order by res.FeedId
OFFSET 1   ROWS
FETCH NEXT  50000   ROWS ONLY
FOR XML PATH('User'), ROOT ('Users')

this is my current op =>

 <Users>
  <User>
    <UserId>1660</UserId>
    <Email>xyz.com</Email>
    <UserName>xyz</UserName>
    <ProfileImage>20160717035320958.jpeg</ProfileImage>
    <InterestId>15</InterestId>
    <FeedId>4689</FeedId>
    <Description>Test</Description>
    <Interest>Event</Interest>
    <Type>2</Type>
</User>
<User>
     <UserId>1660</UserId>
    <Email>xyz.com</Email>
    <UserName>xyz</UserName>
    <ProfileImage>20160717035320958.jpeg</ProfileImage>
    <InterestId>16</InterestId>
    <FeedId>4689</FeedId>
    <Description>Test</Description>
    <Interest>Party</Interest>
    <Type>2</Type>
</User>
<User>
    <UserId>1660</UserId>
    <Email>xyz.com</Email>
    <UserName>xyz</UserName>
    <ProfileImage>20160717035320958.jpeg</ProfileImage>
    <InterestId>21</InterestId>
    <FeedId>4689</FeedId>
    <Description>Test</Description>
    <Interest>Club</Interest>
    <Type>2</Type>
</User>
<User>
<UserId>1661</UserId>
<Email>abc.com</Email>
<UserName>abc</UserName>
<ProfileImage>20160717035320959.jpeg</ProfileImage>
<InterestId>15</InterestId>
<FeedId>4690</FeedId>
<Description>Test1</Description>
<Interest>Cricket</Interest>
<Type>1</Type>

My expected o/p =>

<Users>
 <User>
 <UserId>1660</UserId>
<Email>xyz.com</Email>
<UserName>xyz</UserName>
 <ProfileImage>20160717035320958.jpeg</ProfileImage>

<InterestId>15</InterestId>
<FeedId>4689</FeedId>
<Description>Test</Description>
<Interest>Event</Interest>
<Type>2</Type>

<InterestId>16</InterestId>
<FeedId>4689</FeedId>
<Description>Test</Description>
<Interest>Party</Interest>
<Type>2</Type>

<InterestId>21</InterestId>
<FeedId>4689</FeedId>
<Description>Test</Description>
<Interest>Club</Interest>
<Type>2</Type>
</User>
<User>
<UserId>1661</UserId>
<Email>abc.com</Email>
<UserName>abc</UserName>
<ProfileImage>20160717035320959.jpeg</ProfileImage>

<InterestId>15</InterestId>
<FeedId>4690</FeedId>
<Description>Test1</Description>
<Interest>Cricket</Interest>
<Type>1</Type>

i want like this data in xml format any one know please let me know.

Body:
I have an example for your case.
You could use TYPE to get nested xml

DECLARE @SampleData AS TABLE
(
    UserId INT,
    Email varchar(200),
    UserName varchar(200),
    InterestId int,
    Description varchar(200)
)

INSERT INTO @SampleData
(
    UserId,
    Email,
    UserName,
    InterestId,
    Description
)
VALUES
(1,'1@abc.xyz','User1', 100, 'Description 100'),
(1,'1@abc.xyz','User1', 101, 'Description 101'),
(1,'1@abc.xyz','User1', 102, 'Description 102'),
(1,'1@abc.xyz','User1', 103, 'Description 103')

SELECT  sd.UserId,
       sd.Email,
       sd.UserName,
       (
          SELECT sd2.InterestId,
                sd2.Description
          FROM @SampleData sd2
          WHERE sd2.UserId = sd.UserId
          FOR XML PATH (''), TYPE
       )
FROM
(   select DISTINCT sd.UserId, sd.Email, sd.UserName
    FROM @SampleData sd
) sd
FOR XML PATH('User') ,ROOT('Users')

Returns

<Users>
  <User>
    <UserId>1</UserId>
    <Email>1@abc.xyz</Email>
    <UserName>User1</UserName>
    <InterestId>100</InterestId>
    <Description>Description 100</Description>
    <InterestId>101</InterestId>
    <Description>Description 101</Description>
    <InterestId>102</InterestId>
    <Description>Description 102</Description>
    <InterestId>103</InterestId>
    <Description>Description 103</Description>
  </User>
</Users>

Demo link: http://rextester.com/KKEHCR86171


问:
Batch file to delete files older than N days
I am looking for a way to delete all files older than 7 days in a batch file.  I've searched around the web, and found some examples with hundreds of lines of code, and others that required installing extra command line utilities to accomplish the task.

Similar things can be done in BASH in just a couple lines of code. It seems that something at least remotely easy could be done for batch files in Windows. I'm looking for a solution that works in a standard Windows command prompt, without any extra utilities. Please no PowerShell or Cygwin either.

答:
My command is

```<code>forfiles -p "d:\logs" -s -m*.log -d-15 -c"cmd /c del @PATH\@FILE"
</code>```

@PATH - is just path in my case, so I had to use @PATH\@FILE

also forfiles /? not working for me too, but forfiles (without "?") worked fine.

And the only question I have: how to add multiple mask (for example ".log|.bak")?

All this regarding forfiles.exe that I downloaded here (on win XP)

But if you are using Windows server forfiles.exe should be already there and it is differs from ftp version. That is why I should modify command.

For Windows Server 2003 I'm using this command:

```<code>forfiles -p "d:\Backup" -s -m *.log -d -15 -c "cmd /c del @PATH"
</code>```

OwnerDisplayName: Kibbee

Body:
My command is

forfiles -p "d:\logs" -s -m*.log -d-15 -c"cmd /c del @PATH\@FILE"

@PATH - is just path in my case, so I had to use @PATH\@FILE

also forfiles /? not working for me too, but forfiles (without "?") worked fine.

And the only question I have: how to add multiple mask (for example ".log|.bak")?

All this regarding forfiles.exe that I downloaded here (on win XP)

But if you are using Windows server forfiles.exe should be already there and it is differs from ftp version. That is why I should modify command.

For Windows Server 2003 I'm using this command:

forfiles -p "d:\Backup" -s -m *.log -d -15 -c "cmd /c del @PATH"


问:
Unable to parse stringified array within an array
I have this example code:

```<code>let testData= [{name:'Joshua',age:22,option:"[{value:'test'}]"},{name:'Ali',age:200,option:"[{value:'test2'}]"}]

let parsedData=JSON.parse(testData[0].option);
console.log(parsedData);
</code>```

Testing my code using this site: https://es6console.com/

It seems that I'm unable to parse & log the data at all.

Any ideas why this is happening?

答:
I think the issue is that JSON object's fields should be wrapped in double-quotes.
E.g. </p>

```<code>let testData = [{name:'Joshua',age:22,option:`[{"value":'test'}]`},{name:'Ali',age:200,option:`[{"value":'test2'}]`}]
</code>```

Body:
I have this example code:

let testData= [{name:'Joshua',age:22,option:"[{value:'test'}]"},{name:'Ali',age:200,option:"[{value:'test2'}]"}]

let parsedData=JSON.parse(testData[0].option);
console.log(parsedData);

Testing my code using this site: https://es6console.com/

It seems that I'm unable to parse & log the data at all.

Any ideas why this is happening?

Body:
I think the issue is that JSON object's fields should be wrapped in double-quotes.
E.g.

let testData = [{name:'Joshua',age:22,option:`[{"value":'test'}]`},{name:'Ali',age:200,option:`[{"value":'test2'}]`}]


问:
Why do I get a KeyError in this Python code?
I'm trying to run this code:

```<code>dictVar = {'PI': 3.14,
           25: "The Square of 5",
           "Weihan": "My Name"
           }

print("The value corresponding to the key " + str(3.14) + " is: " + dictVar[3.14])
</code>```

I keep getting the following error:

```<code>Traceback (most recent call last):
  File "C:/Users/KitKat#21266/Google Drive/Project Environment/From 0 to 1 Python Programming/Dictionary and If-Else.py", line 8, in <module>
    print("The value corresponding to the key " + str(3.14) + " is: " + dictVar[3.14])
KeyError: 3.14
</code>```

Why does this error occur?

答:
You are trying to print dictVar[3.14], but there is no key 3.14 in your dictionary.

Instead try using dictVar['PI']

Body:
I'm trying to run this code:

dictVar = {'PI': 3.14,
           25: "The Square of 5",
           "Weihan": "My Name"
           }

print("The value corresponding to the key " + str(3.14) + " is: " + dictVar[3.14])

I keep getting the following error:

Traceback (most recent call last):
  File "C:/Users/KitKat#21266/Google Drive/Project Environment/From 0 to 1 Python Programming/Dictionary and If-Else.py", line 8, in <module>
    print("The value corresponding to the key " + str(3.14) + " is: " + dictVar[3.14])
KeyError: 3.14

Why does this error occur?


问:
Atomic Sequence using Hazelcast
USE CASE: Create AtomicSequence using last saved id in DB (not start from zero) and generate id after last saved id in db.
       First we are checking if AtomicSequence instance is there or not if not we create AtomicSequence from last saved id (if the entry is in db.).

In HazelcastAtomicSequenceManager getSequenceGenerator method is two-step process.

Step 1: getHzInstance().getAtomicLong(key). // It will get if not present create a new one with 0 initial value.
Step 2: this.sequence.compareAndSet(0, startVal); // set value if initial value is zero.

Now consider Thread 1 come check and see the AtomicSequence for the given key is not present and execute stpe1 still did not execute step 2.
Thread 2 come and see the AtomicSequence is created (As step 1 is executed by thread1) and go ahead and increment it to 1.As the initial value still zero as Thread 2 did not execute step 2.
Now thread 1 will try to execute step2 but unable to it as initial value became 1 or something not equal to zero. So the atomicsequence will generate id from 1 next instead it should start from last save id, Due to which our test case is failing.
Any way to fix this issue

答:
You need to get and try compareAndSet in a loop, until it succeeds:

        long current;
        do {
            current = atomicLong.get();
        } while (!atomicLong.compareAndSet(current, startVal));```

Title: Atomic Sequence using Hazelcast


问:
Why isn't arr[-2] equivalent to -2[arr]?
```<code>#include <iostream>
using namespace std;

int main()
{
    int arr[3] = { 10, 20, 30 };
    cout << arr[-2] << endl;
    cout << -2[arr] << endl;
    return 0;
}
</code>```

Output:

```<code>4196160
-30
</code>```

Here arr[-2] is out of range and invalid, causing undefined behavior.
But -2[arr] evaluates to -30. Why?

Isn't arr[-2] equivalent to -2[arr]?

答: -2[arr] is parsed as -(2[arr]). In C (and in C++, ignoring overloading), the definition of X[Y] is *(X+Y) (see more discussion of this in this question), which means that 2[arr] is equal to arr[2].

Body:
#include <iostream>
using namespace std;

int main()
{
    int arr[3] = { 10, 20, 30 };
    cout << arr[-2] << endl;
    cout << -2[arr] << endl;
    return 0;
}

Output:

4196160
-30

Here arr[-2] is out of range and invalid, causing undefined behavior.
But -2[arr] evaluates to -30. Why?

Isn't arr[-2] equivalent to -2[arr]?


问:
CSS: Workaround to backdrop-filter?
backdrop-filter is a recent CSS feature, that is not yet available in modern browsers (at least as of July 1, 2016).

Chrome 51 supports backdrop-filter via Experimental Web Platform flag.

Safari 9.1 supports it with -webkit- prefix

Firefox 47 have no support

Being in such an unusable state, I would like to know whether there exists any alternative way to bring in the same result.

JS workarounds for blur, grayscale,… are also welcome

The development of backdrop-filter can be tracked through https://bugs.chromium.org/p/chromium/issues/detail?id=497522

答:
I use this to get the popular frosted glass effect. Until someone successfully invents a good polyfill for backdrop-filter I'm using a slightly transparent background as a fallback:

```<code>/* slightly transparent fallback */
.backdrop-blur {
  background-color: rgba(255, 255, 255, .9);
}

/* if backdrop support: very transparent and blurred */
@supports ((-webkit-backdrop-filter: none) or (backdrop-filter: none)) {
  .backdrop-blur {
    background-color: rgba(255, 255, 255, .5);
    -webkit-backdrop-filter: blur(2em);
    backdrop-filter: blur(2em);
  }
}
</code>```

The filter will work in currently supported browsers. (Safari and Chrome with experimental Web Platform features enabled) The code should also work in future browsers that support unprefixed backdrop-filter if the spec doesn't change before that.

Examples without and with backdrop-filter support:

Title: CSS: Workaround to backdrop-filter?

Body:
I use this to get the popular frosted glass effect. Until someone successfully invents a good polyfill for backdrop-filter I'm using a slightly transparent background as a fallback:

/* slightly transparent fallback */
.backdrop-blur {
  background-color: rgba(255, 255, 255, .9);
}

/* if backdrop support: very transparent and blurred */
@supports ((-webkit-backdrop-filter: none) or (backdrop-filter: none)) {
  .backdrop-blur {
    background-color: rgba(255, 255, 255, .5);
    -webkit-backdrop-filter: blur(2em);
    backdrop-filter: blur(2em);
  }
}

The filter will work in currently supported browsers. (Safari and Chrome with experimental Web Platform features enabled) The code should also work in future browsers that support unprefixed backdrop-filter if the spec doesn't change before that.

Examples without and with backdrop-filter support:


答:
Don't use keys that don't exist.</p>

```<code>key = "PI"
print("The value corresponding to the key {0} is: {1}".format(key, dictVar[key]))
</code>```

Title: Why do I get a KeyError in this Python code?

Body:
Don't use keys that don't exist.

key = "PI"
print("The value corresponding to the key {0} is: {1}".format(key, dictVar[key]))


问:
Ruby execute a multiline cmd string
I had build a curl command

```<code>cmd = %Q(curl --tlsv1.2 -b #{config['cookies']} -c #{config['cookies']} --
connect-timeout 60 -X POST
            -H 'Content-Type: application/xml'
            -H 'Accept: application/xml'
            -d '#{xml_content}'
            --location #{uri})
puts cmd
</code>```

The output is as follow when the string is printed

```<code>curl --tlsv1.2 -b /tmp/cookie.txt -c /tmp/cookie.txt --connect-timeout 60 -X POST
            -H 'Content-Type: application/xml'
            -H 'Accept: application/xml'
            -d '<?xml version="1.0" encoding="UTF-8" ?>
            <ns:login xmlns:ns="http://www.actility.com/smp/ws/admin">
            <login>hello</login><password>wPa4GwYbRTCw0Uy!</password></ns:login>'
            --location https://myapi.application.com
</code>```

How do I execute it in ruby w/o modifying the cmd string to a single cmd ?

答:
I think that you should add to your cmd before the "\n" de "\" it should be scaped as follows:

```<code>[1] pry(main)> cmd = %Q(curl -i
[1] pry(main)* -H 'Authorization: Basic dXNlcjpwYXNzd29yZA=='
[1] pry(main)* -XGET 'http://httpbin.org/basic-auth/user/password')
=> "curl -i\n" + "-H 'Authorization: Basic dXNlcjpwYXNzd29yZA=='\n" + "-XGET 'http://httpbin.org/basic-auth/user/password'"
[2] pry(main)> exec(cmd)
curl: no URL specified!
curl: try 'curl --help' or 'curl --manual' for more information
sh: line 1: -H: command not found
sh: line 2: -XGET: command not found
</code>```

you should write this:

```<code>[1] pry(main)> cmd = %Q(curl -i \\
[1] pry(main)* -H 'Authorization: Basic dXNlcjpwYXNzd29yZA==' \\
[1] pry(main)* -XGET 'http://httpbin.org/basic-auth/user/password')
=> "curl -i \\\n" + "-H 'Authorization: Basic dXNlcjpwYXNzd29yZA==' \\\n" + "-XGET 'http://httpbin.org/basic-auth/user/password'"
[2] pry(main)> exec(cmd)
HTTP/1.1 200 OK
Connection: keep-alive
Server: meinheld/0.6.1
Date: Mon, 05 Jun 2017 09:46:24 GMT
Content-Type: application/json
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
X-Powered-By: Flask
X-Processed-Time: 0.000503063201904
Content-Length: 47
Via: 1.1 vegur

{
  "authenticated": true,
  "user": "user"
}
</code>```

Title: Ruby execute a multiline cmd string

Body:
I had build a curl command

cmd = %Q(curl --tlsv1.2 -b #{config['cookies']} -c #{config['cookies']} --
connect-timeout 60 -X POST
            -H 'Content-Type: application/xml'
            -H 'Accept: application/xml'
            -d '#{xml_content}'
            --location #{uri})
puts cmd

The output is as follow when the string is printed

curl --tlsv1.2 -b /tmp/cookie.txt -c /tmp/cookie.txt --connect-timeout 60 -X POST
            -H 'Content-Type: application/xml'
            -H 'Accept: application/xml'
            -d '<?xml version="1.0" encoding="UTF-8" ?>
            <ns:login xmlns:ns="http://www.actility.com/smp/ws/admin">
            <login>hello</login><password>wPa4GwYbRTCw0Uy!</password></ns:login>'
            --location https://myapi.application.com

How do I execute it in ruby w/o modifying the cmd string to a single cmd ?

Body:
I think that you should add to your cmd before the "\n" de "\" it should be scaped as follows:

[1] pry(main)> cmd = %Q(curl -i
[1] pry(main)* -H 'Authorization: Basic dXNlcjpwYXNzd29yZA=='
[1] pry(main)* -XGET 'http://httpbin.org/basic-auth/user/password')
=> "curl -i\n" + "-H 'Authorization: Basic dXNlcjpwYXNzd29yZA=='\n" + "-XGET 'http://httpbin.org/basic-auth/user/password'"
[2] pry(main)> exec(cmd)
curl: no URL specified!
curl: try 'curl --help' or 'curl --manual' for more information
sh: line 1: -H: command not found
sh: line 2: -XGET: command not found

you should write this:

[1] pry(main)> cmd = %Q(curl -i \\
[1] pry(main)* -H 'Authorization: Basic dXNlcjpwYXNzd29yZA==' \\
[1] pry(main)* -XGET 'http://httpbin.org/basic-auth/user/password')
=> "curl -i \\\n" + "-H 'Authorization: Basic dXNlcjpwYXNzd29yZA==' \\\n" + "-XGET 'http://httpbin.org/basic-auth/user/password'"
[2] pry(main)> exec(cmd)
HTTP/1.1 200 OK
Connection: keep-alive
Server: meinheld/0.6.1
Date: Mon, 05 Jun 2017 09:46:24 GMT
Content-Type: application/json
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
X-Powered-By: Flask
X-Processed-Time: 0.000503063201904
Content-Length: 47
Via: 1.1 vegur

{
  "authenticated": true,
  "user": "user"
}


问:
Is there a JQuery plugin for displaying default text in a text field?
When I hit the page, the text box says "Search...", in gray font.

Then, I click the textbox.  Then, the "search..." disappears. And I can type.

答:
```<code>$("textinput_id").focus(function(){
    $(this).text("");
    });

$("textinput_id").blur(function(){
    $(this).text("Search...");
    });
</code>```


问:
I can't find my Web app when I SSH to my AWS Elastic Beanstalk instance
I've set up SSH to my AWS Elastic Beanstalk instance using

```<code>eb ssh --setup
</code>```

and can successfully SSH to my environment. But I can't see my Web application. When I am connected I find myself in an empty directory (ec2-user) and when  I

```<code>cd /home
</code>```

I just see

```<code>drwx------  3 ec2-user ec2-user 4096 Jan 15 21:37 ec2-user
dr-xr-xr-x 23 root     root     4096 Jan 15 21:03 ..
drwxr-xr-x  3 root     root     4096 Oct 22 23:29 .
</code>```

Where is my Web application located?

答: the content of your WAR is in /var/lib/tomcat8/webapps/ROOT resp. /usr/share/tomcat8/webapps/ROOT

Body:
I've set up SSH to my AWS Elastic Beanstalk instance using

eb ssh --setup

and can successfully SSH to my environment. But I can't see my Web application. When I am connected I find myself in an empty directory (ec2-user) and when  I

cd /home

I just see

drwx------  3 ec2-user ec2-user 4096 Jan 15 21:37 ec2-user
dr-xr-xr-x 23 root     root     4096 Jan 15 21:03 ..
drwxr-xr-x  3 root     root     4096 Oct 22 23:29 .

Where is my Web application located?