问:
Receiving one notification for each tab in browser in foreground with FCM
I'm using FCM API to receive push notifications from browser. The firebase-messaging-sw.js works as expected and messaging.setBackgroundMessageHandler fires only once when the web app is in background. However, when the app is in foreground, I'm receiving one notification for each browser tab (if I have the app opened in 3 tabs, I receive 3 notifications). I wonder how should I handle this, since I can't find any reference to this issue. This is the code for FCM messages in the foreground:

```<code>import NotificationActionCreators from '../actions/NotificationActionCreators';
import NotificationService from './NotificationService';
import LocalStorageService from './LocalStorageService';
import { FIREBASE_SCRIPT, FCM_URL, FCM_API_KEY, FCM_AUTH_DOMAIN, FCM_PROJECT_ID, FCM_SENDER_ID, PUSH_PUBLIC_KEY } from '../constants/Constants';

class ServiceWorkerService {

constructor() {
    this._messaging = null;
    this._subscriptionData = null;
}

// This function is called once
init() {
    this.loadScript(FIREBASE_SCRIPT, () => this.onFirebaseLoaded());
}

onFirebaseLoaded() {
    // Initialize Firebase
    let config = {
        apiKey: FCM_API_KEY,
        authDomain: FCM_AUTH_DOMAIN,
        projectId: FCM_PROJECT_ID,
        messagingSenderId: FCM_SENDER_ID
    };
    firebase.initializeApp(config);
    this._messaging = firebase.messaging();

    this.requestPermission();

    // Callback fired if Instance ID token is updated.
    this._messaging.onTokenRefresh(() => {
        this._messaging.getToken()
            .then((refreshedToken) => {
                console.log('Token refreshed.');
                NotificationActionCreators.unSubscribe(this._subscriptionData).then(() => {
                    // Indicate that the new Instance ID token has not yet been sent to the
                    // app server.
                    this.setTokenSentToServer(false);
                    // Send Instance ID token to app server.
                    this.sendTokenToServer(refreshedToken);
                }, () => console.log('Error unsubscribing user'));
            })
            .catch(function(err) {
                console.log('Unable to retrieve refreshed token ', err);
            });
    });

    // Handle incoming messages.
    // *** THIS IS FIRED ONCE PER TAB ***
    this._messaging.onMessage(function(payload) {
        console.log("Message received. ", payload);
        const data = payload.data;

        NotificationActionCreators.notify(data);
    });
}

requestPermission() {
    console.log('Requesting permission...');
    return this._messaging.requestPermission()
        .then(() => {
            console.log('Notification permission granted.');
            this.getToken();
        })
        .catch(function(err) {
            console.log('Unable to get permission to notify.', err);
        });
}

getToken() {
    // Get Instance ID token. Initially this makes a network call, once retrieved
    // subsequent calls to getToken will return from cache.
    return this._messaging.getToken()
        .then((currentToken) => {
            if (currentToken) {
                this.sendTokenToServer(currentToken);
            } else {
                // Show permission request.
                console.log('No Instance ID token available. Request permission to generate one.');
                this.setTokenSentToServer(false);
            }
        })
        .catch(function(err) {
            console.log('An error occurred while retrieving token. ', err);
            this.setTokenSentToServer(false);
        });
}

sendTokenToServer(currentToken) {
    const subscriptionData = {
        endpoint: FCM_URL + currentToken,
        platform: 'Web'
    };
    if (!this.isTokenSentToServer()) {
        console.log('Sending token to server...');
        this.updateSubscriptionOnServer(subscriptionData);
    } else {
        console.log('Token already sent to server so won\'t send it again ' +
            'unless it changes');
    }
    this._subscriptionData = subscriptionData;
}

isTokenSentToServer() {
    return LocalStorageService.get('sentToServer') == 1;
}

setTokenSentToServer(sent) {
    LocalStorageService.set('sentToServer', sent ? 1 : 0);
}

updateSubscriptionOnServer(subscriptionData) {
    if (subscriptionData) {
        NotificationActionCreators.subscribe(subscriptionData);
        this.setTokenSentToServer(true);
        this._subscriptionData = subscriptionData;
    } else {
        console.log('Not subscribed');
    }
}

unSubscribe() {
    this.removeSetTokenSentToServer();
    return this._messaging.getToken()
        .then((currentToken) => {
            return this._messaging.deleteToken(currentToken)
                .then(() => {
                    console.log('Token deleted.');
                    return NotificationActionCreators.unSubscribe(this._subscriptionData);
                })
                .catch(function(err) {
                    console.log('Unable to delete token. ', err);
                    return new Promise(function(resolve, reject) {
                        reject(error)
                    });
                });
       })
        .catch(function(err) {
            console.log('Error retrieving Instance ID token. ', err);
            return new Promise(function(resolve, reject) {
                reject(error)
            });
        });
    }
}

removeSetTokenSentToServer() {
    LocalStorageService.remove('sentToServer');
}

loadScript = function (url, callback) {
    let head = document.getElementsByTagName('head')[0];
    let script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;

    script.onload = callback;

    // Fire the loading
    head.appendChild(script);
}
}
</code>```

Is there any way to show the notification just for the first tab found?

答:
The only way I've found to achieve this is to check and set a "notification id" variable in the local storage with a setTimeout with a random time:

```<code>this._messaging.onMessage(function(payload) {
    const data = payload.data;
    // This prevents to show one notification for each tab
    setTimeout(() => {
        if (localStorage.getItem('lastNotificationId')) != parseInt(data.notId)) {
            localStorage.setItem('lastNotificationId', parseInt(data.notId))
            NotificationActionCreators.notify(data);
        }
    }, Math.random() * 1000);
});
</code>```

The notId is sent within the push notification and is an identifier for the notification.

Body:
I'm using FCM API to receive push notifications from browser. The firebase-messaging-sw.js works as expected and messaging.setBackgroundMessageHandler fires only once when the web app is in background. However, when the app is in foreground, I'm receiving one notification for each browser tab (if I have the app opened in 3 tabs, I receive 3 notifications). I wonder how should I handle this, since I can't find any reference to this issue. This is the code for FCM messages in the foreground:

import NotificationActionCreators from '../actions/NotificationActionCreators';
import NotificationService from './NotificationService';
import LocalStorageService from './LocalStorageService';
import { FIREBASE_SCRIPT, FCM_URL, FCM_API_KEY, FCM_AUTH_DOMAIN, FCM_PROJECT_ID, FCM_SENDER_ID, PUSH_PUBLIC_KEY } from '../constants/Constants';

class ServiceWorkerService {

constructor() {
    this._messaging = null;
    this._subscriptionData = null;
}

// This function is called once
init() {
    this.loadScript(FIREBASE_SCRIPT, () => this.onFirebaseLoaded());
}

onFirebaseLoaded() {
    // Initialize Firebase
    let config = {
        apiKey: FCM_API_KEY,
        authDomain: FCM_AUTH_DOMAIN,
        projectId: FCM_PROJECT_ID,
        messagingSenderId: FCM_SENDER_ID
    };
    firebase.initializeApp(config);
    this._messaging = firebase.messaging();

    this.requestPermission();

    // Callback fired if Instance ID token is updated.
    this._messaging.onTokenRefresh(() => {
        this._messaging.getToken()
            .then((refreshedToken) => {
                console.log('Token refreshed.');
                NotificationActionCreators.unSubscribe(this._subscriptionData).then(() => {
                    // Indicate that the new Instance ID token has not yet been sent to the
                    // app server.
                    this.setTokenSentToServer(false);
                    // Send Instance ID token to app server.
                    this.sendTokenToServer(refreshedToken);
                }, () => console.log('Error unsubscribing user'));
            })
            .catch(function(err) {
                console.log('Unable to retrieve refreshed token ', err);
            });
    });

    // Handle incoming messages.
    // *** THIS IS FIRED ONCE PER TAB ***
    this._messaging.onMessage(function(payload) {
        console.log("Message received. ", payload);
        const data = payload.data;

        NotificationActionCreators.notify(data);
    });
}

requestPermission() {
    console.log('Requesting permission...');
    return this._messaging.requestPermission()
        .then(() => {
            console.log('Notification permission granted.');
            this.getToken();
        })
        .catch(function(err) {
            console.log('Unable to get permission to notify.', err);
        });
}

getToken() {
    // Get Instance ID token. Initially this makes a network call, once retrieved
    // subsequent calls to getToken will return from cache.
    return this._messaging.getToken()
        .then((currentToken) => {
            if (currentToken) {
                this.sendTokenToServer(currentToken);
            } else {
                // Show permission request.
                console.log('No Instance ID token available. Request permission to generate one.');
                this.setTokenSentToServer(false);
            }
        })
        .catch(function(err) {
            console.log('An error occurred while retrieving token. ', err);
            this.setTokenSentToServer(false);
        });
}

sendTokenToServer(currentToken) {
    const subscriptionData = {
        endpoint: FCM_URL + currentToken,
        platform: 'Web'
    };
    if (!this.isTokenSentToServer()) {
        console.log('Sending token to server...');
        this.updateSubscriptionOnServer(subscriptionData);
    } else {
        console.log('Token already sent to server so won\'t send it again ' +
            'unless it changes');
    }
    this._subscriptionData = subscriptionData;
}

isTokenSentToServer() {
    return LocalStorageService.get('sentToServer') == 1;
}

setTokenSentToServer(sent) {
    LocalStorageService.set('sentToServer', sent ? 1 : 0);
}

updateSubscriptionOnServer(subscriptionData) {
    if (subscriptionData) {
        NotificationActionCreators.subscribe(subscriptionData);
        this.setTokenSentToServer(true);
        this._subscriptionData = subscriptionData;
    } else {
        console.log('Not subscribed');
    }
}

unSubscribe() {
    this.removeSetTokenSentToServer();
    return this._messaging.getToken()
        .then((currentToken) => {
            return this._messaging.deleteToken(currentToken)
                .then(() => {
                    console.log('Token deleted.');
                    return NotificationActionCreators.unSubscribe(this._subscriptionData);
                })
                .catch(function(err) {
                    console.log('Unable to delete token. ', err);
                    return new Promise(function(resolve, reject) {
                        reject(error)
                    });
                });
       })
        .catch(function(err) {
            console.log('Error retrieving Instance ID token. ', err);
            return new Promise(function(resolve, reject) {
                reject(error)
            });
        });
    }
}

removeSetTokenSentToServer() {
    LocalStorageService.remove('sentToServer');
}

loadScript = function (url, callback) {
    let head = document.getElementsByTagName('head')[0];
    let script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;

    script.onload = callback;

    // Fire the loading
    head.appendChild(script);
}
}

Is there any way to show the notification just for the first tab found?

Body:
The only way I've found to achieve this is to check and set a "notification id" variable in the local storage with a setTimeout with a random time:

this._messaging.onMessage(function(payload) {
    const data = payload.data;
    // This prevents to show one notification for each tab
    setTimeout(() => {
        if (localStorage.getItem('lastNotificationId')) != parseInt(data.notId)) {
            localStorage.setItem('lastNotificationId', parseInt(data.notId))
            NotificationActionCreators.notify(data);
        }
    }, Math.random() * 1000);
});

The notId is sent within the push notification and is an identifier for the notification.


来源: stackexchange

问:
Backdrop-filter in chrome has black border
I tried to add the future-property backdrop-filter in chrome:

```<code>.glass {
    --webkit-backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    backdrop-filter: blur(10px); /* chrome */
}
</code>```

After activating it in chrome://flags/#enable-experimental-web-platform-features it finally works, but, I get a black border. Anybody an idea how to remove that border??

Edit

There is no zero-data-bug or something (tested with the SO-page):

If I take 3px instead of 10px the border is smaller, but not away:

Here is a fiddle but better, you copy it local, because fiddle also just the right boder in example. Then it looks like this:

答:
This is caused by rendering bugs in Chrome as described in comments above, and is unfixable as of now.

With a bit of mucking around, you can cheat it somewhat, but it doesn't behave entirely correctly.

This Fiddle was one of my many attempts, but it only alleviates the problem. You can't entirely fix it.
By carefully controlling where the effect starts and ends, you can avoid chrome reading outside the bounds of the window and blending black, at the expense of a few pixels at the end.

```<code>    .frontcontainer{
        position: fixed;
        width: 100%;
        height: 100%;
    }

    .front1{
        position: relative;
        right: 3px;
        width: calc(100% - 6px);
        backdrop-filter: blur(3px);
    }
</code>```

I also tried layering divs on top of each other and using a lighter blur towards the edge, which would have worked, while not being 100% right, but the layered background blurs don't interact correctly, or consistently.

ContentLicense: CC BY-SA 3.0

Body:
I tried to add the future-property backdrop-filter in chrome:

.glass {
    --webkit-backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    backdrop-filter: blur(10px); /* chrome */
}

After activating it in chrome://flags/#enable-experimental-web-platform-features it finally works, but, I get a black border. Anybody an idea how to remove that border??

Edit

There is no zero-data-bug or something (tested with the SO-page):

If I take 3px instead of 10px the border is smaller, but not away:

Here is a fiddle but better, you copy it local, because fiddle also just the right boder in example. Then it looks like this:

Body:
This is caused by rendering bugs in Chrome as described in comments above, and is unfixable as of now.

With a bit of mucking around, you can cheat it somewhat, but it doesn't behave entirely correctly.

This Fiddle was one of my many attempts, but it only alleviates the problem. You can't entirely fix it.
By carefully controlling where the effect starts and ends, you can avoid chrome reading outside the bounds of the window and blending black, at the expense of a few pixels at the end.

    .frontcontainer{
        position: fixed;
        width: 100%;
        height: 100%;
    }

    .front1{
        position: relative;
        right: 3px;
        width: calc(100% - 6px);
        backdrop-filter: blur(3px);
    }

I also tried layering divs on top of each other and using a lighter blur towards the edge, which would have worked, while not being 100% right, but the layered background blurs don't interact correctly, or consistently.


问:
Select from Two tables
I have two tables Table A and Table B.

I want to select the sum columns of each Code between two month and year=2017 for TableA as A and TableB as B, but i want select all row from TableB as C where Year=2017 without filter of month.

below what i have tried :

```<code>SELECT  A.Annee as Year,
        code_ville as Code,
        SUM(UniteVendu) AS Unit,
        SUM(CAVendu) AS CA,
        SUM(B.UniteVentePrev) AS Unit_P,
        SUM(B.CAVentePrev) AS Ca_P,
        SUM(C.UniteVentePrev) AS Unit_PPP,
        SUM(C.CAVentePrev) AS Ca_PPP
 FROM   TableA A
   left join TableB B on A.code=B.codeP
                     and  A.Annee=PP.Annee
                     and A.mois =B.mois
   left join TableB C on A.code=C.codeP
                     and A.Annee=C.Annee
 where  A.Annee = 2017
 and    A.mois >= 1
 and    A.mois <= 3
 GROUP BY  R.Annee,
           code_ville
</code>```

But I get the incorrect results.

答:
I think I understand your requirements here and if I do they are actually rather simple.  Initially, you need to get your list of Year and Code combinations so you can build a final results dataset from them, joining into both your TableA and TableB and doing some conditional sum calculations.

Note that I have added some additional data to display the full functionality of my approach:

```<code>-- Built test data
declare @a table([Year] int,[Month] int,Code int, Unit int, CA decimal(20,2));
declare @b table([Year] int,[Month] int,CodeP int, Unit_P int, CA_P decimal(20,0));
insert into @a values (2017,1,280,1,298259.42),(2017,1,281,0,0),(2017,2,280,1,298220.99),(2017,2,281,0,0),(2017,3,282,0,0),(2017,3,280,1,298033.09),(2017,4,280,1,298000.00);
insert into @b values (2017,1,280,1,250000),(2017,1,280,3,950000),(2017,3,281,1,250000),(2017,3,282,1,250000),(2017,6,282,1,250000);

-- Derived table to get all combinations of Year and Code across both tables
with y as
(
    select [Year]
          ,Code
    from @a
    union    -- Use of UNION ensures that a unique list is returned.
    select [Year]
          ,CodeP
    from @b
)
select y.[Year]
      ,y.Code
      ,sum(case when a.[Month] between 1 and 3 then a.Unit else 0 end) as Unit
      ,sum(case when a.[Month] between 1 and 3 then a.CA else 0 end) as CA
      ,sum(case when b.[Month] between 1 and 3 then b.Unit_P else 0 end) as Unit_P
      ,sum(case when b.[Month] between 1 and 3 then b.CA_P else 0 end) as CA_P
      ,isnull(sum(a.Unit),0) as Unit_PPP
      ,isnull(sum(a.CA),0) as CA_PPP
from y  -- Then join this list onto both tables to get the totals
    left join @a a
        on(y.[Year] = a.[Year]
            and y.Code = a.Code
            )
    left join @b b
        on(y.[Year] = b.[Year]
            and y.Code = b.CodeP
            )
group by y.[Year]
        ,y.Code
order by y.[Year]
        ,y.Code;
</code>```

Output:

```<code>+------+------+------+------------+--------+---------+----------+------------+
| Year | Code | Unit |     CA     | Unit_P |  CA_P   | Unit_PPP |   CA_PPP   |
+------+------+------+------------+--------+---------+----------+------------+
| 2017 |  280 |    6 | 1789027.00 |     16 | 4800000 |        8 | 2385027.00 |
| 2017 |  281 |    0 |       0.00 |      2 |  500000 |        0 |       0.00 |
| 2017 |  282 |    0 |       0.00 |      1 |  250000 |        0 |       0.00 |
+------+------+------+------------+--------+---------+----------+------------+
</code>```

Title: Select from Two tables

Body:
I have two tables Table A and Table B.

I want to select the sum columns of each Code between two month and year=2017 for TableA as A and TableB as B, but i want select all row from TableB as C where Year=2017 without filter of month.

below what i have tried :

SELECT  A.Annee as Year,
        code_ville as Code,
        SUM(UniteVendu) AS Unit,
        SUM(CAVendu) AS CA,
        SUM(B.UniteVentePrev) AS Unit_P,
        SUM(B.CAVentePrev) AS Ca_P,
        SUM(C.UniteVentePrev) AS Unit_PPP,
        SUM(C.CAVentePrev) AS Ca_PPP
 FROM   TableA A
   left join TableB B on A.code=B.codeP
                     and  A.Annee=PP.Annee
                     and A.mois =B.mois
   left join TableB C on A.code=C.codeP
                     and A.Annee=C.Annee
 where  A.Annee = 2017
 and    A.mois >= 1
 and    A.mois <= 3
 GROUP BY  R.Annee,
           code_ville

But I get the incorrect results.

Body:
I think I understand your requirements here and if I do they are actually rather simple.  Initially, you need to get your list of Year and Code combinations so you can build a final results dataset from them, joining into both your TableA and TableB and doing some conditional sum calculations.

Note that I have added some additional data to display the full functionality of my approach:

-- Built test data
declare @a table([Year] int,[Month] int,Code int, Unit int, CA decimal(20,2));
declare @b table([Year] int,[Month] int,CodeP int, Unit_P int, CA_P decimal(20,0));
insert into @a values (2017,1,280,1,298259.42),(2017,1,281,0,0),(2017,2,280,1,298220.99),(2017,2,281,0,0),(2017,3,282,0,0),(2017,3,280,1,298033.09),(2017,4,280,1,298000.00);
insert into @b values (2017,1,280,1,250000),(2017,1,280,3,950000),(2017,3,281,1,250000),(2017,3,282,1,250000),(2017,6,282,1,250000);

-- Derived table to get all combinations of Year and Code across both tables
with y as
(
    select [Year]
          ,Code
    from @a
    union    -- Use of UNION ensures that a unique list is returned.
    select [Year]
          ,CodeP
    from @b
)
select y.[Year]
      ,y.Code
      ,sum(case when a.[Month] between 1 and 3 then a.Unit else 0 end) as Unit
      ,sum(case when a.[Month] between 1 and 3 then a.CA else 0 end) as CA
      ,sum(case when b.[Month] between 1 and 3 then b.Unit_P else 0 end) as Unit_P
      ,sum(case when b.[Month] between 1 and 3 then b.CA_P else 0 end) as CA_P
      ,isnull(sum(a.Unit),0) as Unit_PPP
      ,isnull(sum(a.CA),0) as CA_PPP
from y  -- Then join this list onto both tables to get the totals
    left join @a a
        on(y.[Year] = a.[Year]
            and y.Code = a.Code
            )
    left join @b b
        on(y.[Year] = b.[Year]
            and y.Code = b.CodeP
            )
group by y.[Year]
        ,y.Code
order by y.[Year]
        ,y.Code;

Output:

+------+------+------+------------+--------+---------+----------+------------+
| Year | Code | Unit |     CA     | Unit_P |  CA_P   | Unit_PPP |   CA_PPP   |
+------+------+------+------------+--------+---------+----------+------------+
| 2017 |  280 |    6 | 1789027.00 |     16 | 4800000 |        8 | 2385027.00 |
| 2017 |  281 |    0 |       0.00 |      2 |  500000 |        0 |       0.00 |
| 2017 |  282 |    0 |       0.00 |      1 |  250000 |        0 |       0.00 |
+------+------+------+------------+--------+---------+----------+------------+


问:
PostgreSQL: Sorting on alphanumeric string and decimal field
Hope you all are fine and doing good!

I have a table items with 2 million+ records the structure looks like below:

```<code>id (int) | price (decimal) | priority (int)
-------------------------------------------
10001    |  59000.25       |    1
10002    |  73000.91       |    2
10003    |  1000.23        |    1
10004    |  9567.18        |    1
</code>```

The solution that I am looking for is very straightforward: How do I sort this table on price+priority on ASC|DESC order?

Current and working solution: I am using ORDER BY priority ASC, price ASC. But as far as my knowledge goes, sorting on multiple column is slow and not optimised approach (and I am facing realtime slowness because of this).

Solutions I tried: I've added a temporary column to this table:

```<code>id (int) | price (decimal) | priority (int) | new_priority (varchar)
--------------------------------------------------------------------
10001    |  59000.25       |    1           | a59000.25
10002    |  73000.91       |    2           | b73000.91
10003    |  1000.23        |    1           | a1000.23
10004    |  9567.18        |    1           | a9567.18
</code>```

I've replaced 1 => a, 2 => b, 3 => c up till 10 (max number I have in database)

Now, whenever I am trying below SQLs, none of them is working

```<code>SELECT * FROM items
ORDER BY new_priority ASC

SELECT * FROM items
ORDER BY new_priority::bytea

SELECT * FROM items
ORDER BY SUBSTRING(new_priority FROM '^(.*?)( \\d+)?$'),
     COALESCE(SUBSTRING(new_priority FROM ' (\\d+)$')::INTEGER, 0)
</code>```

Please advise!

Links I referred:

Postgresql sorting mixed alphanumeric data

Alphanumeric Sorting in PostgreSQL

Alphanumeric sorting with PostgreSQL

Alphanumeric case in-sensitive sorting in postgres

答:
How often does the data change ? If it's not often, use CLUSTER.
See : https://www.postgresql.org/docs/9.5/static/sql-cluster.html
It will basically sort your table in the order of your index.
Combine this cluster with the answer from etsa.

The catch is, the CLUSTER doesn't maintain the order.
So if you have new row inserted, it will be inserted to the last row.

Body:
Hope you all are fine and doing good!

I have a table items with 2 million+ records the structure looks like below:

id (int) | price (decimal) | priority (int)
-------------------------------------------
10001    |  59000.25       |    1
10002    |  73000.91       |    2
10003    |  1000.23        |    1
10004    |  9567.18        |    1

The solution that I am looking for is very straightforward: How do I sort this table on price+priority on ASC|DESC order?

Current and working solution: I am using ORDER BY priority ASC, price ASC. But as far as my knowledge goes, sorting on multiple column is slow and not optimised approach (and I am facing realtime slowness because of this).

Solutions I tried: I've added a temporary column to this table:

id (int) | price (decimal) | priority (int) | new_priority (varchar)
--------------------------------------------------------------------
10001    |  59000.25       |    1           | a59000.25
10002    |  73000.91       |    2           | b73000.91
10003    |  1000.23        |    1           | a1000.23
10004    |  9567.18        |    1           | a9567.18

I've replaced 1 => a, 2 => b, 3 => c up till 10 (max number I have in database)

Now, whenever I am trying below SQLs, none of them is working

SELECT * FROM items
ORDER BY new_priority ASC

SELECT * FROM items
ORDER BY new_priority::bytea

SELECT * FROM items
ORDER BY SUBSTRING(new_priority FROM '^(.*?)( \\d+)?$'),
     COALESCE(SUBSTRING(new_priority FROM ' (\\d+)$')::INTEGER, 0)

Please advise!

Links I referred:

Postgresql sorting mixed alphanumeric data

Alphanumeric Sorting in PostgreSQL

Alphanumeric sorting with PostgreSQL

Alphanumeric case in-sensitive sorting in postgres


问:
C# for loop to delete strings containing 'TJ' deletes only one of the Strings containing it
I am trying to create a method that deletes all Sales objects if they have a material description that includes "TJ" somewhere in the string. My problem is that when I create a List with four Sales, two of which include "TJ" in their description, only one is deleted. The one being deleted is not unique to the first one. if I delete the "TJ" from the first Sale the second Sale is then deleted correctly. Why does this occur? My method, along with the TestCase is below. </p>

```<code>/// <summary>
/// This method deletes all sales with a 'TJ' material.
/// </summary>
public void deleteTJ()
{
    for (int i = 0; i < salesList.Count; i++)
    {
        if (salesList[i].material.Contains("TJ"))
        {
            salesList.Remove(salesList[i]);
            Console.WriteLine("FOUND IT");
        }
        else
        {
            Console.WriteLine("Not this time");
        }
    }
}

    [TestMethod]
    public void TestDeleteTJ()
    {
        sale1.material = "ABJFSJTJ"; // Contains TJ
        sale2.material = "KTJANDKFH"; // Contains TJ
        sale3.material = "SADVUAWDJ"; // No TJ
        sale4.material = "JTNDBAYK"; // No TJ

        testList.Add(sale1);
        testList.Add(sale2);
        testList.Add(sale3);
        testList.Add(sale4);

        Modifier modifier = new Modifier(testList);

        Assert.IsTrue(testList.Count == 4);

        modifier.deleteTJ();

        Assert.IsTrue(testList.Count == 2);
        Assert.AreEqual("SADVUAWDJ", testList[0]);
        Assert.AreEqual("JTNDBAYK", testList[1]);
    }
</code>```

答:
Your issue stems from your loop.

```<code>for(int index = 0; index < collection.Count; index++)
     if(collection[index].Contains("TJ")
          collection.Remove(...)
</code>```

So in your code, you are physically removing an index from your collection.  The problem though, is you're iterating through the array.  So you can solve a couple of ways:

Create a copy of your collection, then remove from the one you aren't iterating through.

You could use Linq, it would remove all the "TJ" contained elements from the collection.

Example 1:

```<code>var filter = collection;
for(int index = 0; index < collection.Count; index++)
    if(collection[index].Material.Contains("TJ"))
         filter.Remove(..);
</code>```

Example 2:

```<code>var filter = collection.Where(item => !item.Material.Contains("TJ"));
</code>```

Example 3:

```<code>  var filter = collection.RemoveAll(item => item.Material.Contains("TJ");
</code>```

Body:
I am trying to create a method that deletes all Sales objects if they have a material description that includes "TJ" somewhere in the string. My problem is that when I create a List with four Sales, two of which include "TJ" in their description, only one is deleted. The one being deleted is not unique to the first one. if I delete the "TJ" from the first Sale the second Sale is then deleted correctly. Why does this occur? My method, along with the TestCase is below.

///
/// This method deletes all sales with a 'TJ' material.
///
public void deleteTJ()
{
    for (int i = 0; i < salesList.Count; i++)
    {
        if (salesList[i].material.Contains("TJ"))
        {
            salesList.Remove(salesList[i]);
            Console.WriteLine("FOUND IT");
        }
        else
        {
            Console.WriteLine("Not this time");
        }
    }
}

    [TestMethod]
    public void TestDeleteTJ()
    {
        sale1.material = "ABJFSJTJ"; // Contains TJ
        sale2.material = "KTJANDKFH"; // Contains TJ
        sale3.material = "SADVUAWDJ"; // No TJ
        sale4.material = "JTNDBAYK"; // No TJ

        testList.Add(sale1);
        testList.Add(sale2);
        testList.Add(sale3);
        testList.Add(sale4);

        Modifier modifier = new Modifier(testList);

        Assert.IsTrue(testList.Count == 4);

        modifier.deleteTJ();

        Assert.IsTrue(testList.Count == 2);
        Assert.AreEqual("SADVUAWDJ", testList[0]);
        Assert.AreEqual("JTNDBAYK", testList[1]);
    }

Body:
Your issue stems from your loop.

for(int index = 0; index < collection.Count; index++)
     if(collection[index].Contains("TJ")
          collection.Remove(...)

So in your code, you are physically removing an index from your collection.  The problem though, is you're iterating through the array.  So you can solve a couple of ways:

Create a copy of your collection, then remove from the one you aren't iterating through.

You could use Linq, it would remove all the "TJ" contained elements from the collection.

Example 1:

var filter = collection;
for(int index = 0; index < collection.Count; index++)
    if(collection[index].Material.Contains("TJ"))
         filter.Remove(..);

Example 2:

var filter = collection.Where(item => !item.Material.Contains("TJ"));

Example 3:

  var filter = collection.RemoveAll(item => item.Material.Contains("TJ");


问:
Sending a slash through mysql
I'm not sure why this has stumped me. I have the following code

```<code>$website = "http://www.google.com";
$name = "Person";

if(!empty($website) {
   $name = "[url=$website]$name[/url]";
}
</code>```

Then i try to insert that into mysql. I tried adding mysql_real_escape_string to both $website and $name (after the if statement), thinking the "/url" might also cause problems.

```<code>$name       = mysql_real_escape_string($name);
</code>```

Still no luck though. Any advice? What am I missing? It's giving me this error

"Parse error: syntax error, unexpected '/', expecting T_STRING or T_VARIABLE or T_NUM_STRING"

答:
Make sure you're quoting values you send into a query, like so:

```<code>$sql = "INSERT INTO table (column) VALUES ('$value')";
</code>```

Whatever is in $value gets passed into the query. If you leave out the quotes, bad things may happen even if you use mysql_real_escape_string(). Inside strings, forward slashes do not have any special meaning in MySQL, and so mysql_real_escape_string() leaves them intact. This is not a bug, but the documented, correct behaviour. Basically, you need to quote all values in your query.

However, the best solution IMHO is to use PDO and its parametrized queries instead of the mysql_XXX API. It's a bit more complicated (not much though), and it allows you to pass parameters into a query through an associative array, doing all the escaping and quoting you need for you.

ContentLicense: CC BY-SA 2.5

Title: Sending a slash through mysql

Body:
I'm not sure why this has stumped me. I have the following code

$website = "http://www.google.com";
$name = "Person";

if(!empty($website) {
   $name = "[url=$website]$name[/url]";
}

Then i try to insert that into mysql. I tried adding mysql_real_escape_string to both $website and $name (after the if statement), thinking the "/url" might also cause problems.

$name       = mysql_real_escape_string($name);

Still no luck though. Any advice? What am I missing? It's giving me this error

"Parse error: syntax error, unexpected '/', expecting T_STRING or T_VARIABLE or T_NUM_STRING"

Body:
Make sure you're quoting values you send into a query, like so:

$sql = "INSERT INTO table (column) VALUES ('$value')";

Whatever is in $value gets passed into the query. If you leave out the quotes, bad things may happen even if you use mysql_real_escape_string(). Inside strings, forward slashes do not have any special meaning in MySQL, and so mysql_real_escape_string() leaves them intact. This is not a bug, but the documented, correct behaviour. Basically, you need to quote all values in your query.

However, the best solution IMHO is to use PDO and its parametrized queries instead of the mysql_XXX API. It's a bit more complicated (not much though), and it allows you to pass parameters into a query through an associative array, doing all the escaping and quoting you need for you.


问:
Set value of boolean (type = bit(1)) in Mysql Workbench
How can I edit the value of a boolean (type = bit(1)) in Mysql Workbench's result grid of a table?

If I set it to 1 or 0 I get the error :

ERROR 1406: 1406: Data too long for column 'enabled' at row 1

答:
You can also use true false keywords for value where true = 1 and false = 0.

MySQL Workbench Version: 6.3.4.0

UPDATE

Mysql Server Version: 5.6.27-log


问:
How to get the currently logged in username from a remote computer
Is there a way to get the currently logged in username from a remote computer? (I'm looking for something along the line of getUserName())

I've got a solution that kinda works but (to be brutally honest) feels like killing a fly with a cruise missile shot from a skateboard (complicated, definitely taking to long and probably overkill).

My solution (so far):

```<code>QString NetworkHandle::getUserName(QString entry){
    QString s1, s2, command;
    std::string temp, line;
    const char *cmd;
    char buf[BUFSIZ];
    FILE *ptr, *file;
    int c;

    s1 = "wmic.exe /node:";
    s2 = " computersystem get username 2> nul";
    command = s1 + entry + s2;
    temp = command.toLocal8Bit().constData();
    cmd = temp.c_str();

    file = fopen("buffer.txt", "w");

    if(!file){
        this->setErrLvl(3);
        return "ERROR";
    }

    if((ptr = popen(cmd, "r")) != NULL){
        while (fgets(buf, BUFSIZ, ptr) != NULL){
            fprintf(file, "%s", buf);
        }
        pclose(ptr);
    }
    fclose(file);

    std::ifstream input("buffer.txt");
    c = 0;

    if(!input){
        this->setErrLvl(4);
        return "ERROR";
    }

    while(!input.eof()){
        std::getline(input, line);
        if(c == 1 && line.size() > 1){
            input.close();
            entry = QString::fromUtf8(line.data(), line.size());
            return entry;
        }
        c++;
    }
    input.close();
    std::remove("buffer.txt");
    return "Could not return Username.";
}
</code>```

Like i said: just a tad on the extremly unpractial side.

The methode gets a QString with the IP-Address, combines it with wmic.exe /node: and  computersystem get username 2> nul and writes the output from wmic.exe into a text-file, reads the required line (the second), shortens the string to the necessary information and returns said information (the User-name)

Now my problem is the following: This is all fine and dandy if i just want to get one username or so during runtime... which i don't. I need to fill an entire table (containing up to 200 or more entries, depending on network activity) which takes somewhere between 10 to 15 minutes.

Now my program handles getting the IP and computername collection via sockets but i'm new to this type of programming (tbh: i just started C++ coming from C and i never did any network-related programming stuff) so i'm not that deep in the matter.

Is there a way to get the currently logged in username on a remote computer via socket?

答:
You can use QProcess to handle wmic.exe tool like this:

```<code>void NetworkHandle::getUserName(QString entry)
{
    QProcess *wmic_process = new QProcess();
    wmic_process->setProgram("wmic.exe");
    wmic_process->setArguments(QStringList() << QString("/node:%1").arg(entry) << "computersystem" << "get" << "username");
    wmic_process->setProperty("ip_address", entry);

    connect(wmic_process, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(parseUserName(int,QProcess::ExitStatus)) );
    wmic_process->start();
}

void NetworkHandle::parseUserName(int exitCode, QProcess::ExitStatus exitStatus)
{
    QProcess *process = dynamic_cast<QProcess*>(sender());
    if (exitStatus == QProcess::NormalExit)
    {
        qDebug() << "information for node" << process->property("ip_address").toString();
        qDebug() << process->readAllStandardOutput();
    }
    process->deleteLater();
}
</code>```

Body:
Is there a way to get the currently logged in username from a remote computer? (I'm looking for something along the line of getUserName())

I've got a solution that kinda works but (to be brutally honest) feels like killing a fly with a cruise missile shot from a skateboard (complicated, definitely taking to long and probably overkill).

My solution (so far):

QString NetworkHandle::getUserName(QString entry){
    QString s1, s2, command;
    std::string temp, line;
    const char *cmd;
    char buf[BUFSIZ];
    FILE *ptr, *file;
    int c;

    s1 = "wmic.exe /node:";
    s2 = " computersystem get username 2> nul";
    command = s1 + entry + s2;
    temp = command.toLocal8Bit().constData();
    cmd = temp.c_str();

    file = fopen("buffer.txt", "w");

    if(!file){
        this->setErrLvl(3);
        return "ERROR";
    }

    if((ptr = popen(cmd, "r")) != NULL){
        while (fgets(buf, BUFSIZ, ptr) != NULL){
            fprintf(file, "%s", buf);
        }
        pclose(ptr);
    }
    fclose(file);

    std::ifstream input("buffer.txt");
    c = 0;

    if(!input){
        this->setErrLvl(4);
        return "ERROR";
    }

    while(!input.eof()){
        std::getline(input, line);
        if(c == 1 && line.size() > 1){
            input.close();
            entry = QString::fromUtf8(line.data(), line.size());
            return entry;
        }
        c++;
    }
    input.close();
    std::remove("buffer.txt");
    return "Could not return Username.";
}

Like i said: just a tad on the extremly unpractial side.

The methode gets a QString with the IP-Address, combines it with wmic.exe /node: and  computersystem get username 2> nul and writes the output from wmic.exe into a text-file, reads the required line (the second), shortens the string to the necessary information and returns said information (the User-name)

Now my problem is the following: This is all fine and dandy if i just want to get one username or so during runtime... which i don't. I need to fill an entire table (containing up to 200 or more entries, depending on network activity) which takes somewhere between 10 to 15 minutes.

Now my program handles getting the IP and computername collection via sockets but i'm new to this type of programming (tbh: i just started C++ coming from C and i never did any network-related programming stuff) so i'm not that deep in the matter.

Is there a way to get the currently logged in username on a remote computer via socket?

Body:
You can use QProcess to handle wmic.exe tool like this:

void NetworkHandle::getUserName(QString entry)
{
    QProcess *wmic_process = new QProcess();
    wmic_process->setProgram("wmic.exe");
    wmic_process->setArguments(QStringList() << QString("/node:%1").arg(entry) << "computersystem" << "get" << "username");
    wmic_process->setProperty("ip_address", entry);

    connect(wmic_process, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(parseUserName(int,QProcess::ExitStatus)) );
    wmic_process->start();
}

void NetworkHandle::parseUserName(int exitCode, QProcess::ExitStatus exitStatus)
{
    QProcess *process = dynamic_cast<QProcess*>(sender());
    if (exitStatus == QProcess::NormalExit)
    {
        qDebug() << "information for node" << process->property("ip_address").toString();
        qDebug() << process->readAllStandardOutput();
    }
    process->deleteLater();
}


问:
Is there an elegant way to extract individual words from variable names into an array?
Basically I want to do this:

I get a string "myVariableName" and turn it into: ["my", "variable", "name"]

I tried doing this using regex, but I get a lot of undefineds in my ending array it seems. The two possible cases for variable names are camel-case and upper snake-case in this situation.

```<code>const matchVariableNames =  /(\b[a-z]+)|([A-Z][a-z]+)|(\b[A-Z]+)|(_[A-Z]+)/g;
const variableName = 'myVariable';
let words = [];
let regexMatches;

while (regexMatches = matchVariableNames.exec(variableName)) {
  regexMatches.forEach((match) => {
    words.push(match);
  });
};
</code>```

outputs:

```<code>["my", "my", undefined, undefined, undefined, "Variable", undefined, "Variable", undefined, undefined]
undefined
</code>```

答:
I've created this:

```<code>x = 'myVariableName';
const isUpper = e => (e === e.toUpperCase());
[].reduce.call(x, (words, letter, i) => {
  if(isUpper(letter)) words.push([letter]);
  else {
    let length = words.length-1,
        word = words[length];
    words[length] = word+letter;
  }
  return words;
}, [[]]);
</code>```

Returns ["my", "Variable", "Name"]

Is it very elegant? We can fight about it, but I'm sure more than your RegExp. :P

Body:
Basically I want to do this:

I get a string "myVariableName" and turn it into: ["my", "variable", "name"]

I tried doing this using regex, but I get a lot of undefineds in my ending array it seems. The two possible cases for variable names are camel-case and upper snake-case in this situation.

const matchVariableNames =  /(\b[a-z]+)|([A-Z][a-z]+)|(\b[A-Z]+)|(_[A-Z]+)/g;
const variableName = 'myVariable';
let words = [];
let regexMatches;

while (regexMatches = matchVariableNames.exec(variableName)) {
  regexMatches.forEach((match) => {
    words.push(match);
  });
};

outputs:

["my", "my", undefined, undefined, undefined, "Variable", undefined, "Variable", undefined, undefined]
undefined

Body:
I've created this:

x = 'myVariableName';
const isUpper = e => (e === e.toUpperCase());
[].reduce.call(x, (words, letter, i) => {
  if(isUpper(letter)) words.push([letter]);
  else {
    let length = words.length-1,
        word = words[length];
    words[length] = word+letter;
  }
  return words;
}, [[]]);

Returns ["my", "Variable", "Name"]

Is it very elegant? We can fight about it, but I'm sure more than your RegExp. :P


答:
If I understand correctly what you are trying to do, you can achieve it using the Pandas library: you need to read the input data into a DataFrame (it should handle correctly the date format), and then make use of the groupby method (see doc here).

A simple example for the case of your csv file is here (you'll probably want to additionally change the format of ticks, etc.):

```<code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

infile = "foo.csv"

# Read in the file to a Pandas 'DataFrame'
df = pd.read_csv(infile)

# Group the different entries by the content of the
# Country/Pais column
dfg = df.groupby('Pais')

fig, ax = plt.subplots()

# Loop over group names (country names),
# and plot each one separately (assigning the appropriate label)
for country in dfg.groups.keys():
    thisdf = dfg.get_group(country)
    ax.plot_date(thisdf['Fecha'], thisdf['count'], 'o-', label=country)

ax.legend()
fig.autofmt_xdate()

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

And here is the result (for a minimal version of your input file):

Title: Plot values by date showed by a string

Body:
I can´t find how to plot values by a string into a time chart.

Here is my data.

The input (from csv):

Fecha,Pais,count
"20/05/2017",Brazil,1
"20/05/2017",China,821
"20/05/2017",Czechia,31
"20/05/2017",France,1
"20/05/2017","Republic of Korea",1
"21/05/2017",Argentina,5
"21/05/2017",Australia,2
"21/05/2017",China,3043
"21/05/2017",Denmark,1
"21/05/2017",Egypt,1
...
..
.

I have imported al the data from the CSV with the Date, String and Integer values parsed well:

DatetimeIndex(['2017-05-20', '2017-05-20', '2017-05-20', '2017-05-20',
               '2017-05-20', '2017-05-21', '2017-05-21', '2017-05-21',
               '2017-05-21', '2017-05-21', '2017-05-21', '2017-05-21',
               '2017-05-21', '2017-05-21', '2017-05-21', '2017-05-21',
               '2017-05-21', '2017-05-21', '2017-05-21', '2017-05-21',
               '2017-05-22', '2017-05-22', '2017-05-22', '2017-05-22',
               '2017-05-22', '2017-05-22', '2017-05-22', '2017-05-22',
               '2017-05-22', '2017-05-22', '2017-05-22', '2017-05-22',
               '2017-05-22', '2017-05-22', '2017-05-22', '2017-05-22'],
              dtype='datetime64[ns]', freq=None)
['Brazil' 'China' 'Czechia' 'France' 'Republic of Korea' 'Argentina'
 'Australia' 'China' 'Denmark' 'Egypt' 'France' 'Hungary' 'Netherlands'
 'Oman' 'Republic of Korea' 'Russia' 'Slovak Republic' 'Taiwan' 'Ukraine'
 'United Arab Emirates' 'Argentina' 'Brazil' 'China' 'Czechia' 'Ecuador'
 'France' 'Germany' 'India' 'Latvia' 'Liberia' 'Pakistan' 'Peru'
 'Republic of Korea' 'Russia' 'Taiwan' 'Ukraine']
['1' '821' '31' '1' '1' '5' '2' '3043' '1' '1' '1' '1' '1' '1' '1' '1' '1'
 '3' '48' '1' '2' '1' '3759' '79' '2' '1' '3' '1' '192' '1' '1' '1' '1' '2'
 '1' '1']

In fact I have the plot:

but, I can´t join the values by the same country, plotting the history by each in the date that contains data.

Here is my code:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from  matplotlib.dates import DateFormatter, DayLocator, AutoDateLocator, AutoDateFormatter
import datetime

locator = DayLocator()
formatter = AutoDateFormatter(locator)

date, country, count = np.loadtxt("72hcountcountry.csv",
                                  delimiter=',',
                                  unpack=True,
                                  dtype='string',
                                  skiprows=1)

date = np.char.replace (date, '"', '')
country = np.char.replace (country, '"', '')
date2 = pd.to_datetime(date, format="%d/%m/%Y")

print date2
print country
print count

fig, ax = plt.subplots()

ax.plot_date(date2, count)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)
ax.autoscale_view()

ax.grid(True)
fig.autofmt_xdate()

plt.show()

How can I separate each country plotting with line each date with data?

Body:
If I understand correctly what you are trying to do, you can achieve it using the Pandas library: you need to read the input data into a DataFrame (it should handle correctly the date format), and then make use of the groupby method (see doc here).

A simple example for the case of your csv file is here (you'll probably want to additionally change the format of ticks, etc.):

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

infile = "foo.csv"

# Read in the file to a Pandas 'DataFrame'
df = pd.read_csv(infile)

# Group the different entries by the content of the
# Country/Pais column
dfg = df.groupby('Pais')

fig, ax = plt.subplots()

# Loop over group names (country names),
# and plot each one separately (assigning the appropriate label)
for country in dfg.groups.keys():
    thisdf = dfg.get_group(country)
    ax.plot_date(thisdf['Fecha'], thisdf['count'], 'o-', label=country)

ax.legend()
fig.autofmt_xdate()

plt.show()

And here is the result (for a minimal version of your input file):


问:
Strange UI behavior after double-click
I have HTML code which utilize KnockoutJS for data binding and DOM manipulation. One of them is to highlight (single-click) and execute an action on double-click. All works fine except after double-click and hiding and showing some DIVs first word in a new spawned DIV is highlighted no clue why.

Code for highlighting and selection looks like:

```<code> <tr data-bind="attr: { id: resource.id},
                css: {'isSelected':$root.selRow() == $data},
                click: $parent.highlightRow.bind($parent),
                event : { dblclick: $parent.selectRow.bind($parent) }" >
</code>```

I have tired to "unselect" it by executing click() event on a highlighted element but looks like is not working

```<code>    setTimeout(function(){
            $(".first_name").click();
            console.log("Clicked!");
        }, 3000);
</code>```

答:
You didn't mentioned which browser your are using here.

Please update the css with following styles for different browsers:

```<code>-webkit-user-select: none; /* webkit (safari, chrome) browsers */
-moz-user-select: none; /* mozilla browsers */
-khtml-user-select: none; /* webkit (konqueror) browsers */
-ms-user-select: none; /* IE10+ */
</code>```

Title: Strange UI behavior after double-click

Body:
I have HTML code which utilize KnockoutJS for data binding and DOM manipulation. One of them is to highlight (single-click) and execute an action on double-click. All works fine except after double-click and hiding and showing some DIVs first word in a new spawned DIV is highlighted no clue why.

Code for highlighting and selection looks like:

I have tired to "unselect" it by executing click() event on a highlighted element but looks like is not working

    setTimeout(function(){
            $(".first_name").click();
            console.log("Clicked!");
        }, 3000);

Body:
You didn't mentioned which browser your are using here.

Please update the css with following styles for different browsers:

-webkit-user-select: none; /* webkit (safari, chrome) browsers */
-moz-user-select: none; /* mozilla browsers */
-khtml-user-select: none; /* webkit (konqueror) browsers */
-ms-user-select: none; /* IE10+ */


问:
Embedding some third party subclass with all fields
Assume we have a Parent class in some library:

```<code>public abstract class Parent {
    private String name;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}
</code>```

Also assume that we have a Child class in some other library:

```<code>public class Child extends Parent {

}
</code>```

I want to use Child class as embedded in one of my entities, like

```<code>@Entity
public class SomeEntity {
    // id and other fields
    @Embedded
    private Child child;

    // getters, setters etc.
}
</code>```

The problem is, the fields defined in Parent are not embedded, i.e. there are no columns for them in the corresponding table of SomeEntity.

Just to make sure that it is because of inheritance, I first added some fields to Child and observed that they are embedded as expected. I also tried embedding Parent directly, and the columns for them are generated this time too.

The problem is, how can I embed the fields defined in a super class?

I tried to mark child field of SomeEntity with @Access(AccessType.PROPERTY), but it did not work. I also tried to change those fields in Parent class (i.e. name in our example) to public but this didn't work either.

In case it is related, my project is a Spring Boot project, with Hibernate as the JPA provider. Any help is appreciated.

EDIT: The attempted orm.xml file is as follows:

```<code><?xml version="1.0" encoding="UTF-8"?>
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm
                    http://java.sun.com/xml/ns/persistence/orm_2_0.xsd"
                 version="2.0">

    <embeddable class="...Child" access="PROPERTY">
        <attributes>
            <basic name="name">
                <column nullable="false"/>
            </basic>
        </attributes>
    </embeddable>
</entity-mappings>
</code>```

I tried with access="FIELD" and also without any access parameter, but no luck.

To make sure that orm.xml is loaded, I gave an invalid class to embeddable and observed ClassNotFoundException, hence it is loaded.

答:
Quoting from here,

The JPA spec does not support embeddable objects having inheritance, although some JPA providers may allow this.

I guess this as the cause of my problem. Shame on JPA.

In an answer to a similar question, it is stated that:

Hibernate doesn't support inheritance of @Embeddable component.

Body:
Assume we have a Parent class in some library:

public abstract class Parent {
    private String name;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

Also assume that we have a Child class in some other library:

public class Child extends Parent {

}

I want to use Child class as embedded in one of my entities, like

@Entity
public class SomeEntity {
    // id and other fields
    @Embedded
    private Child child;

    // getters, setters etc.
}

The problem is, the fields defined in Parent are not embedded, i.e. there are no columns for them in the corresponding table of SomeEntity.

Just to make sure that it is because of inheritance, I first added some fields to Child and observed that they are embedded as expected. I also tried embedding Parent directly, and the columns for them are generated this time too.

The problem is, how can I embed the fields defined in a super class?

I tried to mark child field of SomeEntity with @Access(AccessType.PROPERTY), but it did not work. I also tried to change those fields in Parent class (i.e. name in our example) to public but this didn't work either.

In case it is related, my project is a Spring Boot project, with Hibernate as the JPA provider. Any help is appreciated.

EDIT: The attempted orm.xml file is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm
                    http://java.sun.com/xml/ns/persistence/orm_2_0.xsd"
                 version="2.0">

    <embeddable class="...Child" access="PROPERTY">
        <attributes>
            <basic name="name">
                <column nullable="false"/>
            </basic>
        </attributes>
    </embeddable>
</entity-mappings>

I tried with access="FIELD" and also without any access parameter, but no luck.

To make sure that orm.xml is loaded, I gave an invalid class to embeddable and observed ClassNotFoundException, hence it is loaded.


问:
Div not inline when window gets smaller?
I'm having a small issue with a couple divs. I have it set up with 5 divs all different colors, when the window size is shrunk the divs drop down under each other one by one. Is there a way I can make the space between them shrinks with it so they but up closer?

Thanks again guys

p {
  margin: 0;
}

.pageColourOn {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 155px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.pageColourOff {
  display: none;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

.bg01Off {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg02Off {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg03Off {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg04Off {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg05Off {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.center {
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="pageColourOn" id="pageColour">
  <div id="pageName">
    <p>Colour</p>
  </div>
  <div class="center">
    <div id="bg01" class="bg01Off">
    </div>
    <div id="bg02" class="bg02Off">
    </div>
    <div id="bg03" class="bg03Off">
    </div>
    <div id="bg04" class="bg04Off">
    </div>
    <div id="bg05" class="bg05Off">
    </div>
  </div></code>```

答:
Change the container center to a flexbox with the following properties:

```<code>.center {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  padding: 0 4%
}
</code>```

p {
  margin: 0;
}

.pageColourOn {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 155px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.pageColourOff {
  display: none;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

.bgOff {
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  display: inline-block;
}

.bg01Off {
  background-color: #80b3ff;
}

.bg02Off {
  background-color: #afe9af;

}

.bg03Off {
  background-color: #ffb380;
}

.bg04Off {
  background-color: #ffaaaa;
}

.bg05Off {
  background-color: #eeaaff;
}

.center {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  padding: 0 4%
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="pageColourOn" id="pageColour">
  <div id="pageName">
    <p>Colour</p>
  </div>
  <div class="center">
    <div id="bg01" class="bgOff bg01Off">
    </div>
    <div id="bg02" class="bgOff bg02Off">
    </div>
    <div id="bg03" class="bgOff bg03Off">
    </div>
    <div id="bg04" class="bgOff bg04Off">
    </div>
    <div id="bg05" class="bgOff bg05Off">
    </div>
  </div></code>```

Body:
I'm having a small issue with a couple divs. I have it set up with 5 divs all different colors, when the window size is shrunk the divs drop down under each other one by one. Is there a way I can make the space between them shrinks with it so they but up closer?

Thanks again guys

p {
  margin: 0;
}

.pageColourOn {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 155px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.pageColourOff {
  display: none;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

.bg01Off {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg02Off {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg03Off {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg04Off {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg05Off {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.center {
  text-align: center;
}

Colour

Body:
Change the container center to a flexbox with the following properties:

.center {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  padding: 0 4%
}

p {
  margin: 0;
}

.pageColourOn {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 155px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.pageColourOff {
  display: none;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

.bgOff {
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  display: inline-block;
}

.bg01Off {
  background-color: #80b3ff;
}

.bg02Off {
  background-color: #afe9af;

}

.bg03Off {
  background-color: #ffb380;
}

.bg04Off {
  background-color: #ffaaaa;
}

.bg05Off {
  background-color: #eeaaff;
}

.center {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  padding: 0 4%
}

<div class="pageColourOn" id="pageColour">
  <div id="pageName">
    <p>Colour</p>
  </div>
  <div class="center">
    <div id="bg01" class="bgOff bg01Off">
    </div>
    <div id="bg02" class="bgOff bg02Off">
    </div>
    <div id="bg03" class="bgOff bg03Off">
    </div>
    <div id="bg04" class="bgOff bg04Off">
    </div>
    <div id="bg05" class="bgOff bg05Off">
    </div>
  </div>


问:
Angular2 - Subscribe not firing
I'm trying to implement a shared service in order to share information between components.

In this moment, the subscribe doesn't work and I don't know why...

This is the service:

service

```<code>private subject = new Subject<any>();

getCurrentUser(): Observable<any>
    {

        this.subject.next({data:"test"});
        return this.subject.asObservable();
    }
</code>```

component

```<code>subscription: Subscription;

ngOnInit() {

    this.subscription = this.authService.getCurrentUser().subscribe(data => {

      this.message = data;
      alert('I called the method');

    });
  }
</code>```

In this moment the execution didn't go inside the procedure that set the message and do the alert...

Thanks to support

答:
In your example/test try changing the Subject to a BehaviorSubject

```<code>private subject = new BehaviorSubject<any>({date: "test"});
</code>```

then change your getCurrentUser to

```<code>getCurrentUser(): Observable<any> {
   return this.subject.asObservable();
}
</code>```

One big difference between a subject and behaviorSubject is that you have to provide a start value for the behaviorSubject, and it also emits the current value to you when you subscribe to it. A Subject will not emit its last set value to you when you subscribe, it will only start "watching" at the point you subscribe and pick up on subsequent changes.

Title: Angular2 - Subscribe not firing

Body:
I'm trying to implement a shared service in order to share information between components.

In this moment, the subscribe doesn't work and I don't know why...

This is the service:

service

private subject = new Subject<any>();

getCurrentUser(): Observable<any>
    {

        this.subject.next({data:"test"});
        return this.subject.asObservable();
    }

component

subscription: Subscription;

ngOnInit() {

    this.subscription = this.authService.getCurrentUser().subscribe(data => {

      this.message = data;
      alert('I called the method');

    });
  }

In this moment the execution didn't go inside the procedure that set the message and do the alert...

Thanks to support

Body:
In your example/test try changing the Subject to a BehaviorSubject

private subject = new BehaviorSubject<any>({date: "test"});

then change your getCurrentUser to

getCurrentUser(): Observable<any> {
   return this.subject.asObservable();
}

One big difference between a subject and behaviorSubject is that you have to provide a start value for the behaviorSubject, and it also emits the current value to you when you subscribe to it. A Subject will not emit its last set value to you when you subscribe, it will only start "watching" at the point you subscribe and pick up on subsequent changes.


问:
Angular 2 : what make a service to be "Outside" angular zone?
After having same issues as many people on StackOverflow i didn't manage to understand what is an  "Outside angular zone" Service ?

I've checks all existing questions  around this subject, and it's exactly why i needer to ask this one :

https://github.com/angular/angular/issues/5150

Angular2: view is not updated from inside a subscription

https://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html

http://blog.assaf.co/angular-2-change-detection-zones-and-an-example/

Code Example in any component with default ChangeDetectionStrategy :
(considering this.value referenced in view)

```<code>this.myService.method().subscribe(e => {
    this.value = e;
  });
</code>```

Is the given service is not "Outside angular zone", the view is refreshed, on the other hand, if it's "Outside angular zone", the view is not refreshed, unless we call ChangeDetectorRef.detectChanges().

So the question is : what the condition to know if a service is Inside or Outside "Angular Zone" ?

答:
It looks like I found my responses by myself, but i Hope it will be an assistance for other people :

an "Outside Angular Zone" service is a class that was not instantiate inside Angular Context.
Many libraries using static accessors are susceptible to be in this case, here's an example :

http://techqa.info/programming/question/34592857/view-is-not-updated-on-change-in-angular2

My luck is that it was the same library used. As described in this external resource, manage to instantiate the external library object would resolve view refresh issue and let this service became an "Inside Angular zone" one.

Body:
After having same issues as many people on StackOverflow i didn't manage to understand what is an  "Outside angular zone" Service ?

I've checks all existing questions  around this subject, and it's exactly why i needer to ask this one :

https://github.com/angular/angular/issues/5150

Angular2: view is not updated from inside a subscription

https://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html

http://blog.assaf.co/angular-2-change-detection-zones-and-an-example/

Code Example in any component with default ChangeDetectionStrategy :
(considering this.value referenced in view)

this.myService.method().subscribe(e => {
    this.value = e;
  });

Is the given service is not "Outside angular zone", the view is refreshed, on the other hand, if it's "Outside angular zone", the view is not refreshed, unless we call ChangeDetectorRef.detectChanges().

So the question is : what the condition to know if a service is Inside or Outside "Angular Zone" ?


问:
How do I protect phone number from bots
I want a phone number which display on public page will be protected. Example converts phone number characters to HTML entities and bots can't grab the number in plain text. Let me know the trick.</p>

答:
The first thing I'd think of is render an image.

Use Javascript to obfuscate

Obfuscate using a php function

Title: How do I protect phone number from bots


问:
dotnet core and angular node dependency?
Having a hard time trying to figure out why my dotnet new angular application has a node dependency when running through iis?  Using Visual Studio Code and dotnet core 1.0.4, after publishing, my application still has a dependency on node.js?  Not sure why.  We are running the application through iis, but our production server does not have node installed and this results in a 500 status code.  We are using Microsoft spa package which has angular 2.

Has anyone else had any similar issue?

How can I remove the node dependency?

答:
It looks like your using the Microsoft.AspNetCore.SpaTemplates for this.  If so, you have two options to create a production build:

Use the command dotnet publish -c Release

Use the publish option under the build menu in Visual Studio 2017

A good tutorial and walkthrough can be found here


问:
How to parse out date from non standard date string
I have a date that is returned in this string format from moment.js for a calendar app.

Fri Jun 16 2017 00:00:00 GMT-0500 (Central Daylight Time)

How can i parse this string back into '2017-06-16', using moment to backtrack specifies this is an invalid input. Using it as an instance of new Date() returns to me an incorrect date.

```<code>var check = moment('Fri Jun 16 2017 00:00:00 GMT-0500 (Central Daylight Time)', 'YYYY/MM/DD');

var month = check.format('M');
var day   = check.format('D');
var year  = check.format('YYYY');

console.log(month, day, year);
//-->invalid date
</code>```

http://jsfiddle.net/t89apndd/

答:
If you really want moment.js...

var check = moment(new Date('Fri Jun 16 2017 00:00:00 GMT-0500 (Central Daylight Time)'));

var month = check.format('M');
var day   = check.format('D');
var year  = check.format('YYYY');

console.log(month, day, year);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script></code>```

Body:
I have a date that is returned in this string format from moment.js for a calendar app.

Fri Jun 16 2017 00:00:00 GMT-0500 (Central Daylight Time)

How can i parse this string back into '2017-06-16', using moment to backtrack specifies this is an invalid input. Using it as an instance of new Date() returns to me an incorrect date.

var check = moment('Fri Jun 16 2017 00:00:00 GMT-0500 (Central Daylight Time)', 'YYYY/MM/DD');

var month = check.format('M');
var day   = check.format('D');
var year  = check.format('YYYY');

console.log(month, day, year);
//-->invalid date

http://jsfiddle.net/t89apndd/

Body:
If you really want moment.js...

var check = moment(new Date('Fri Jun 16 2017 00:00:00 GMT-0500 (Central Daylight Time)'));

var month = check.format('M');
var day   = check.format('D');
var year  = check.format('YYYY');

console.log(month, day, year);

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>


问:
How to switch to frame having given HTML using Selenium
```<code><!DOCTYPE html>
<html>
<head>
<body>
<header class="masthead">
<div id="mydiv">
<object id="frame" data="tdreporthome.html"></object>
</div>
<footer class="navbar default-footer">
</body>
</html>
</code>```

In the above html structure if I want to switch Selenium control to  frame how to do so using Selenium ?

答:
```<code>//Object[@id='frame']
</code>```

you can use the above xpath

Body:
<!DOCTYPE html>

<object id="frame" data="tdreporthome.html"></object>

In the above html structure if I want to switch Selenium control to  frame how to do so using Selenium ?

Body:
//Object[@id='frame']

you can use the above xpath


问:
R Shiny: Control checkbox value with action button
I would like to be able to control the value of a checkbox also by clicking an action button (for disabling certain program options when one selects a different functionality). Though I got close to what I want, I cannot get the checkbox properly initialized. The action button has to be pressed at least once to get see the checkbox in the first place.

MWE:

```<code># server.R

function(input, output) {

    output$make_box <- renderUI({
      checkboxInput("checkbox", label = "Choice A", value = setboxon())
    })

    setboxon <- eventReactive(input$action, {
      if(is.null(input$checkbox))
        return(FALSE)
      else if(input$checkbox==TRUE)
        return(FALSE)
      else
        return(TRUE)
    })

    # check status off checkbox value
    output$value <- renderPrint({ input$checkbox })

}
</code>```

and

```<code># ui.R

fluidPage(

# plot checkbox
uiOutput("make_box"),

# plot action button
actionButton("action", label = "Action"),
br(),

hr(),
# output check
fluidRow(column(3, verbatimTextOutput("value")))

)
</code>```

答:
One way would be to use a reactiveVal():

```<code>setboxon <- reactiveVal(TRUE)

observe({
  if(is.null(input$checkbox))
    setboxon(FALSE)
  else if(input$checkbox==FALSE)
    setboxon(FALSE)
})

observe({
  if(input$action) setboxon(TRUE)
})
</code>```

Body:
I would like to be able to control the value of a checkbox also by clicking an action button (for disabling certain program options when one selects a different functionality). Though I got close to what I want, I cannot get the checkbox properly initialized. The action button has to be pressed at least once to get see the checkbox in the first place.

MWE:

# server.R

function(input, output) {

    output$make_box <- renderUI({
      checkboxInput("checkbox", label = "Choice A", value = setboxon())
    })

    setboxon <- eventReactive(input$action, {
      if(is.null(input$checkbox))
        return(FALSE)
      else if(input$checkbox==TRUE)
        return(FALSE)
      else
        return(TRUE)
    })

    # check status off checkbox value
    output$value <- renderPrint({ input$checkbox })

}

and

# ui.R

fluidPage(

# plot checkbox
uiOutput("make_box"),

# plot action button
actionButton("action", label = "Action"),
br(),

hr(),
# output check
fluidRow(column(3, verbatimTextOutput("value")))

)

Body:
One way would be to use a reactiveVal():

setboxon <- reactiveVal(TRUE)

observe({
  if(is.null(input$checkbox))
    setboxon(FALSE)
  else if(input$checkbox==FALSE)
    setboxon(FALSE)
})

observe({
  if(input$action) setboxon(TRUE)
})


问:
Connecting React Native with Meteorjs
I'm build a simple app with React Native and MeteorJs.

To establish a connection between the two frameworks i'm using DDP through the 'react-native-meteor' package.

My problem is that on my local machine, it's working fine with

```<code>Meteor.connect('ws://localhost:3000/websocket');
</code>```

I have hosted my backend (the meteor js app) on heroku.

Doing :

```<code>Meteor.connect('ws://https://www.myapp.herokuapp.com/websocket');
</code>```

is not working,

How to fix that?

答:
I had simply to do this </p>

```<code>Meteor.connect('ws://myapp.herokuapp.com/websocket');
</code>```

Title: Connecting React Native with Meteorjs

Body:
I'm build a simple app with React Native and MeteorJs.

To establish a connection between the two frameworks i'm using DDP through the 'react-native-meteor' package.

My problem is that on my local machine, it's working fine with

Meteor.connect('ws://localhost:3000/websocket');

I have hosted my backend (the meteor js app) on heroku.

Doing :

Meteor.connect('ws://https://www.myapp.herokuapp.com/websocket');

is not working,

How to fix that?

Body:
I had simply to do this

Meteor.connect('ws://myapp.herokuapp.com/websocket');


问:
I can't get windows authentication to work on IIS website
Background:

I am making a 'splash' page for my companies intranet (citrix access), on of the requirements is that the welcome message is personalised to the user viewing it, so it says 'Welcome Fred Jones'. This means I have to make an active directory request. I want to run the person's login (Domain\User.name) against active directory and return their name (Fred Jones)

What I have tried:

I have this code working locally but cannot seem to get it work on a live server:

```<code>PrincipalContext ctx = new PrincipalContext(ContextType.Domain,
    "adurl.ad",
    "DC=company,DC=ad",
    "AccountUserName",
    "Password");
//UserPrincipal user = UserPrincipal.Current;
//UserPrincipal user = UserPrincipal.FindByIdentity(ctx, User.Identity.Name);
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "DOMAIN\\User.Name");
string displayName = user.DisplayName;
</code>```

(Locally the 'DOMAIN\User.Name' is different to that on citrix so I hard coded in my username and this works locally)

I have set the web config to have windows authentication on, and I have also configured the server to only have windows authentication on. When I go to the website the windows security pop-up appears, I enter my details and it doesn't let me log in. Repeated tries leads to the following error message:

HTTP Error 401.1 - Unauthorized

You do not have permission to view this directory or page using the
  credentials that you supplied.

If I enable anonymous authentication then the page appears without a windows security prompt but then the 'User.Identity.Name' is blank.

I have looked through so many stack overflow questions and answers and can't quite find a fix for my issue, any help would be appreciated!

答: I found the solution, adding IIS_IUSRS to the website folder permissions allowed and gave full access allowed my website to work correctly.

Body:
Background:

I am making a 'splash' page for my companies intranet (citrix access), on of the requirements is that the welcome message is personalised to the user viewing it, so it says 'Welcome Fred Jones'. This means I have to make an active directory request. I want to run the person's login (Domain\User.name) against active directory and return their name (Fred Jones)

What I have tried:

I have this code working locally but cannot seem to get it work on a live server:

PrincipalContext ctx = new PrincipalContext(ContextType.Domain,
    "adurl.ad",
    "DC=company,DC=ad",
    "AccountUserName",
    "Password");
//UserPrincipal user = UserPrincipal.Current;
//UserPrincipal user = UserPrincipal.FindByIdentity(ctx, User.Identity.Name);
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "DOMAIN\\User.Name");
string displayName = user.DisplayName;

(Locally the 'DOMAIN\User.Name' is different to that on citrix so I hard coded in my username and this works locally)

I have set the web config to have windows authentication on, and I have also configured the server to only have windows authentication on. When I go to the website the windows security pop-up appears, I enter my details and it doesn't let me log in. Repeated tries leads to the following error message:

HTTP Error 401.1 - Unauthorized

You do not have permission to view this directory or page using the
  credentials that you supplied.

If I enable anonymous authentication then the page appears without a windows security prompt but then the 'User.Identity.Name' is blank.

I have looked through so many stack overflow questions and answers and can't quite find a fix for my issue, any help would be appreciated!


问:
Faker YML add 1 hour to a date
My question is about Faker.
I need to add one hour to a created date
Like this :

```<code>MyEntity:
    startAt: '<dateTimeBetween("- 10 days", "now")>'
    endAt: $startAt + 1 hour
</code>```

Thx for your help.

答:
Well that does not exist yet. Need to create a custom provider

Like this :

```<code>public static function manipulateTime($date, $action = '-30 years')
    {
        $date = new \DateTime($date->format('Y-m-d H:i:s'));
        $date->modify($action);

        return $date;
    }
</code>```

Title: Faker YML add 1 hour to a date

Body:
My question is about Faker.
I need to add one hour to a created date
Like this :

MyEntity:
    startAt: '<dateTimeBetween("- 10 days", "now")>'
    endAt: $startAt + 1 hour

Thx for your help.

Body:
Well that does not exist yet. Need to create a custom provider

Like this :

public static function manipulateTime($date, $action = '-30 years')
    {
        $date = new \DateTime($date->format('Y-m-d H:i:s'));
        $date->modify($action);

        return $date;
    }


问:
Difference in including the .cpp file and .h file (with the same content in cpp)?
I've recently started learning cpp from basics and was very much confused with the folowing:

Lets say I have a header( test.h which contains only declarations) with some content and some source file (source.cpp) and program produced some result.

If I have copied the same content of that header file to a .cpp file (testcpp.cpp) and included this in source.cpp

In this case, I did not understood what difference it makes?

(I'll not include this testcpp.cpp in make file)

I have seen some threads similar to this but couldn't get a clear idea!!!

I learnt the usage of header and cpp files and have used it correctly in projects till now, Please answer specific to this scenario (I know doing this way adds confusion but just want to know). Will there be any difference doing so or it's just a common practice everyone follows ?

答: #include just does a copy-n-paste of the file you include into the current file. What the file is named doesn't matter one bit - you can name it "foo.exe" if you like; as long as it contains valid source-code in the context where it is included all is well (but please don't use unconventional names, you'll just confuse people).


问:
Mocked restTemplate.postForObject is not being used in execution of test
I have mocked a postForObject resttemplate call using mickito.

Mockito.when(restTemplate.postForObject(Mockito.eq(remoteServerlocation), Mockito.any(Input.class), Mockito.eq(String.class))).thenReturn(responseString);

But in the actual code, this mocked value is not being used and trying to call the remote location.

String responseString = restTemplate.postForObject(url, input, String.class);

As per my understanding , I have mocked exactly same call. But not working.
Any help on this will be thankful.

I'm autowiring the class which contains the testing method in testcase class. And this test class I have created restTemplate using new.

TestClass

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Application.class)
public class ActionImplTest {

    @Autowired
    private ActionImpl recommendation;

    RestTemplate restTemplate = new RestTemplate();

    @Test
    public void performActionTest() throws Exception {
        String textInput = "InputText";
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("convId", "C123");
        map.put("reID", 1);
        map.put("chID", "Chann_1");

        String convID = "1254356671563";
        String chId = "2";
        String responseString = "Success"
        Mockito.when(restTemplate.postForObject(Mockito.eq("remoteServerlocation"), Mockito.any(Input.class), Mockito.eq(String.class))).thenReturn(responseString);

        Map<String, Object> response = recommendation.performAction(textInput, map, convID, chId);
    }
}
</code>```

答:
Here is an example of what I meant in the comment referring to the Spring documentation.</p>

```<code>@RunWith(SpringRunner.class)
@SpringBootTest
public class ActionImplTest {

    @MockBean
    private RestTemplate restTemplate;

    @Autowired
    private ActionImpl recommendation;
</code>```

Body:
I have mocked a postForObject resttemplate call using mickito.

Mockito.when(restTemplate.postForObject(Mockito.eq(remoteServerlocation), Mockito.any(Input.class), Mockito.eq(String.class))).thenReturn(responseString);

But in the actual code, this mocked value is not being used and trying to call the remote location.

String responseString = restTemplate.postForObject(url, input, String.class);

As per my understanding , I have mocked exactly same call. But not working.
Any help on this will be thankful.

I'm autowiring the class which contains the testing method in testcase class. And this test class I have created restTemplate using new.

TestClass

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Application.class)
public class ActionImplTest {

    @Autowired
    private ActionImpl recommendation;

    RestTemplate restTemplate = new RestTemplate();

    @Test
    public void performActionTest() throws Exception {
        String textInput = "InputText";
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("convId", "C123");
        map.put("reID", 1);
        map.put("chID", "Chann_1");

        String convID = "1254356671563";
        String chId = "2";
        String responseString = "Success"
        Mockito.when(restTemplate.postForObject(Mockito.eq("remoteServerlocation"), Mockito.any(Input.class), Mockito.eq(String.class))).thenReturn(responseString);

        Map<String, Object> response = recommendation.performAction(textInput, map, convID, chId);
    }
}

Body:
Here is an example of what I meant in the comment referring to the Spring documentation.

@RunWith(SpringRunner.class)
@SpringBootTest
public class ActionImplTest {

    @MockBean
    private RestTemplate restTemplate;

    @Autowired
    private ActionImpl recommendation;


问:
Global variable in AngularJS (good practice)
I'm looking for a pattern in order to have globals constant in my application. But not with a controller or a factory. (so not with app.constant() too)

I just want to set a variable but I didn't find something good.

I wanted to set this var in my rootScoop but without success.
with something like

```<code>myApp.run(function($rootScoop){
$rootScoop.global = {};
});
</code>```

When I use that code, an arror occurs for nothing (transtateFilterProvider). When I delete this code, the translateService works,

I MUST have access in all html view, I don't want to always use a controller (useless in this case), I just want to set a global variable in rootScoop.

Thank you.

答:
You are getting an error because it is :

```<code>$rootScope
</code>```

And not

```<code>$rootScoop
</code>```

Anyway, correct way to do this is to add a constant module to your app like :

```<code>angular.module('yourapp', []).constant('Constants', {
    foo: 'bar'
});
</code>```

But you'll have to call Constants in controllers.

If you use $rootScope, remember you will need to call $root.global in templates.

Body:
I'm looking for a pattern in order to have globals constant in my application. But not with a controller or a factory. (so not with app.constant() too)

I just want to set a variable but I didn't find something good.

I wanted to set this var in my rootScoop but without success.
with something like

myApp.run(function($rootScoop){
$rootScoop.global = {};
});

When I use that code, an arror occurs for nothing (transtateFilterProvider). When I delete this code, the translateService works,

I MUST have access in all html view, I don't want to always use a controller (useless in this case), I just want to set a global variable in rootScoop.

Thank you.

Body:
You are getting an error because it is :

$rootScope

And not

$rootScoop

Anyway, correct way to do this is to add a constant module to your app like :

angular.module('yourapp', []).constant('Constants', {
    foo: 'bar'
});

But you'll have to call Constants in controllers.

If you use $rootScope, remember you will need to call $root.global in templates.


问:
jmeter + Selenium iDE
I'm unable to active Redline recording button in SeleniumIDE,I have recorded my steps then clicked on  Redline recording button & run the recorded steps but in this time Redline recording button is showing as inactive & after running the steps again clicked on Redline recording button to save jmx file but it appears that-  "Nothing to Save"

答: That is just a "visual issue" you should hit the JMETER button one time then play the entire test suite on selenium and when the test suite have been completed hit the JMETER button again and a modal windows to save as JMETER sould appear</p>

Title: jmeter + Selenium iDE


问:
Sending a slash through mysql
I'm not sure why this has stumped me. I have the following code

```<code>$website = "http://www.google.com";
$name = "Person";

if(!empty($website) {
   $name = "[url=$website]$name[/url]";
}
</code>```

Then i try to insert that into mysql. I tried adding mysql_real_escape_string to both $website and $name (after the if statement), thinking the "/url" might also cause problems.

```<code>$name       = mysql_real_escape_string($name);
</code>```

Still no luck though. Any advice? What am I missing? It's giving me this error

"Parse error: syntax error, unexpected '/', expecting T_STRING or T_VARIABLE or T_NUM_STRING"

答:
Are you putting quotes around the value you want to insert? This will work

```<code>INSERT INTO table_name (column_name)
VALUES ('[url=$website]http://www.google.com[/url]')
</code>```

This will fail

```<code>INSERT INTO table_name (column_name)
VALUES ([url=$website]http://www.google.com[/url])
</code>```

So you might have in you php

```<code>$query = "INSERT INTO table_name (column_name) VALUES ('$name')";
// DO MYSQL_QUERY
</code>```

Title: Sending a slash through mysql

Body:
I'm not sure why this has stumped me. I have the following code

$website = "http://www.google.com";
$name = "Person";

if(!empty($website) {
   $name = "[url=$website]$name[/url]";
}

Then i try to insert that into mysql. I tried adding mysql_real_escape_string to both $website and $name (after the if statement), thinking the "/url" might also cause problems.

$name       = mysql_real_escape_string($name);

Still no luck though. Any advice? What am I missing? It's giving me this error

"Parse error: syntax error, unexpected '/', expecting T_STRING or T_VARIABLE or T_NUM_STRING"

Body:
Are you putting quotes around the value you want to insert? This will work

INSERT INTO table_name (column_name)
VALUES ('[url=$website]http://www.google.com[/url]')

This will fail

INSERT INTO table_name (column_name)
VALUES ([url=$website]http://www.google.com[/url])

So you might have in you php

$query = "INSERT INTO table_name (column_name) VALUES ('$name')";
// DO MYSQL_QUERY