问:
Connecting to Google API with Service Account and OAuth
I'm using an environment that doesn't have native support for a GCP client library. So I'm trying to figure out how to authenticate directly using manually crafted JWT token.

I've adapted the tasks from here Using nodeJS test environment, with jwa to implement the algorithm.

https://developers.google.com/identity/protocols/OAuth2ServiceAccount

The private key is taken from a JSON version of the service account file.

When the test runs, it catches a very basic 400 error, that just says "invalid request". I'm not sure how to troubleshoot it.

Could someone please help identify what I'm doing wrong?

```<code>var assert = require('assert');
const jwa = require('jwa');
const request = require('request-promise');

const pk = require('../auth/tradestate-2-tw').private_key;

const authEndpoint = 'https://www.googleapis.com/oauth2/v4/token';

describe('Connecting to Google API', function() {

    it('should be able to get an auth token for Google Access', async () => {
      assert(pk && pk.length, 'PK exists');
      const header = { alg: "RS256", typ: "JWT" };
      const body = {
        "iss":"salesforce-treasury-wine@tradestate-2.iam.gserviceaccount.com",
        "scope":"https://www.googleapis.com/auth/devstorage.readonly",
        "aud":"https://www.googleapis.com/oauth2/v4/token",
        "exp": new Date().getTime() + 3600 * 1000,
        "iat": new Date().getTime()
      };
      console.log(JSON.stringify(body, null, 2));
      const encodedHeader = Buffer.from(JSON.toString(header)).toString('base64')
      const encodedBody = Buffer.from(JSON.toString(body)).toString('base64');
      const cryptoString = `${encodedHeader}.${encodedBody}`;
      const algo = jwa('RS256');
      const signature = algo.sign(cryptoString, pk);
      const jwt = `${encodedHeader}.${encodedBody}.${signature}`;
      console.log('jwt', jwt);
      const headers = {'Content-Type': 'application/x-www-form-urlencoded'};
      const form = {
        grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
        assertion: jwt
      };
      try {
        const result = await request.post({url: authEndpoint, form, headers});
        assert(result, 'Reached result');
        console.log('Got result', JSON.stringify(result, null, 2));
      } catch (err) {
        console.log(JSON.stringify(err, null, 2));
        throw (err);
      }

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

答:
Use JSON.stringify instead of JSON.toString. From the link in your question:

{"alg":"RS256","typ":"JWT"}

The Base64url representation of this is as follows:

eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9

When using JSON.toString() and then base64 encoding, you would get W29iamVjdCBKU09OXQ== which explains the 400 for an invalid request as it can't decrypt anything you're sending it.

Body:
I'm using an environment that doesn't have native support for a GCP client library. So I'm trying to figure out how to authenticate directly using manually crafted JWT token.

I've adapted the tasks from here Using nodeJS test environment, with jwa to implement the algorithm.

https://developers.google.com/identity/protocols/OAuth2ServiceAccount

The private key is taken from a JSON version of the service account file.

When the test runs, it catches a very basic 400 error, that just says "invalid request". I'm not sure how to troubleshoot it.

Could someone please help identify what I'm doing wrong?

var assert = require('assert');
const jwa = require('jwa');
const request = require('request-promise');

const pk = require('../auth/tradestate-2-tw').private_key;

const authEndpoint = 'https://www.googleapis.com/oauth2/v4/token';

describe('Connecting to Google API', function() {

    it('should be able to get an auth token for Google Access', async () => {
      assert(pk && pk.length, 'PK exists');
      const header = { alg: "RS256", typ: "JWT" };
      const body = {
        "iss":"salesforce-treasury-wine@tradestate-2.iam.gserviceaccount.com",
        "scope":"https://www.googleapis.com/auth/devstorage.readonly",
        "aud":"https://www.googleapis.com/oauth2/v4/token",
        "exp": new Date().getTime() + 3600 * 1000,
        "iat": new Date().getTime()
      };
      console.log(JSON.stringify(body, null, 2));
      const encodedHeader = Buffer.from(JSON.toString(header)).toString('base64')
      const encodedBody = Buffer.from(JSON.toString(body)).toString('base64');
      const cryptoString = `${encodedHeader}.${encodedBody}`;
      const algo = jwa('RS256');
      const signature = algo.sign(cryptoString, pk);
      const jwt = `${encodedHeader}.${encodedBody}.${signature}`;
      console.log('jwt', jwt);
      const headers = {'Content-Type': 'application/x-www-form-urlencoded'};
      const form = {
        grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
        assertion: jwt
      };
      try {
        const result = await request.post({url: authEndpoint, form, headers});
        assert(result, 'Reached result');
        console.log('Got result', JSON.stringify(result, null, 2));
      } catch (err) {
        console.log(JSON.stringify(err, null, 2));
        throw (err);
      }

    });
});


来源: stackexchange

问:
How to get status of web service
How can I get the status of web service using C#? whether it is completed successfully, failed or pending like this.</p>

答:
First i found this question Web Service For Database/Website Status

And you should try this code;

```<code>System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController("myService");
return sc.Status
</code>```

And you should examine this code;

```<code>public static string PingHost(string args)
        {
            HttpWebResponse res = null;

            try
            {
                // Create a request to the passed URI.
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(args);
                req.Credentials = CredentialCache.DefaultNetworkCredentials;

                // Get the response object.
                res = (HttpWebResponse)req.GetResponse();

                return "Service Up";
            }
            catch (Exception e)
            {
                MessageBox.Show("Source : " + e.Source, "Exception Source", MessageBoxButtons.OK);
                MessageBox.Show("Message : " + e.Message, "Exception Message", MessageBoxButtons.OK);
                return "Host Unavailable";
            }
        }
</code>```

And also you should look;

Using Session State in a Web Service

ContentLicense: CC BY-SA 3.0

Title: How to get status of web service

Body:
First i found this question Web Service For Database/Website Status

And you should try this code;

System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController("myService");
return sc.Status

And you should examine this code;

public static string PingHost(string args)
        {
            HttpWebResponse res = null;

            try
            {
                // Create a request to the passed URI.
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(args);
                req.Credentials = CredentialCache.DefaultNetworkCredentials;

                // Get the response object.
                res = (HttpWebResponse)req.GetResponse();

                return "Service Up";
            }
            catch (Exception e)
            {
                MessageBox.Show("Source : " + e.Source, "Exception Source", MessageBoxButtons.OK);
                MessageBox.Show("Message : " + e.Message, "Exception Message", MessageBoxButtons.OK);
                return "Host Unavailable";
            }
        }

And also you should look;

Using Session State in a Web Service


问:
How get steam nickname via javascript
Hello i now using this php code for get steam nicknames

```<code>function EchoPlayerName($steamid){
    $xml = simplexml_load_file("http://steamcommunity.com/profiles/$steamid/?xml=1");//link to user xml
    if(!empty($xml)) {
        $username = $xml->steamID;
        echo $username;
    }
}
</code>```

or

```<code>$steam = file_get_contents("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={API_KEY}&steamids=$steamid64", true);
$steamarray = json_decode($steam, true);
$name = $steamarray['response']['players'][0]['personaname'];
</code>```

but i this using for listing players and loading page is slow
so i want this data load via javascript after full load page

any ideas?

API example

```<code>{"response":{"players":[{"steamid":"76561197964477177","communityvisibilitystate":3,"profilestate":1,"personaname":"The [G]amerX #.","lastlogoff":1558765863,"commentpermission":1,"profileurl":"https://steamcommunity.com/id/gamerxcz/","avatar":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/66/6673d6df066386d232164e8f9a5d9b36cad1d013.jpg","avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/66/6673d6df066386d232164e8f9a5d9b36cad1d013_medium.jpg","avatarfull":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/66/6673d6df066386d232164e8f9a5d9b36cad1d013_full.jpg","personastate":0,"realname":"Community Owner","primaryclanid":"103582791433644720","timecreated":1076786008,"personastateflags":0,"loccountrycode":"CZ"}]}}
</code>```

答:
First, you should get Data using ajax of pure javascript or jquery. Then you should target an HTML element that you want to fill it using this retrieved data. Imagine element with ID target.

jQuery:

```<code>$(document).ready(function () {
    $.ajax({
        url: "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={API_KEY}&steamids=$steamid64",
    }).done(function (data) {
        var json = JSON.parse(data);
        $('#target').text(json['response']['players'][0]['personaname']);
    });
});
</code>```

pure javascript:

```<code>var xhr = new XMLHttpRequest();
    xhr.open('POST', 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={API_KEY}&steamids=$steamid64');
    xhr.onload = function () {
        if (xhr.status === 200) {
            var json = JSON.parse(xhr.responseText);
            document.getElementById('target').innerHTML = json['response']['players'][0]['personaname'];
        } else {
            alert('Request failed.  Returned status of ' + xhr.status);
        }
    };
    xhr.send();
</code>```

Remember to place these scripts at the end of your document.

ContentLicense: CC BY-SA 4.0

Title: How get steam nickname via javascript

Body:
Hello i now using this php code for get steam nicknames

function EchoPlayerName($steamid){
    $xml = simplexml_load_file("http://steamcommunity.com/profiles/$steamid/?xml=1");//link to user xml
    if(!empty($xml)) {
        $username = $xml->steamID;
        echo $username;
    }
}

or

$steam = file_get_contents("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={API_KEY}&steamids=$steamid64", true);
$steamarray = json_decode($steam, true);
$name = $steamarray['response']['players'][0]['personaname'];

but i this using for listing players and loading page is slow
so i want this data load via javascript after full load page

any ideas?

API example

{"response":{"players":[{"steamid":"76561197964477177","communityvisibilitystate":3,"profilestate":1,"personaname":"The [G]amerX #.","lastlogoff":1558765863,"commentpermission":1,"profileurl":"https://steamcommunity.com/id/gamerxcz/","avatar":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/66/6673d6df066386d232164e8f9a5d9b36cad1d013.jpg","avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/66/6673d6df066386d232164e8f9a5d9b36cad1d013_medium.jpg","avatarfull":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/66/6673d6df066386d232164e8f9a5d9b36cad1d013_full.jpg","personastate":0,"realname":"Community Owner","primaryclanid":"103582791433644720","timecreated":1076786008,"personastateflags":0,"loccountrycode":"CZ"}]}}

Body:
First, you should get Data using ajax of pure javascript or jquery. Then you should target an HTML element that you want to fill it using this retrieved data. Imagine element with ID target.

jQuery:

$(document).ready(function () {
    $.ajax({
        url: "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={API_KEY}&steamids=$steamid64",
    }).done(function (data) {
        var json = JSON.parse(data);
        $('#target').text(json['response']['players'][0]['personaname']);
    });
});

pure javascript:

var xhr = new XMLHttpRequest();
    xhr.open('POST', 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={API_KEY}&steamids=$steamid64');
    xhr.onload = function () {
        if (xhr.status === 200) {
            var json = JSON.parse(xhr.responseText);
            document.getElementById('target').innerHTML = json['response']['players'][0]['personaname'];
        } else {
            alert('Request failed.  Returned status of ' + xhr.status);
        }
    };
    xhr.send();

Remember to place these scripts at the end of your document.


问:
System.Random producing the same random number
Despite the Random generator only being created once, the output is always the same random result (for all three test outputs).

A test snippet from a slightly larger script:

```<code>   let myRandGen = System.Random()
   let getRandomObject =
      let options = [|"Bob"; "Jim"; "Jane"|]
      let randIndex  = myRandGen.Next(options.Length)
      options.[randIndex]

   printfn "New one: %s" getRandomObject
   printfn "New two: %s" getRandomObject
   printfn "New three: %s" getRandomObject
</code>```

I need the output to be random for each call, which it currently isn't.

Example output:

```<code>New one: Jane
New two: Jane
New three: Jane
</code>```

答:
Your getRandomObject is a value. It is evaluated once. To fix this, make getRandomObject a function:

```<code>let getRandomObject () =
  let options = [|"Bob"; "Jim"; "Jane"|]
  let randIndex  = myRandGen.Next(options.Length)
  options.[randIndex]
</code>```

and call it like so: getRandomObject ()

Body:
Despite the Random generator only being created once, the output is always the same random result (for all three test outputs).

A test snippet from a slightly larger script:

   let myRandGen = System.Random()
   let getRandomObject =
      let options = [|"Bob"; "Jim"; "Jane"|]
      let randIndex  = myRandGen.Next(options.Length)
      options.[randIndex]

   printfn "New one: %s" getRandomObject
   printfn "New two: %s" getRandomObject
   printfn "New three: %s" getRandomObject

I need the output to be random for each call, which it currently isn't.

Example output:

New one: Jane
New two: Jane
New three: Jane

Body:
Your getRandomObject is a value. It is evaluated once. To fix this, make getRandomObject a function:

let getRandomObject () =
  let options = [|"Bob"; "Jim"; "Jane"|]
  let randIndex  = myRandGen.Next(options.Length)
  options.[randIndex]

and call it like so: getRandomObject ()


问:
Unable to setup Jenkins slave on docker
I'm trying to create slave on docker by using the below command but it returned exception

```<code>:~$ docker run jenkins/jnlp-slave -disableHttpsCertValidation -url https://hostName/CI-KINDLE-1924  774351357f93a1026afasdfagsg180551cca56a9cfa741234531fsdfdee8feeb dockerslave
</code>```

Exception:

Observed the below exception in console:

INFO: Protocol JNLP4-connect encountered an unexpected exception
  java.util.concurrent.ExecutionException:
  org.jenkinsci.remoting.protocol.impl.ConnectionRefusalException:
  Unknown client name: dockerslave
          at org.jenkinsci.remoting.util.SettableFuture.get(SettableFuture.java:223)
          at hudson.remoting.Engine.innerRun(Engine.java:614)
          at hudson.remoting.Engine.run(Engine.java:474) Caused by: org.jenkinsci.remoting.protocol.impl.ConnectionRefusalException:
  Unknown client name: dockerslave
          at org.jenkinsci.remoting.protocol.impl.ConnectionHeadersFilterLayer.newAbortCause(ConnectionHeadersFilterLayer.java:378)
          at org.jenkinsci.remoting.protocol.impl.ConnectionHeadersFilterLayer.onRecvClosed(ConnectionHeadersFilterLayer.java:433)
          at org.jenkinsci.remoting.protocol.ProtocolStack$Ptr.onRecvClosed(ProtocolStack.java:816)
          at org.jenkinsci.remoting.protocol.FilterLayer.onRecvClosed(FilterLayer.java:287)
          at org.jenkinsci.remoting.protocol.impl.SSLEngineFilterLayer.onRecvClosed(SSLEngineFilterLayer.java:172)

When I tried to connect through "Web Launch agent from browser" using below command It connected successfully.

```<code>java -jar agent.jar -jnlpUrl https://hostName/CI-KINDLE-1924/computer/Worker/slave-agent.jnlp -secret 774351357f93a1026afasdfagsg180551cca56a9cfa741234531fsdfdee8feeb -workDir "/x/home/achu"
</code>```

The above command works as expected and the slave will be active. But I just want to create slave nodes in docker and wanna activate them at runtime and destroy.

Please anyone help me to achieve this

答:
I just added my slave node name as client name and it worked.

I just created a slave node in Jenkins master and I just used the name It works perfectly fine.

Title: Unable to setup Jenkins slave on docker

Body:
I'm trying to create slave on docker by using the below command but it returned exception

:~$ docker run jenkins/jnlp-slave -disableHttpsCertValidation -url https://hostName/CI-KINDLE-1924  774351357f93a1026afasdfagsg180551cca56a9cfa741234531fsdfdee8feeb dockerslave

Exception:

Observed the below exception in console:

INFO: Protocol JNLP4-connect encountered an unexpected exception
  java.util.concurrent.ExecutionException:
  org.jenkinsci.remoting.protocol.impl.ConnectionRefusalException:
  Unknown client name: dockerslave
          at org.jenkinsci.remoting.util.SettableFuture.get(SettableFuture.java:223)
          at hudson.remoting.Engine.innerRun(Engine.java:614)
          at hudson.remoting.Engine.run(Engine.java:474) Caused by: org.jenkinsci.remoting.protocol.impl.ConnectionRefusalException:
  Unknown client name: dockerslave
          at org.jenkinsci.remoting.protocol.impl.ConnectionHeadersFilterLayer.newAbortCause(ConnectionHeadersFilterLayer.java:378)
          at org.jenkinsci.remoting.protocol.impl.ConnectionHeadersFilterLayer.onRecvClosed(ConnectionHeadersFilterLayer.java:433)
          at org.jenkinsci.remoting.protocol.ProtocolStack$Ptr.onRecvClosed(ProtocolStack.java:816)
          at org.jenkinsci.remoting.protocol.FilterLayer.onRecvClosed(FilterLayer.java:287)
          at org.jenkinsci.remoting.protocol.impl.SSLEngineFilterLayer.onRecvClosed(SSLEngineFilterLayer.java:172)

When I tried to connect through "Web Launch agent from browser" using below command It connected successfully.

java -jar agent.jar -jnlpUrl https://hostName/CI-KINDLE-1924/computer/Worker/slave-agent.jnlp -secret 774351357f93a1026afasdfagsg180551cca56a9cfa741234531fsdfdee8feeb -workDir "/x/home/achu"

The above command works as expected and the slave will be active. But I just want to create slave nodes in docker and wanna activate them at runtime and destroy.

Please anyone help me to achieve this


问:
How to create unique batch number for the day
I want create unique batch number for the day,tomorrow batch number should be max(batchno)+1 . and serial number should be maintain as follows

record set should be as follows

```<code>ID    | invoice date   | Batchno     |  seqno
1     | 2019-05-24     |201905000001 | 1
2     | 2019-05-24     |201905000001 | 2
3     | 2019-05-25     |201905000002 | 1
4     | 2019-05-25     |201905000002 | 2

   ON  [dbo].[EBSIEMSTransfernew]
   AFTER INSERT

AS

 declare @year varchar(4)
 declare @month varchar(2)
 declare @serialNo varchar(10)

 select @year = year(getdate())
 select @month = REPLICATE('0', 2-len( month(getdate())))+ cast(month(getdate()) as varchar)
 select @serialNo = Max(right(BatchNo,5)) FROM  [Onaccount].[dbo].[EBSIEMSTransfernew] where InvoiceDate >= dateadd(day,datediff(day,1,GETDATE()),0)
 AND InvoiceDate < dateadd(day,datediff(day,0,GETDATE()),0)

BEGIN

UPDATE    [Onaccount].[dbo].[EBSIEMSTransfernew]
SET              BatchNo = @year + @month + REPLICATE('0', 5 - LEN(@serialNo + 1)) + CAST(@serialNo + 1 AS varchar)
FROM         [Onaccount].[dbo].[EBSIEMSTransfernew] INNER JOIN
                      inserted AS i ON EBSIEMSTransfernew.InvoiceDate = i.InvoiceDate
WHERE     (EBSIEMSTransfernew.InvoiceDate = i.InvoiceDate)

SET NOCOUNT ON;

END

GO
</code>```

答:
For a Daily BATCH number, I would go for the option of using YYYYMMDD as a batch number. Because this is UNIQUE in all sense. So every new day, the date is itself a new UNIQUE batch number as shown below-

```<code>20190526
20190527
...
20190530
</code>```

As you are managing a daily sequence/serial number starting from 1 everyday, together they will produce a meaningful number as well. You can easily read some value from them. I would suggest to use the 'seqno' something like 0001..0002 based on the guess of Maximum INVOICE may required for a single day.

You can now also generate the Invoice Number from above two number as below-

```<code>201905260001
201905260002
</code>```

The invoice number will then itself meaningful as it can easily understandable the Invoice belong to date 20190526 and the sell invoice was the first/second sell of that day.

Body:
I want create unique batch number for the day,tomorrow batch number should be max(batchno)+1 . and serial number should be maintain as follows

record set should be as follows

ID    | invoice date   | Batchno     |  seqno
1     | 2019-05-24     |201905000001 | 1
2     | 2019-05-24     |201905000001 | 2
3     | 2019-05-25     |201905000002 | 1
4     | 2019-05-25     |201905000002 | 2

   ON  [dbo].[EBSIEMSTransfernew]
   AFTER INSERT

AS

 declare @year varchar(4)
 declare @month varchar(2)
 declare @serialNo varchar(10)

 select @year = year(getdate())
 select @month = REPLICATE('0', 2-len( month(getdate())))+ cast(month(getdate()) as varchar)
 select @serialNo = Max(right(BatchNo,5)) FROM  [Onaccount].[dbo].[EBSIEMSTransfernew] where InvoiceDate >= dateadd(day,datediff(day,1,GETDATE()),0)
 AND InvoiceDate < dateadd(day,datediff(day,0,GETDATE()),0)

BEGIN

UPDATE    [Onaccount].[dbo].[EBSIEMSTransfernew]
SET              BatchNo = @year + @month + REPLICATE('0', 5 - LEN(@serialNo + 1)) + CAST(@serialNo + 1 AS varchar)
FROM         [Onaccount].[dbo].[EBSIEMSTransfernew] INNER JOIN
                      inserted AS i ON EBSIEMSTransfernew.InvoiceDate = i.InvoiceDate
WHERE     (EBSIEMSTransfernew.InvoiceDate = i.InvoiceDate)

SET NOCOUNT ON;

END

GO

Body:
For a Daily BATCH number, I would go for the option of using YYYYMMDD as a batch number. Because this is UNIQUE in all sense. So every new day, the date is itself a new UNIQUE batch number as shown below-

20190526
20190527
...
20190530

As you are managing a daily sequence/serial number starting from 1 everyday, together they will produce a meaningful number as well. You can easily read some value from them. I would suggest to use the 'seqno' something like 0001..0002 based on the guess of Maximum INVOICE may required for a single day.

You can now also generate the Invoice Number from above two number as below-

201905260001
201905260002

The invoice number will then itself meaningful as it can easily understandable the Invoice belong to date 20190526 and the sell invoice was the first/second sell of that day.


问:
Entity Framework Core code-first approach one to many relationship returns null
I'm new to Entity Framework Core, in my code I have a number of Questions class objects, and a list of choices to those questions. My query list of Choices always returns Null.

Here are my classes:

```<code>public class Questions
{
    [Key]
    public int QuestionID { get; set; }
    public string  Question { get; set; }

    public ICollection<Choices> choices { get; set; }
}

public class Choices
{
    [Key]
    public int ChoicesId { get; set; }
    public int QuestionId { get; set; }
    public Questions questions  { get; set; }
    public string Choice { get; set; }
}

public class SqlUserRepository : IUserRepository
{
    private readonly AppDbContext context;

    public SqlUserRepository(AppDbContext context)
    {
        this.context = context;
    }

    public List<Questions> getAllQuestions()
    {
        return context.questions.ToList();
    }
}
</code>```

I'm getting this O/p. choices always returns null

```<code>[
    { "questionID":1, "question":"which is your fav.heroien", "choices":null },
    { "questionID":2, "question":"which is your fav.hero", "choices":null  }
]
</code>```

I expect this output

```<code>[{"questionID":1,"question":"which is your fav.heroien","choices":[{"choicesId":5,"questionId":1,"questions":null,"choice":"kajol Agarwal"},{"choicesId":6,"questionId":1,"questions":null,"choice":"Thammanna Bhatia"},{"choicesId":7,"questionId":1,"questions":null,"choice":"Anushka Shetty"},{"choicesId":8,"questionId":1,"questions":null,"choice":"Keerthi Suresh"}]},{"questionID":2,"question":"which is your fav.hero","choices":[{"choicesId":1,"questionId":2,"questions":null,"choice":"upendera"},{"choicesId":2,"questionId":2,"questions":null,"choice":"real star"},{"choicesId":3,"questionId":2,"questions":null,"choice":"Super star"},{"choicesId":4,"questionId":2,"questions":null,"choice":"Only star"}]}]
</code>```

答: How to build your app with code first approach and with relational data the link will guide step by step do the things apply the code first approach.</p>

Body:
I'm new to Entity Framework Core, in my code I have a number of Questions class objects, and a list of choices to those questions. My query list of Choices always returns Null.

Here are my classes:

public class Questions
{
    [Key]
    public int QuestionID { get; set; }
    public string  Question { get; set; }

    public ICollection<Choices> choices { get; set; }
}

public class Choices
{
    [Key]
    public int ChoicesId { get; set; }
    public int QuestionId { get; set; }
    public Questions questions  { get; set; }
    public string Choice { get; set; }
}

public class SqlUserRepository : IUserRepository
{
    private readonly AppDbContext context;

    public SqlUserRepository(AppDbContext context)
    {
        this.context = context;
    }

    public List<Questions> getAllQuestions()
    {
        return context.questions.ToList();
    }
}

I'm getting this O/p. choices always returns null

[
    { "questionID":1, "question":"which is your fav.heroien", "choices":null },
    { "questionID":2, "question":"which is your fav.hero", "choices":null  }
]

I expect this output

[{"questionID":1,"question":"which is your fav.heroien","choices":[{"choicesId":5,"questionId":1,"questions":null,"choice":"kajol Agarwal"},{"choicesId":6,"questionId":1,"questions":null,"choice":"Thammanna Bhatia"},{"choicesId":7,"questionId":1,"questions":null,"choice":"Anushka Shetty"},{"choicesId":8,"questionId":1,"questions":null,"choice":"Keerthi Suresh"}]},{"questionID":2,"question":"which is your fav.hero","choices":[{"choicesId":1,"questionId":2,"questions":null,"choice":"upendera"},{"choicesId":2,"questionId":2,"questions":null,"choice":"real star"},{"choicesId":3,"questionId":2,"questions":null,"choice":"Super star"},{"choicesId":4,"questionId":2,"questions":null,"choice":"Only star"}]}]


问:
Pass values in array to a range of cells on Google Spreadsheet
I'm tryin to read in a column of cells its numbers and backgrounng colors ,and copy it to another columuns.

I can read both and put values in arrays, so what I need is pass the values in these arrays to the range that should receive it.

That's what I'm trying, reading values in column A and pass it to column C:

```<code>var origin =["A1:A5"]
var destiny=["C1:C5"]

var ColCell = SpreadsheetApp.getActiveSpreadsheet().getRange(origin).getBackgrounds();
var ValCell=SpreadsheetApp.getActiveSheet().getRange(origin).getValues();

// now i have two arrays, ColCell and ValCell,
// that have backgound colors and Values of original
// cells in the range "A1:A5".
</code>```

I can't figure how to pass values in ColCell and ValCell to ["C1:C5"]. Have anyone had this problem before?

答:
You want to copy the values (background colors and cell values) of "A1:A5" of the active sheet to the range of "C1:C5" of the active sheet using Google Apps Script.

If my understanding is correct, how about this modification?

Modified script:

```<code>var origin = ["A1:A5"];
var destiny = ["C1:C5"];

// Retrieve values.
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange(origin);
var ColCell = range.getBackgrounds();
var ValCell = range.getValues();

// Set values.
sheet.getRange(destiny).setBackgrounds(ColCell).setValues(ValCell);
</code>```

References:

setBackgrounds(color)

setValues(values)

If I misunderstood your question and this was not the result you want, I apologize.

Body:
I'm tryin to read in a column of cells its numbers and backgrounng colors ,and copy it to another columuns.

I can read both and put values in arrays, so what I need is pass the values in these arrays to the range that should receive it.

That's what I'm trying, reading values in column A and pass it to column C:

var origin =["A1:A5"]
var destiny=["C1:C5"]

var ColCell = SpreadsheetApp.getActiveSpreadsheet().getRange(origin).getBackgrounds();
var ValCell=SpreadsheetApp.getActiveSheet().getRange(origin).getValues();

// now i have two arrays, ColCell and ValCell,
// that have backgound colors and Values of original
// cells in the range "A1:A5".

I can't figure how to pass values in ColCell and ValCell to ["C1:C5"]. Have anyone had this problem before?

Body:
You want to copy the values (background colors and cell values) of "A1:A5" of the active sheet to the range of "C1:C5" of the active sheet using Google Apps Script.

If my understanding is correct, how about this modification?

Modified script:

var origin = ["A1:A5"];
var destiny = ["C1:C5"];

// Retrieve values.
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange(origin);
var ColCell = range.getBackgrounds();
var ValCell = range.getValues();

// Set values.
sheet.getRange(destiny).setBackgrounds(ColCell).setValues(ValCell);

References:

setBackgrounds(color)

setValues(values)

If I misunderstood your question and this was not the result you want, I apologize.


问:
ERROR !!! OpenQA.Selenium.DriverServiceNotFoundException is showing even tho i have installed all the drivers required
OpenQA.Selenium.DriverServiceNotFoundException . Tried Installing all the drivers but still showing me the error. </p>

```<code>using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System.Threading;

namespace lettryanotherone
{
    class EntryPoint
    {
        static void Main(string[] args)
        {

            IWebDriver ChromeDriver = new ChromeDriver();

            ChromeDriver.Navigate().GoToUrl("http://www.OverWorldInnovations.com");
            Thread.Sleep(3000);

            ChromeDriver.Quit();

        }
    }
}
</code>```

答:
Make sure to download Chromedriver which exactly matches Chrome browser version you're using

Unpack chromedriver.exe somewhere in operating system PATH

That should be it, however you might need to restart your console and/or IDE

Instead of step 2 you can also consider using ChromeDriverService class and explicitly provide the location of the chromedriver.exe to the ChromeDriver initialization statement.

```<code>// given path to chromedriver is c:\selenium\webdriver\chromedriver.exe
ChromeDriver driver = new ChromeDriver(
    ChromeDriverService.CreateDefaultService("c:\\selenium\\webdriver", "chromedriver.exe"));
</code>```

Selenium C# Tutorial for Beginners

Selenium with C Sharp

Body:
OpenQA.Selenium.DriverServiceNotFoundException . Tried Installing all the drivers but still showing me the error.

using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System.Threading;

namespace lettryanotherone
{
    class EntryPoint
    {
        static void Main(string[] args)
        {

            IWebDriver ChromeDriver = new ChromeDriver();

            ChromeDriver.Navigate().GoToUrl("http://www.OverWorldInnovations.com");
            Thread.Sleep(3000);

            ChromeDriver.Quit();

        }
    }
}

Body:
Make sure to download Chromedriver which exactly matches Chrome browser version you're using

Unpack chromedriver.exe somewhere in operating system PATH

That should be it, however you might need to restart your console and/or IDE

Instead of step 2 you can also consider using ChromeDriverService class and explicitly provide the location of the chromedriver.exe to the ChromeDriver initialization statement.

// given path to chromedriver is c:\selenium\webdriver\chromedriver.exe
ChromeDriver driver = new ChromeDriver(
    ChromeDriverService.CreateDefaultService("c:\\selenium\\webdriver", "chromedriver.exe"));

Selenium C# Tutorial for Beginners

Selenium with C Sharp


问:
Find maximum value of a column and return the corresponding row values using Pandas

Using Python Pandas I am trying to find the Country & Place with the maximum value.

This returns the maximum value:

```<code>data.groupby(['Country','Place'])['Value'].max()
</code>```

But how do I get the corresponding Country and Place name?

答:
I'd recommend using nlargest for better performance and shorter code. import pandas

```<code>df[col_name].value_counts().nlargest(n=1)
</code>```

Body:
Using Python Pandas I am trying to find the Country & Place with the maximum value.

This returns the maximum value:

data.groupby(['Country','Place'])['Value'].max()

But how do I get the corresponding Country and Place name?

Body:
I'd recommend using nlargest for better performance and shorter code. import pandas

df[col_name].value_counts().nlargest(n=1)


问:
Best Way to manage AWS Access key ? So that when an employee leave the company . The employ should not be able to access the AWS account
I want to know a way .

Assume there is an organization . There are many team which are using the EC2 resource and all the user have key that is required for the EC2 and now the employee leave the company . But he still have that Access key using which he can access it .

is there any best way to handle . AWS account permission so that when employee leave the company the access to aws account is denied .

答:
Your question is a little unclear, so I'll start by clarifying a few terms.

An AWS Access Key (which looks like AKIAIOSFODNN7EXAMPLE) is associated with an IAM User. Think of it like a username when making API calls. It is accompanied by a Secret Key that acts like a password.

An Access Key and Secret Key is used when making API calls to AWS, such as requesting creation of an Amazon EC2 instance or sending a message to an Amazon SQS queue.

A Keypair, on the other hand, is used when connecting to a Linux computer (even outside of AWS). When using a command like ssh, a user can authenticate by providing the private half of a keypair. The receiving computer then compares it to the public half of the key pair which is stored in the user's .ssh/authorized_keys file. If they match, the user is permitted to login.

When launching a new Amazon EC2 instance, you can specify a keypair. Software on Amazon Linux AMIs will copy this keypair to /users/ec2-user/.ssh/authorized_keys so that you can login to the instance. After doing so, it is recommended that you connect the instance to your standard corporate security system, such as Active Directory or LDAP. Continuing to use keypairs rather than AD/LDAP can be difficult to manage on an on-going basis.

So, to answer your question...

If you are referring to an Access Key, then simply delete the IAM User and their Access Key can no longer be used.

If you are referring to a Keypair, then in the best situation, access is managed with Active Directory or LDAP. If so, you can disable the user in the directory.

If, on the other hand, you are managing access by using the keypairs originally setup on the instance, then you will need to go to every instance that has that keypair and remove it from the appropriate authorized_keys file. Please note that a keypair is stored in a user directory, to there might be multiple users on an instance that have a copy of the keypair. If this sounds like a lot of work, then you now know why many organizations prefer using a central directory of users to manage security.


问:
setSerializationId no such method error
Im trying to run my project, but this error hits me everytime:

```<code>org.springframework.web.context.ContextLoaderListener
java.lang.NoSuchMethodError: org.springframework.beans.factory.support.DefaultListableBeanFactory.setSerializationId(Ljava/lang/String;)V
    at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:128)
    at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:467)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:397)
    at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
</code>```

This is my spring application context:

http://sharetext.org/2E7

What can cause this? Any help would be appreciated.

Thanks in advance.

答: The setSerializationId method is present in DefaultListableBeanFactory class from spring 3.0 but not in the same class from spring 2.5. I think you're working with a mixdown of the two versions of spring. It seems that you are using a library which depends on the old version of spring, for instance maybe spring-web. I suggest you to check all the jars in your classpath.

Title: setSerializationId no such method error

Body:
Im trying to run my project, but this error hits me everytime:

org.springframework.web.context.ContextLoaderListener
java.lang.NoSuchMethodError: org.springframework.beans.factory.support.DefaultListableBeanFactory.setSerializationId(Ljava/lang/String;)V
    at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:128)
    at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:467)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:397)
    at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)

This is my spring application context:

http://sharetext.org/2E7

What can cause this? Any help would be appreciated.

Thanks in advance.


问:
Querying into arrays with JSON_VALUE
I have a field with the following JSON data in it

```<code>[
   {
      "@odata.type":"#Sitecore.XConnect.Goal",
      "CustomValues":[

      ],
      "DefinitionId":"82c4c49c-b6b2-4b02-8e2f-fbcba9f92fe4",
      "EngagementValue":60,
      "Id":"335c92ce-5e36-4b13-9472-4940ad66e75f",
      "Timestamp":"2019-05-07T23:53:34.4268677Z"
   }
]
</code>```

I am trying to find all SQL rows that have the field @odata.type equal to #Sitecore.XConnect.Goal. But it is inside of an array. I have tried the SQL below, but I can't return any SQL rows.

```<code>SELECT *
  FROM [client_Xdb.Collection.Shard0].[xdb_collection].[Interactions]
  WHERE JSON_VALUE([Events], '$.[0]"odata.type"') = '#Sitecore.XConnect.Goal'
</code>```

答:
You need to specify the path as '$[0]."@odata.type"' (missing dot operator . that indicates a member of your $[0] object).

```<code>SELECT *
FROM [usms_Xdb.Collection.Shard0].[xdb_collection].[Interactions]
WHERE JSON_VALUE([Events], '$[0]."@odata.type"') = '#Sitecore.XConnect.Goal'
</code>```

Example:

```<code>DECLARE @json nvarchar(max) = N'[
   {
      "@odata.type":"#Sitecore.XConnect.Goal",
      "CustomValues":[

      ],
      "DefinitionId":"82c4c49c-b6b2-4b02-8e2f-fbcba9f92fe4",
      "EngagementValue":60,
      "Id":"335c92ce-5e36-4b13-9472-4940ad66e75f",
      "Timestamp":"2019-05-07T23:53:34.4268677Z"
   }
]'

SELECT JSON_VALUE(@json, '$[0]."@odata.type"') AS JsonValue
</code>```

Output:

```<code>-----------------------
JsonValue
-----------------------
#Sitecore.XConnect.Goal
</code>```

Title: Querying into arrays with JSON_VALUE

Body:
I have a field with the following JSON data in it

[
   {
      "@odata.type":"#Sitecore.XConnect.Goal",
      "CustomValues":[

      ],
      "DefinitionId":"82c4c49c-b6b2-4b02-8e2f-fbcba9f92fe4",
      "EngagementValue":60,
      "Id":"335c92ce-5e36-4b13-9472-4940ad66e75f",
      "Timestamp":"2019-05-07T23:53:34.4268677Z"
   }
]

I am trying to find all SQL rows that have the field @odata.type equal to #Sitecore.XConnect.Goal. But it is inside of an array. I have tried the SQL below, but I can't return any SQL rows.

SELECT *
  FROM [client_Xdb.Collection.Shard0].[xdb_collection].[Interactions]
  WHERE JSON_VALUE([Events], '$.[0]"odata.type"') = '#Sitecore.XConnect.Goal'

Body:
You need to specify the path as '$[0]."@odata.type"' (missing dot operator . that indicates a member of your $[0] object).

SELECT *
FROM [usms_Xdb.Collection.Shard0].[xdb_collection].[Interactions]
WHERE JSON_VALUE([Events], '$[0]."@odata.type"') = '#Sitecore.XConnect.Goal'

Example:

DECLARE @json nvarchar(max) = N'[
   {
      "@odata.type":"#Sitecore.XConnect.Goal",
      "CustomValues":[

      ],
      "DefinitionId":"82c4c49c-b6b2-4b02-8e2f-fbcba9f92fe4",
      "EngagementValue":60,
      "Id":"335c92ce-5e36-4b13-9472-4940ad66e75f",
      "Timestamp":"2019-05-07T23:53:34.4268677Z"
   }
]'

SELECT JSON_VALUE(@json, '$[0]."@odata.type"') AS JsonValue

Output:

-----------------------
JsonValue
-----------------------
#Sitecore.XConnect.Goal


问:
Convert list of pandas series to pandas dataframe
I have a list of rows that I want to convert to a data frame. Each element of a list is of type pandas Series. How can I convert it?

The sample data is like this:

```<code>GROUP_NUM                                                      61
PID_LOCATION    [(-111.58903, 33.252235), (-111.59659, 33.2470...)]
PROJECT_KEYS    224033,20542,224037,224039,224040,224041,16610...
PROJECT_NAME    name1...
ZIPCODE         xxxxx
DEFAULT_GEOM    MULTIPOLYGON (((-111.645291932 33.215893723,-1...
Name: 8468, dtype: object, aoi_attr_type_id
aoi_id                       ffeaac-cb85-447f-a367-b37558e452
GROUP_NUM                                                      60
PID_LOCATION                      [(u'-117.40181', u'34.542542')]
PROJECT_KEYS                                               204222
PROJECT_NAME                                          xyz
ZIPCODE                                                     92xxx
DEFAULT_GEOM    MULTIPOLYGON(((-117.416929337 34.557322993,-11...)))
Name: 8469, dtype: object, aoi_attr_type_id
aoi_id                       ff69ae-d61a-4776-af1d-5da73eb05a
GROUP_NUM                                                      63
PID_LOCATION    [(-97.348755, 32.587357), (-97.33046, 32.57823...)]
PROJECT_KEYS                     218461,181794,209575,59540,15239
PROJECT_NAME    some_name2
ZIPCODE                                               yyyyy
DEFAULT_GEOM    MULTIPOLYGON (((-97.332423163 32.571877745,-97...)))
Name: 8470, dtype: object]```

I tried this and get the following error:

    ipdb> res_df=pd.DataFrame.from_items(merged_polygons)
    *** ValueError: too many values to unpack

FYI
ipdb> type(merged_polygons[0])
<class 'pandas.core.series.Series'>
```

答:
You may use pd.concat to make it more simple. Every series will be a column in df

```<code>df = pd.concat(merged_polygons, axis=1)
</code>```

If you want every series as a row in df, just add T

```<code>df = pd.concat(merged_polygons, axis=1).T

or

df = pd.DataFrame(merged_polygons)
</code>```

Body:
I have a list of rows that I want to convert to a data frame. Each element of a list is of type pandas Series. How can I convert it?

The sample data is like this:

GROUP_NUM                                                      61
PID_LOCATION    [(-111.58903, 33.252235), (-111.59659, 33.2470...)]
PROJECT_KEYS    224033,20542,224037,224039,224040,224041,16610...
PROJECT_NAME    name1...
ZIPCODE         xxxxx
DEFAULT_GEOM    MULTIPOLYGON (((-111.645291932 33.215893723,-1...
Name: 8468, dtype: object, aoi_attr_type_id
aoi_id                       ffeaac-cb85-447f-a367-b37558e452
GROUP_NUM                                                      60
PID_LOCATION                      [(u'-117.40181', u'34.542542')]
PROJECT_KEYS                                               204222
PROJECT_NAME                                          xyz
ZIPCODE                                                     92xxx
DEFAULT_GEOM    MULTIPOLYGON(((-117.416929337 34.557322993,-11...)))
Name: 8469, dtype: object, aoi_attr_type_id
aoi_id                       ff69ae-d61a-4776-af1d-5da73eb05a
GROUP_NUM                                                      63
PID_LOCATION    [(-97.348755, 32.587357), (-97.33046, 32.57823...)]
PROJECT_KEYS                     218461,181794,209575,59540,15239
PROJECT_NAME    some_name2
ZIPCODE                                               yyyyy
DEFAULT_GEOM    MULTIPOLYGON (((-97.332423163 32.571877745,-97...)))
Name: 8470, dtype: object]```

I tried this and get the following error:

    ipdb> res_df=pd.DataFrame.from_items(merged_polygons)
    *** ValueError: too many values to unpack

FYI
ipdb> type(merged_polygons[0])
<class 'pandas.core.series.Series'>

Body:
You may use pd.concat to make it more simple. Every series will be a column in df

df = pd.concat(merged_polygons, axis=1)

If you want every series as a row in df, just add T

df = pd.concat(merged_polygons, axis=1).T

or

df = pd.DataFrame(merged_polygons)


问:
How to show plot made in R in pycharm?
I'm learning R, for one of my projects. I use it in combination with the JetBrains Pycharm IDE.

It seems that it has out of the box support for R. However when I plot something nothing shows up in the "SciView" or "R Graphics" window.

The R code does generate a pdf file with the correct plot.

I use this code:

```<code># Title     : TODO
# Objective : TODO
# Created by: boatfolder
# Created on: 2019-03-04

print("Hello world")

# Define the cars vector with 5 values
cars <- c(1, 3, 6, 4, 9)

# Graph cars using blue points overlayed by a line
plot(cars, type="o", col="blue")

# Create a title with a red, bold/italic font
title(main="Autos", col.main="red", font.main=4)
</code>```

And this is how the result looks like:

Why is it not showing up in the "SciView" or "R Graphics" window?

答:
It's disable now:
https://github.com/holgerbrandl/r4intellij/issues/134

I use jpeg(...) to set ouput file name like:

```<code>jpeg("plot.jpg")
plot(c(1, 2, 3), c(1, 2, 3))
</code>```

Hope it will be useful for someone

Title: How to show plot made in R in pycharm?

Body:
I'm learning R, for one of my projects. I use it in combination with the JetBrains Pycharm IDE.

It seems that it has out of the box support for R. However when I plot something nothing shows up in the "SciView" or "R Graphics" window.

The R code does generate a pdf file with the correct plot.

I use this code:

# Title     : TODO
# Objective : TODO
# Created by: boatfolder
# Created on: 2019-03-04

print("Hello world")

# Define the cars vector with 5 values
cars <- c(1, 3, 6, 4, 9)

# Graph cars using blue points overlayed by a line
plot(cars, type="o", col="blue")

# Create a title with a red, bold/italic font
title(main="Autos", col.main="red", font.main=4)

And this is how the result looks like:

Why is it not showing up in the "SciView" or "R Graphics" window?

Body:
It's disable now:
https://github.com/holgerbrandl/r4intellij/issues/134

I use jpeg(...) to set ouput file name like:

jpeg("plot.jpg")
plot(c(1, 2, 3), c(1, 2, 3))

Hope it will be useful for someone


问:
issue in getting unsorted eigen values
I want to extract linearly independent samples from a matrix. For which I want to use eigen values. But the issue is numpy/scipy based functions give sorted list of eigen values. Through which I loose the information that which eigen value corresponds to which row vector of original matrix, in order to carefully drop them.

I tried to create my own code to compute eigen values as:

```<code>   numpy.linalg.solve(numpy.linalg.det(I,A))
</code>```

where, A is the original matrix and I is identity. But this gives error and is incorrect. What way I can solve this problem?

答:
They do not give sorted lists by default, try for example

```<code>import numpy as np
from numpy import linalg as LA
A = np.array([[1,2,3],[3,2,1],[1,0,-1]])
w, v = LA.eig(A)
print(w)
    [  4.31662479e+00  -2.31662479e+00   3.43699053e-17]
print(v)
    [[ 0.58428153  0.73595785  0.40824829]
     [ 0.80407569 -0.38198836 -0.81649658]
     [ 0.10989708 -0.55897311  0.40824829]]
</code>```

The eigenvalue w[0] corresponds to the 0th column of v. The eigenvalue w[1] to column 1, .... To extract the ith column vector, just use

```<code>u = v[:,i]
</code>```

Title: issue in getting unsorted eigen values

Body:
I want to extract linearly independent samples from a matrix. For which I want to use eigen values. But the issue is numpy/scipy based functions give sorted list of eigen values. Through which I loose the information that which eigen value corresponds to which row vector of original matrix, in order to carefully drop them.

I tried to create my own code to compute eigen values as:

   numpy.linalg.solve(numpy.linalg.det(I,A))

where, A is the original matrix and I is identity. But this gives error and is incorrect. What way I can solve this problem?

Body:
They do not give sorted lists by default, try for example

import numpy as np
from numpy import linalg as LA
A = np.array([[1,2,3],[3,2,1],[1,0,-1]])
w, v = LA.eig(A)
print(w)
    [  4.31662479e+00  -2.31662479e+00   3.43699053e-17]
print(v)
    [[ 0.58428153  0.73595785  0.40824829]
     [ 0.80407569 -0.38198836 -0.81649658]
     [ 0.10989708 -0.55897311  0.40824829]]

The eigenvalue w[0] corresponds to the 0th column of v. The eigenvalue w[1] to column 1, .... To extract the ith column vector, just use

u = v[:,i]


问:
How to remove Kotlin support from an Android project?
How to remove kotlin support from a new project and work with only java support without creating a new project ?</p>

答:
While creating a new Project

Select Java Language, instead of Kotlin


问:
Google promises that Fusion tables can be imported into Google Sheets but how?
Google states that fusion tables could be imported into sheets and turned into maps but I cannot find any information on how to import Fusion tables nor how to turn them into maps similar as in Fusion Tables. Please help!

Googled for hours...

答:
From https://support.google.com/fusiontables/?hl=en

Google Fusion Tables will not be available after Dec. 3, 2019. Learn more

From https://developers.google.com/apps-script/advanced/fusion-tables

Warning: The Fusion Tables API that this service enabled was deprecated on December 11, 2018. You can continue to use the advanced service until December 3, 2019, when the API will be fully shutdown. See the Fusion Tables help center for more details.

Anyway, the above link include code samples. I think that this links will help you on your quest is you still are interested on using Fusion Tables.


问:
Using Silverlight for an entire website?
We need to build an administration portal website to support our client/server application. Since we're a .Net shop the obvious traditional way would be to do that in ASP.Net. But Silverlight 2 will be coming out of beta a good while before our release date. Should we consider building the whole website in silverlight instead, with a supporting WCF backend?

The main function of the portal will be: users, groups and permissions configuration; user profile settings configuration; file upload and download for files needed to support the application.

I think the main reason for taking this approach would be that we have good experience with WPF and WCF, but little experience in ASP.Net. Either way we would have to learn ASP.Net or Silverlight, and learning Silverlight seems a more natural extension of our current skills.

Are there any big no-nos from the experience of StackOverflowers? What are the big positives?

答: There are some downsides with developing a site completely in Flash / Silverlight, but if those downsides won't matter to you or won't have an impact then there is nothing stopping you. Choose whatever tool you think meets your needs more fully. I wouldn't be put off creating a site purely in Silverlight based on the downsides, because it brings a lot more positives to the user experience.</p>

OwnerDisplayName: Sam

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Sam

OwnerDisplayName: Mark Ingram


问:
problem with space display on tkinter widgets
I just learned tkinterr, I want to make widgets display using tkinter, I have a problem doing the layout, the text that I want to display instead is centered, can I get help putting text on the linked widget to the left corner and using neat spaces or tutorial recommendations for management of layouts on widgets
the appearance is like this.</p>

```<code>import time
import serial
from Tkinter import *

serial_speed = 115200
serial_port = '/dev/ttyACM0'

ser = serial.Serial(serial_port, serial_speed, timeout=1)

class Application(Frame):

    def measure(self):

         ser.write("m")
        data = ser.readline()

        # If the answer is not empty, process & display data
        if (data != ""):
            processed_data = data.split(",")

            self.tegangan_data.set("TEGANGAN: " + str(processed_data[0]))
            self.tegangan.pack()

            self.arus_data.set("    ARUS    : " + str(processed_data[1]))
            self.arus.pack()

            self.daya_data.set("   DAYA : " + str(processed_data[2]))
            self.daya.pack()

            self.torsi_data.set("   TORSI   : " + str(processed_data[3]))
            self.torsi.pack()

            self.panas_data.set("   PANAS MESIN : " + str(processed_data[4]))
            self.panas.pack()

            self.jarak_data.set("   JARAK TEMPUH    : " + str(processed_data[5]))
            self.jarak.pack()

        # Wait 1 second between each measurement
        self.after(500,self.measure)

    # Create display elements
    def createWidgets(self):

        self.tegangan = Label(self, textvariable=self.tegangan_data, font=('Verdana', 20, 'bold'))
        self.tegangan_data.set("Tegangan")
        self.tegangan.pack()

        self.arus = Label(self, textvariable=self.arus_data, font=('Verdana', 20, 'bold'))
        self.arus_data.set("Arus")
        self.arus.pack()

        self.daya = Label(self, textvariable=self.daya_data, font=('Verdana', 20, 'bold'))
        self.daya_data.set("Daya")
        self.daya.pack()

        self.torsi = Label(self, textvariable=self.torsi_data, font=('Verdana', 20, 'bold'))
        self.torsi_data.set("Torsi")
        self.torsi.pack()

        self.panas = Label(self, textvariable=self.panas_data, font=('Verdana', 20, 'bold'))
        self.panas_data.set("Panas mesin")
        self.panas.pack()

        self.jarak = Label(self, textvariable=self.jarak_data, font=('Verdana', 20, 'bold'))
        self.jarak_data.set("Daya")
        self.jarak.pack()

     def __init__(self, master=None):
        Frame.__init__(self, master)
        self.tegangan_data = StringVar()
        self.arus_data = StringVar()
        self.daya_data = StringVar()
        self.torsi_data = StringVar()
        self.panas_data = StringVar()
        self.jarak_data = StringVar()

        self.createWidgets()
        self.pack()
        self.measure()
root = Tk()
app = Application(master=root)
app.mainloop()
</code>```

答:
To make the labels left-aligned in your window, you can change the code in the "measure" method to be:

```<code>            self.tegangan_data.set("TEGANGAN: " + str(processed_data[0]))
            self.tegangan.pack(anchor='w')

            self.arus_data.set("ARUS: " + str(processed_data[1]))
            self.arus.pack(anchor='w')

            self.daya_data.set("DAYA: " + str(processed_data[2]))
            self.daya.pack(anchor='w')

            self.torsi_data.set("TORSI: " + str(processed_data[3]))
            self.torsi.pack(anchor='w')

            self.panas_data.set("PANAS MESIN: " + str(processed_data[4]))
            self.panas.pack(anchor='w')

            self.jarak_data.set("JARAK TEMPUH: " + str(processed_data[5]))
            self.jarak.pack(anchor='w')
</code>```

Which will result in this:

Now if you expand the window horizontally, you will see that even though the labels remain left-aligned, they do not stick to the left-side of the window but instead stay in the middle. I don't know if you want that behavior or not, but if you want to get an idea of why this happened, change the line initializing the Frame window to:

```<code>Frame.__init__(self, master, borderwidth=5, relief=RIDGE)
</code>```

The labels are currently packed to the left side of the frame but the frame that contain them is not packed to the left side of the window. A frame can be packed just like other Tkinter UI widgets. Since you inherited from Frame in the Application class, you can use this after you called the Application constructor (if you want the frame and the labels to stay on left side of the window):

```<code>app.pack(anchor='w')
</code>```

You can also use:

```<code>app.pack(side='left')
</code>```

There is a difference in their behavior though, but I'll leave that to you to explore.

Finally, to improve the look of the application, you can configure the frame to always have some padding between it and the edges of the window. Try this:

```<code>app.config(padx=20)
app.config(pady=10)
</code>```

A good source of information on using pack():
https://effbot.org/tkinterbook/pack.htm

If you want to do complicated layout in Tkinter then you should check out grid():
https://effbot.org/tkinterbook/grid.htm

Also, it's a good idea to check out documentation of the widgets you will have to work with, e.g. Frame
http://effbot.org/tkinterbook/frame.htm

Body:
I just learned tkinterr, I want to make widgets display using tkinter, I have a problem doing the layout, the text that I want to display instead is centered, can I get help putting text on the linked widget to the left corner and using neat spaces or tutorial recommendations for management of layouts on widgets
the appearance is like this.

import time
import serial
from Tkinter import *

serial_speed = 115200
serial_port = '/dev/ttyACM0'

ser = serial.Serial(serial_port, serial_speed, timeout=1)

class Application(Frame):

    def measure(self):

         ser.write("m")
        data = ser.readline()

        # If the answer is not empty, process & display data
        if (data != ""):
            processed_data = data.split(",")

            self.tegangan_data.set("TEGANGAN: " + str(processed_data[0]))
            self.tegangan.pack()

            self.arus_data.set("    ARUS    : " + str(processed_data[1]))
            self.arus.pack()

            self.daya_data.set("   DAYA : " + str(processed_data[2]))
            self.daya.pack()

            self.torsi_data.set("   TORSI   : " + str(processed_data[3]))
            self.torsi.pack()

            self.panas_data.set("   PANAS MESIN : " + str(processed_data[4]))
            self.panas.pack()

            self.jarak_data.set("   JARAK TEMPUH    : " + str(processed_data[5]))
            self.jarak.pack()

        # Wait 1 second between each measurement
        self.after(500,self.measure)

    # Create display elements
    def createWidgets(self):

        self.tegangan = Label(self, textvariable=self.tegangan_data, font=('Verdana', 20, 'bold'))
        self.tegangan_data.set("Tegangan")
        self.tegangan.pack()

        self.arus = Label(self, textvariable=self.arus_data, font=('Verdana', 20, 'bold'))
        self.arus_data.set("Arus")
        self.arus.pack()

        self.daya = Label(self, textvariable=self.daya_data, font=('Verdana', 20, 'bold'))
        self.daya_data.set("Daya")
        self.daya.pack()

        self.torsi = Label(self, textvariable=self.torsi_data, font=('Verdana', 20, 'bold'))
        self.torsi_data.set("Torsi")
        self.torsi.pack()

        self.panas = Label(self, textvariable=self.panas_data, font=('Verdana', 20, 'bold'))
        self.panas_data.set("Panas mesin")
        self.panas.pack()

        self.jarak = Label(self, textvariable=self.jarak_data, font=('Verdana', 20, 'bold'))
        self.jarak_data.set("Daya")
        self.jarak.pack()

     def __init__(self, master=None):
        Frame.__init__(self, master)
        self.tegangan_data = StringVar()
        self.arus_data = StringVar()
        self.daya_data = StringVar()
        self.torsi_data = StringVar()
        self.panas_data = StringVar()
        self.jarak_data = StringVar()

        self.createWidgets()
        self.pack()
        self.measure()
root = Tk()
app = Application(master=root)
app.mainloop()

Body:
To make the labels left-aligned in your window, you can change the code in the "measure" method to be:

            self.tegangan_data.set("TEGANGAN: " + str(processed_data[0]))
            self.tegangan.pack(anchor='w')

            self.arus_data.set("ARUS: " + str(processed_data[1]))
            self.arus.pack(anchor='w')

            self.daya_data.set("DAYA: " + str(processed_data[2]))
            self.daya.pack(anchor='w')

            self.torsi_data.set("TORSI: " + str(processed_data[3]))
            self.torsi.pack(anchor='w')

            self.panas_data.set("PANAS MESIN: " + str(processed_data[4]))
            self.panas.pack(anchor='w')

            self.jarak_data.set("JARAK TEMPUH: " + str(processed_data[5]))
            self.jarak.pack(anchor='w')

Which will result in this:

Now if you expand the window horizontally, you will see that even though the labels remain left-aligned, they do not stick to the left-side of the window but instead stay in the middle. I don't know if you want that behavior or not, but if you want to get an idea of why this happened, change the line initializing the Frame window to:

Frame.__init__(self, master, borderwidth=5, relief=RIDGE)

The labels are currently packed to the left side of the frame but the frame that contain them is not packed to the left side of the window. A frame can be packed just like other Tkinter UI widgets. Since you inherited from Frame in the Application class, you can use this after you called the Application constructor (if you want the frame and the labels to stay on left side of the window):

app.pack(anchor='w')

You can also use:

app.pack(side='left')

There is a difference in their behavior though, but I'll leave that to you to explore.

Finally, to improve the look of the application, you can configure the frame to always have some padding between it and the edges of the window. Try this:

app.config(padx=20)
app.config(pady=10)

A good source of information on using pack():
https://effbot.org/tkinterbook/pack.htm

If you want to do complicated layout in Tkinter then you should check out grid():
https://effbot.org/tkinterbook/grid.htm

Also, it's a good idea to check out documentation of the widgets you will have to work with, e.g. Frame
http://effbot.org/tkinterbook/frame.htm


问:
Pandas: vectorize local range operations (max & sum for [i:i+2] rows)
I'm looking to do calculations in a local range for each row in a dataframe while avoiding a slow for loop. For example, for each row in the data below I want to find the maximum temperature within the next 3 days (including current day) and the total amount of rain within the next 3 days:

```<code>Day Temperature Rain
0   30          4
1   31          14
2   31          0
3   30          0
4   33          5
5   34          0
6   32          0
7   33          2
8   31          5
9   29          9
</code>```

The ideal output would then be the new columns as in the table below. TempMax of Day 0 shows the highest temperature between Day 0 and Day 2, RainTotal shows the sum of rain between Day 0 and Day 2:

```<code>Day  Temperature  Rain  TempMax  RainTotal
0    30           4     31       18
1    31           14    31       14
2    31           0     33       5
3    30           0     34       5
4    33           5     34       5
5    34           0     34       2
6    32           0     33       7
7    33           2     33       16
8    31           5     31       14
9    29           9     29       9
</code>```

Currently I'm using a for loop:

```<code>  # Make empty arrays to store each row's max & sum values
  temp_max = np.zeros(len(df))
  rain_total = np.zeros(len(df))

  # Loop through the df and do operations in the local range [i:i+2]
  for i in range(len(df)):
    temp_max[i] = df['Temperature'].iloc[i:i+2].max()
    rain_total = df['Rain'].iloc[i:i+2].sum()

  # Insert the arrays to df
  df['TempMax'] = temp_max
  df['RainTotal'] = rain_total
</code>```

The for loop gets the job done but takes 50 minutes with my dataframe. Any chance this can be vecrotized or made faster some other way?

Thanks a bunch!

答:
For the case when Day has data for all successive days, we can employ fast NumPy and SciPy tools to our rescue -

```<code>from scipy.ndimage.filters import maximum_filter1d

N = 2 # window length
temp = df['Temperature'].to_numpy()
rain = df['Rain'].to_numpy()
df['TempMax'] = maximum_filter1d(temp,N+1,origin=-1,mode='nearest')
df['RainTotal'] = np.convolve(rain,np.ones(N+1,dtype=int))[N:]
</code>```

Sample output -

```<code>In [27]: df
Out[27]:
   Day  Temperature  Rain  TempMax  RainTotal
0    0           30     4       31         18
1    1           31    14       31         14
2    2           31     0       33          5
3    3           30     0       34          5
4    4           33     5       34          5
5    5           34     0       34          2
6    6           32     0       33          7
7    7           33     2       33         16
8    8           31     5       31         14
9    9           29     9       29          9
</code>```

Body:
I'm looking to do calculations in a local range for each row in a dataframe while avoiding a slow for loop. For example, for each row in the data below I want to find the maximum temperature within the next 3 days (including current day) and the total amount of rain within the next 3 days:

Day Temperature Rain
0   30          4
1   31          14
2   31          0
3   30          0
4   33          5
5   34          0
6   32          0
7   33          2
8   31          5
9   29          9

The ideal output would then be the new columns as in the table below. TempMax of Day 0 shows the highest temperature between Day 0 and Day 2, RainTotal shows the sum of rain between Day 0 and Day 2:

Day  Temperature  Rain  TempMax  RainTotal
0    30           4     31       18
1    31           14    31       14
2    31           0     33       5
3    30           0     34       5
4    33           5     34       5
5    34           0     34       2
6    32           0     33       7
7    33           2     33       16
8    31           5     31       14
9    29           9     29       9

Currently I'm using a for loop:

  # Make empty arrays to store each row's max & sum values
  temp_max = np.zeros(len(df))
  rain_total = np.zeros(len(df))

  # Loop through the df and do operations in the local range [i:i+2]
  for i in range(len(df)):
    temp_max[i] = df['Temperature'].iloc[i:i+2].max()
    rain_total = df['Rain'].iloc[i:i+2].sum()

  # Insert the arrays to df
  df['TempMax'] = temp_max
  df['RainTotal'] = rain_total

The for loop gets the job done but takes 50 minutes with my dataframe. Any chance this can be vecrotized or made faster some other way?

Thanks a bunch!

Body:
For the case when Day has data for all successive days, we can employ fast NumPy and SciPy tools to our rescue -

from scipy.ndimage.filters import maximum_filter1d

N = 2 # window length
temp = df['Temperature'].to_numpy()
rain = df['Rain'].to_numpy()
df['TempMax'] = maximum_filter1d(temp,N+1,origin=-1,mode='nearest')
df['RainTotal'] = np.convolve(rain,np.ones(N+1,dtype=int))[N:]

Sample output -

In [27]: df
Out[27]:
   Day  Temperature  Rain  TempMax  RainTotal
0    0           30     4       31         18
1    1           31    14       31         14
2    2           31     0       33          5
3    3           30     0       34          5
4    4           33     5       34          5
5    5           34     0       34          2
6    6           32     0       33          7
7    7           33     2       33         16
8    8           31     5       31         14
9    9           29     9       29          9


答:
According to EF Core-Loading Related Data documentaiton you have to use .Include to load your related data as follows:

```<code>public List<Questions> getAllQuestions()
{
    return context.questions.Include(q => q.choices).ToList();
}
</code>```

Title: Entity Framework Core code-first approach one to many relationship returns null

Body:
I'm new to Entity Framework Core, in my code I have a number of Questions class objects, and a list of choices to those questions. My query list of Choices always returns Null.

Here are my classes:

public class Questions
{
    [Key]
    public int QuestionID { get; set; }
    public string  Question { get; set; }

    public ICollection<Choices> choices { get; set; }
}

public class Choices
{
    [Key]
    public int ChoicesId { get; set; }
    public int QuestionId { get; set; }
    public Questions questions  { get; set; }
    public string Choice { get; set; }
}

public class SqlUserRepository : IUserRepository
{
    private readonly AppDbContext context;

    public SqlUserRepository(AppDbContext context)
    {
        this.context = context;
    }

    public List<Questions> getAllQuestions()
    {
        return context.questions.ToList();
    }
}

I'm getting this O/p. choices always returns null

[
    { "questionID":1, "question":"which is your fav.heroien", "choices":null },
    { "questionID":2, "question":"which is your fav.hero", "choices":null  }
]

I expect this output

[{"questionID":1,"question":"which is your fav.heroien","choices":[{"choicesId":5,"questionId":1,"questions":null,"choice":"kajol Agarwal"},{"choicesId":6,"questionId":1,"questions":null,"choice":"Thammanna Bhatia"},{"choicesId":7,"questionId":1,"questions":null,"choice":"Anushka Shetty"},{"choicesId":8,"questionId":1,"questions":null,"choice":"Keerthi Suresh"}]},{"questionID":2,"question":"which is your fav.hero","choices":[{"choicesId":1,"questionId":2,"questions":null,"choice":"upendera"},{"choicesId":2,"questionId":2,"questions":null,"choice":"real star"},{"choicesId":3,"questionId":2,"questions":null,"choice":"Super star"},{"choicesId":4,"questionId":2,"questions":null,"choice":"Only star"}]}]

Body:
According to EF Core-Loading Related Data documentaiton you have to use .Include to load your related data as follows:

public List<Questions> getAllQuestions()
{
    return context.questions.Include(q => q.choices).ToList();
}


问:
How to get status of web service
How can I get the status of web service using C#? whether it is completed successfully, failed or pending like this.</p>

答:
if you are calling your webservice in sync mode, there is no problem with getting status.

if you are calling your webservice in Async mode, you should set a callback function and track webservice status in the result returned to that callback function.

Title: How to get status of web service


问:
VS Code and Typescript watch: Files are being recompiled without being saved
I'm developing a Typescript project and I run "tsc -w" to keep it compiling while I edit.

The problem is, sometimes my files will be recompiled even when I don't save them. Sometimes it recompiles files randomly that I haven't touched (Like if I open an existing file in typescript to begin editing)

Is this vs code? or Typescript? does anyone know a solution to stop this happening?

My .tsconfig is below

```<code>{
  "compilerOptions": {
    "target": "es2015",
    "module": "es2015",
    "allowJs": false,
    "jsx": "react",
    "sourceMap": true,
    "outDir": "build",

    "baseUrl": ".",
    "paths": {
      "@shared/*": [ "src/shared/*" ],
      "@app/*": ["src/*"]
    },
    "strict": true,
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "skipLibCheck": true,
  },
  "filesGlob": [
    "src/**/*.ts",
    "src/**/*.tsx",
  ],
  "types": [
    "react",
    "react-dom",
    "react-native"
  ],
  "exclude": [
    "build",
    "**/node_modules/*",
    "jest.config.js",
    "App.js"
  ],
  "include": [
    "./src",
  ],
  "compileOnSave": false
}
</code>```

答:
Turns out I didn't have to run a separate Typescript Watch process - Expo Typescript support has improved since I started my project.

See https://docs.expo.io/versions/latest/guides/typescript/

Body:
I'm developing a Typescript project and I run "tsc -w" to keep it compiling while I edit.

The problem is, sometimes my files will be recompiled even when I don't save them. Sometimes it recompiles files randomly that I haven't touched (Like if I open an existing file in typescript to begin editing)

Is this vs code? or Typescript? does anyone know a solution to stop this happening?

My .tsconfig is below

{
  "compilerOptions": {
    "target": "es2015",
    "module": "es2015",
    "allowJs": false,
    "jsx": "react",
    "sourceMap": true,
    "outDir": "build",

    "baseUrl": ".",
    "paths": {
      "@shared/*": [ "src/shared/*" ],
      "@app/*": ["src/*"]
    },
    "strict": true,
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "skipLibCheck": true,
  },
  "filesGlob": [
    "src/**/*.ts",
    "src/**/*.tsx",
  ],
  "types": [
    "react",
    "react-dom",
    "react-native"
  ],
  "exclude": [
    "build",
    "**/node_modules/*",
    "jest.config.js",
    "App.js"
  ],
  "include": [
    "./src",
  ],
  "compileOnSave": false
}


问:
Ionic 4 loading until images in page loaded
enter image description hereI am using ionic 4 so i need to a loader untill the page loaded completely. Now i am using loadingController and dismiss it when api res, loading finished but images still loading. I want loading untill all loading finished.

Like ionic 3 ionViewDidLoad() works
Below is the Answer i found on Ionic Documentation an event called ionImgWillLoad but dont know how to use it.

答: The closest to ionViewDidLoad is probably ionViewDidEnter. See the life cycle events below:


问:
Can I calculate the difference between two dates if there is matching data in another column, MTBF calculation
I am attempting to find the mean time between failure of serialized equipment. I am using Access 2013 for my database and have Access 2016 also. My problem is that I have multiple entries for the serial numbers with Warranty start dates and job entry dates. I need to calculate the days between each job if the serial numbers match. Using > to find the dates and then calculate them worked great until I had more than one entry for a serial number.

I have tried using a join property between two tables but could not calculate the dates correctly with more than two entries

Below is my sql statement. I would rather use VBA to calculate this if possible. I can post my data with the criteria I am looking for, this is my first post.

```<code>SELECT qry_MTBF_Warranty_Date_Closed.BarCode,
    tbl_Closed_Jobs.Cust_Part,
    tbl_Closed_Jobs.Desc,
    tbl_Closed_Jobs.Plant,
    tbl_Closed_Jobs.Date_Ent,
    qry_MTBF_Warranty_Date_Closed.Warranty_Activation,
    qry_MTBF_Warranty_Date_Closed.Warr_WO,
    qry_MTBF_Warranty_Date_Closed.Cust_Ref,
    qry_MTBF_Warranty_Date_Closed.Rel_No,
    (tbl_Closed_Jobs.Date_Ent-
    [qry_MTBF_Warranty_Date_Closed].Warranty_Activation) AS MTBF,
    "C" AS Status,
    tbl_Closed_Jobs.Prty
FROM qry_MTBF_Warranty_Date_Closed
    INNER JOIN tbl_Closed_Jobs ON qry_MTBF_Warranty_Date_Closed.BarCode = tbl_Closed_Jobs.BarCode
WHERE (((tbl_Closed_Jobs.Date_Ent)>=([qry_MTBF_Warranty_Date_Closed].[Warranty_Activation])) AND ((tbl_Closed_Jobs.Prty) Not Like "1C*"))
ORDER BY tbl_Closed_Jobs.Cust_Part;
</code>```

I expect to only have an output of days where my serial(Barcodes) match and the Priority codes are no a 1C. I can post an Excel file if that would help.

Thanks

So, I have SQL to find the number of days between the two dates if there are only two matching barcodes. I need to know the difference of days between each entry. The below sql will give me the Min and Max days and the difference of them but some barcodes will have multiple entries and I need to know the difference between each entry if the barcodes match..
SELECT t1.BarCode, max(abs(DateDiff("d", t3.Date_,t1.Date_Warranty))) AS DateDifference
FROM tbl_MTBF_Multiple_Entries AS t1 INNER JOIN (SELECT t2.BarCode as BarCode_, Max(t2.Date_Ent) as Date_
    FROM tbl_MTBF_Multiple_Entries t2
    GROUP BY t2.BarCode
    )  AS t3 ON t1.BarCode=t3.Barcode_
WHERE t1.Date_Warranty < t3.Date_
GROUP BY t1.BarCode;

答:
Try using built-in vba DateDiff()

```<code>Function DateDiff(Interval As String, Date1, Date2, [FirstDayOfWeek As VbDayOfWeek = vbSunday], [FirstWeekOfYear As VbFirstWeekOfYear = vbFirstJan1])
    Member of VBA.DateTime
</code>```

Example:

```<code>' Return the number of days remaining in the taxation year from the present date.
' Positive value <= 365 = taxation year has # days left.
' Positive value > 365, date is before taxation year.
' Negative value = beyond taxation year
Public Function daysRemainingInTaxYear() As Integer

    Dim myTaxationYear
    Dim myEoY As Variant

    myTaxationYear = DLookup("TaxationYear", "myParametersT", "ID=1")

    myEoY = "31/12/" & myTaxationYear
    daysRemainingInTaxYear = DateDiff("d", Now(), myEoY)
End Function
</code>```

Body:
I am attempting to find the mean time between failure of serialized equipment. I am using Access 2013 for my database and have Access 2016 also. My problem is that I have multiple entries for the serial numbers with Warranty start dates and job entry dates. I need to calculate the days between each job if the serial numbers match. Using > to find the dates and then calculate them worked great until I had more than one entry for a serial number.

I have tried using a join property between two tables but could not calculate the dates correctly with more than two entries

Below is my sql statement. I would rather use VBA to calculate this if possible. I can post my data with the criteria I am looking for, this is my first post.

SELECT qry_MTBF_Warranty_Date_Closed.BarCode,
    tbl_Closed_Jobs.Cust_Part,
    tbl_Closed_Jobs.Desc,
    tbl_Closed_Jobs.Plant,
    tbl_Closed_Jobs.Date_Ent,
    qry_MTBF_Warranty_Date_Closed.Warranty_Activation,
    qry_MTBF_Warranty_Date_Closed.Warr_WO,
    qry_MTBF_Warranty_Date_Closed.Cust_Ref,
    qry_MTBF_Warranty_Date_Closed.Rel_No,
    (tbl_Closed_Jobs.Date_Ent-
    [qry_MTBF_Warranty_Date_Closed].Warranty_Activation) AS MTBF,
    "C" AS Status,
    tbl_Closed_Jobs.Prty
FROM qry_MTBF_Warranty_Date_Closed
    INNER JOIN tbl_Closed_Jobs ON qry_MTBF_Warranty_Date_Closed.BarCode = tbl_Closed_Jobs.BarCode
WHERE (((tbl_Closed_Jobs.Date_Ent)>=([qry_MTBF_Warranty_Date_Closed].[Warranty_Activation])) AND ((tbl_Closed_Jobs.Prty) Not Like "1C*"))
ORDER BY tbl_Closed_Jobs.Cust_Part;

I expect to only have an output of days where my serial(Barcodes) match and the Priority codes are no a 1C. I can post an Excel file if that would help.

Thanks

So, I have SQL to find the number of days between the two dates if there are only two matching barcodes. I need to know the difference of days between each entry. The below sql will give me the Min and Max days and the difference of them but some barcodes will have multiple entries and I need to know the difference between each entry if the barcodes match..
SELECT t1.BarCode, max(abs(DateDiff("d", t3.Date_,t1.Date_Warranty))) AS DateDifference
FROM tbl_MTBF_Multiple_Entries AS t1 INNER JOIN (SELECT t2.BarCode as BarCode_, Max(t2.Date_Ent) as Date_
    FROM tbl_MTBF_Multiple_Entries t2
    GROUP BY t2.BarCode
    )  AS t3 ON t1.BarCode=t3.Barcode_
WHERE t1.Date_Warranty < t3.Date_
GROUP BY t1.BarCode;

Body:
Try using built-in vba DateDiff()

Function DateDiff(Interval As String, Date1, Date2, [FirstDayOfWeek As VbDayOfWeek = vbSunday], [FirstWeekOfYear As VbFirstWeekOfYear = vbFirstJan1])
    Member of VBA.DateTime

Example:

' Return the number of days remaining in the taxation year from the present date.
' Positive value <= 365 = taxation year has # days left.
' Positive value > 365, date is before taxation year.
' Negative value = beyond taxation year
Public Function daysRemainingInTaxYear() As Integer

    Dim myTaxationYear
    Dim myEoY As Variant

    myTaxationYear = DLookup("TaxationYear", "myParametersT", "ID=1")

    myEoY = "31/12/" & myTaxationYear
    daysRemainingInTaxYear = DateDiff("d", Now(), myEoY)
End Function


问:
How can i display the list of his/her orders that made by my login user?
I want to know. How can i change or improve my codes so that the login user can only see his/her order items? He/she cannot see others orders that not made by him/her.

this is senarai_tempahan.php. This is the interface for displaying the list of orders from tbl_orders.

```<code>
<?php
include('session.php');

 include_once 'orders_crud.php';

if(isset($_SESSION['login_user'])){

}
?>

<!DOCTYPE html>
<html>
<head>
   <link rel="icon" href="icon.ico">
  <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
  <title>EZ-Wedding4U : Senarai Tempahan</title>
  <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
   <style type="text/css">
      @import "main.css";

  </style>
</head>
<body>

  <?php include_once 'nav_bar3.php'; ?>

 <div class="container-fluid">

    <div class="row">
    <div class="col-xs-12 col-sm-10 col-sm-offset-1 col-md-8 col-md-offset-2">
      <div class="page-header">
        <h2>Tempahan Saya</h2>
      </div>
      <table class="table table-striped table-bordered">
        <tr>
          <th>Gambar</th>
          <th>Tempahan ID</th>
          <th>Tarikh Tempahan</th>
          <th>Nama Produk</th>
          <th>Kuantiti</th>
          <th>Harga per Unit</th>
          <th>Jumlah Harga (RM)</th>
          <th>Saiz</th>
          <th>Nama Pelanggan</th>
          <th>Alamat Pelanggan</th>
          <th>Notel Pelanggan</th>
          <th>Nama Syarikat</th>
          <th></th>
        </tr>

      <?php
      // Read
      $per_page = 5;
      if (isset($_GET["page"]))
        $page = $_GET["page"];
      else
        $page = 1;
      $start_from = ($page-1) * $per_page;

      try {
        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $stmt = $conn->prepare("SELECT * FROM tbl_orders, tbl_pelanggan WHERE
          tbl_orders.nama_pelanggan = tbl_pelanggan.nama_penuh AND
          tbl_pelanggan.nama_pengguna = '".$_SESSION['username']."' AND id =:oid
          LIMIT $start_from, $per_page");

        $stmt->execute();
        $result = $stmt->fetchAll();
      }
      catch(PDOException $e){
            echo "Error: " . $e->getMessage();
      }
      foreach($result as $readrow) {
      ?>
      <tr>
        <td> <?php if ($readrow['id'] == "" ) {
        echo "No image";
      }
      else { ?>
      <img src="produk/<?php echo $readrow['img'] ?>" class="img-responsive">
      <?php } ?></td>

        <td><?php echo $readrow['id']; ?></td>
        <td><?php echo $readrow['tarikh_tempah']; ?></td>
        <td><?php echo $readrow['nama_produk']; ?></td>
        <td><?php echo $readrow['kuantiti']; ?></td>
        <td><?php echo $readrow['harga']; ?></td>
        <td><?php echo $readrow['total_harga']; ?></td>
        <td><?php echo $readrow['saiz']; ?></td>
        <td><?php echo $readrow['nama_pelanggan']; ?></td>
        <td><?php echo $readrow['alamat_pelanggan']; ?></td>
        <td><?php echo $readrow['notel_pelanggan']; ?></td>
        <td><?php echo $readrow['namaSyarikat']; ?></td>

        <td>

          <a href="edit_tempahan.php?edit=<?php echo $readrow['id']; ?>" class="btn btn-success btn-xs" role="button"> Kemas kini </a>
          <a href="senarai_tempahan.php?delete=<?php echo $readrow['id']; ?>" onclick="return confirm('Anda pasti mahu membatalkan tempahan ini?');" class="btn btn-danger btn-xs" role="button">Batal</a>
        </td>
      </tr>
      <?php } ?>

    </table>
    </div>
  </div>
  <div class="row">
    <div class="col-xs-12 col-sm-10 col-sm-offset-1 col-md-8 col-md-offset-2">
      <nav>
          <ul class="pagination">
          <?php
          try {
            $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $stmt = $conn->prepare("SELECT * FROM tbl_orders, tbl_pelanggan
              WHERE tbl_orders.nama_pelanggan = tbl_pelanggan.nama_penuh AND
              tbl_pelanggan.nama_pengguna = '".$_SESSION['username']."' AND id =
              :oid ");

            $stmt->execute();
            $result = $stmt->fetchAll();
            $total_records = count($result);
          }
          catch(PDOException $e){
                echo "Error: " . $e->getMessage();
          }
          $total_pages = ceil($total_records / $per_page);
          ?>
          <?php if ($page==1) { ?>
            <li class="disabled"><span aria-hidden="true">«</span></li>
          <?php } else { ?>
            <li><a href="senarai_tempahan.php?page=<?php echo $page-1 ?>" aria-label="Previous"><span aria-hidden="true">«</span></a></li>
          <?php
          }
          for ($i=1; $i<=$total_pages; $i++)
            if ($i == $page)
              echo "<li class=\"active\"><a href=\"senarai_tempahan.php?page=$i\">$i</a></li>";
            else
              echo "<li><a href=\"senarai_tempahan.php?page=$i\">$i</a></li>";
          ?>
          <?php if ($page==$total_pages) { ?>
            <li class="disabled"><span aria-hidden="true">»</span></li>
          <?php } else { ?>
            <li><a href="senarai_tempahan.php?page=<?php echo $page+1 ?>" aria-label="Previous"><span aria-hidden="true">»</span></a></li>
          <?php } ?>
        </ul>
      </nav>
    </div>

</div>
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
  <script src="main.js">
      </script>
</body>
</html>
</code>```

I have try this code but it is error. I think that this code is wrong but I do not know how to fix it. I'm just want to display the data from tbl_orders that nama_pelanggan is equal to nama_penuh from tbl_pelanggan based on the login user data. please help me and thank you for your time and answers.

答:
You can do it very simply.
Just use WHERE id='$_SESSION["login_user"]'

Body:
I want to know. How can i change or improve my codes so that the login user can only see his/her order items? He/she cannot see others orders that not made by him/her.

this is senarai_tempahan.php. This is the interface for displaying the list of orders from tbl_orders.

<?php
include('session.php');

 include_once 'orders_crud.php';

if(isset($_SESSION['login_user'])){

}
?>

<!DOCTYPE html>

   <link rel="icon" href="icon.ico">
  <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>EZ-Wedding4U : Senarai Tempahan</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

  <?php include_once 'nav_bar3.php'; ?>

Tempahan Saya

          Gambar
          Tempahan ID
          Tarikh Tempahan
          Nama Produk
          Kuantiti
          Harga per Unit
          Jumlah Harga (RM)
          Saiz
          Nama Pelanggan
          Alamat Pelanggan
          Notel Pelanggan
          Nama Syarikat

      <?php
      // Read
      $per_page = 5;
      if (isset($_GET["page"]))
        $page = $_GET["page"];
      else
        $page = 1;
      $start_from = ($page-1) * $per_page;

      try {
        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $stmt = $conn->prepare("SELECT * FROM tbl_orders, tbl_pelanggan WHERE
          tbl_orders.nama_pelanggan = tbl_pelanggan.nama_penuh AND
          tbl_pelanggan.nama_pengguna = '".$_SESSION['username']."' AND id =:oid
          LIMIT $start_from, $per_page");

        $stmt->execute();
        $result = $stmt->fetchAll();
      }
      catch(PDOException $e){
            echo "Error: " . $e->getMessage();
      }
      foreach($result as $readrow) {
      ?>

         <?php if ($readrow['id'] == "" ) {
        echo "No image";
      }
      else { ?>
      <img src="produk/<?php echo $readrow['img'] ?>" class="img-responsive">
      <?php } ?>

        <?php echo $readrow['id']; ?>
        <?php echo $readrow['tarikh_tempah']; ?>
        <?php echo $readrow['nama_produk']; ?>
        <?php echo $readrow['kuantiti']; ?>
        <?php echo $readrow['harga']; ?>
        <?php echo $readrow['total_harga']; ?>
        <?php echo $readrow['saiz']; ?>
        <?php echo $readrow['nama_pelanggan']; ?>
        <?php echo $readrow['alamat_pelanggan']; ?>
        <?php echo $readrow['notel_pelanggan']; ?>
        <?php echo $readrow['namaSyarikat']; ?>

          <a href="edit_tempahan.php?edit=<?php echo $readrow['id']; ?>" class="btn btn-success btn-xs" role="button"> Kemas kini
          <a href="senarai_tempahan.php?delete=<?php echo $readrow['id']; ?>" onclick="return confirm('Anda pasti mahu membatalkan tempahan ini?');" class="btn btn-danger btn-xs" role="button">Batal

      <?php } ?>

          <?php
          try {
            $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $stmt = $conn->prepare("SELECT * FROM tbl_orders, tbl_pelanggan
              WHERE tbl_orders.nama_pelanggan = tbl_pelanggan.nama_penuh AND
              tbl_pelanggan.nama_pengguna = '".$_SESSION['username']."' AND id =
              :oid ");

            $stmt->execute();
            $result = $stmt->fetchAll();
            $total_records = count($result);
          }
          catch(PDOException $e){
                echo "Error: " . $e->getMessage();
          }
          $total_pages = ceil($total_records / $per_page);
          ?>
          <?php if ($page==1) { ?>

«

          <?php } else { ?>

<a href="senarai_tempahan.php?page=<?php echo $page-1 ?>" aria-label="Previous">«

          <?php
          }
          for ($i=1; $i<=$total_pages; $i++)
            if ($i == $page)
              echo "
$i
";
            else
              echo "
$i
";
          ?>
          <?php if ($page==$total_pages) { ?>

»

          <?php } else { ?>

<a href="senarai_tempahan.php?page=<?php echo $page+1 ?>" aria-label="Previous">»

          <?php } ?>

I have try this code but it is error. I think that this code is wrong but I do not know how to fix it. I'm just want to display the data from tbl_orders that nama_pelanggan is equal to nama_penuh from tbl_pelanggan based on the login user data. please help me and thank you for your time and answers.


问:
How to write multiple queries in one query based on condition in SQL Server?
```<code>SELECT
    [LNMAJORTP], [MainType],
    SUM(x + y - z) [x]
FROM
    [my_table]
WHERE
    state LIKE '%firstCondition%'
GROUP BY
    [LNMAJORTP], [MainType]

SELECT
    [LNMAJORTP], [MainType],
    SUM(x + y - z) [y]
FROM
    [my_table]
WHERE
    state LIKE '%secondCondition%'
GROUP BY
    [LNMAJORTP], [MainType]

SELECT
    [LNMAJORTP], [MainType],
    SUM(x + y - z) [z]
FROM
    [my_table]
WHERE
    state LIKE '%thirdCondition%'
GROUP BY
    [LNMAJORTP], [MainType]
</code>```

How I can change this queries to one query?

答:
You can merge your three query as follow. Which will return your results in different rows-    </p>

```<code>SELECT state,[LNMAJORTP],[MainType],
sum(x+y-z) [z]
FROM [my_table]
where state LIKE '%thirdCondition%'
OR state LIKE '%firstCondition%'
OR state LIKE '%secondCondition%'
GROUP BY state,[LNMAJORTP],[MainType]
</code>```

Body:
SELECT
    [LNMAJORTP], [MainType],
    SUM(x + y - z) [x]
FROM
    [my_table]
WHERE
    state LIKE '%firstCondition%'
GROUP BY
    [LNMAJORTP], [MainType]

SELECT
    [LNMAJORTP], [MainType],
    SUM(x + y - z) [y]
FROM
    [my_table]
WHERE
    state LIKE '%secondCondition%'
GROUP BY
    [LNMAJORTP], [MainType]

SELECT
    [LNMAJORTP], [MainType],
    SUM(x + y - z) [z]
FROM
    [my_table]
WHERE
    state LIKE '%thirdCondition%'
GROUP BY
    [LNMAJORTP], [MainType]

How I can change this queries to one query?

Body:
You can merge your three query as follow. Which will return your results in different rows-

SELECT state,[LNMAJORTP],[MainType],
sum(x+y-z) [z]
FROM [my_table]
where state LIKE '%thirdCondition%'
OR state LIKE '%firstCondition%'
OR state LIKE '%secondCondition%'
GROUP BY state,[LNMAJORTP],[MainType]


问:
Why is my buffer stored in two locations in stack?
Code:

```<code>#include <stdio.h>

    int main(int argc, char *argv[]){
    char buf[512];
    strcpy(buf, argv[1]);
    return 0;
}
</code>```

Compilation:

```<code>gcc -g -z execstack buf.c -o buf -fno-stack-protector
</code>```

Question:

So Basically using gdb I set a breakpoint on line return 0; and run the script as follow: run $(python -c 'print "A"*600'), and then when I do x/600x $rsp, I get my buffer start at:

```<code>0x7fffffffdcf0: 0xffffdfe8      0x00007fff      0xf7fd3298      0x00000002
0x7fffffffdd00: 0x41414141      0x41414141      0x41414141      0x41414141
0x7fffffffdd10: 0x41414141      0x41414141      0x41414141      0x41414141

// it goes on... until
0x7fffffffdf50: 0x41414141      0x41414141      0x00000000      0x00000000
</code>```

But then when I go further down the stack, I also see:

```<code>0x7fffffffe2f0: 0x776f6c66      0x6675622f      0x41414100      0x41414141
0x7fffffffe300: 0x41414141      0x41414141      0x41414141      0x41414141

// It goes until
0x7fffffffe540: 0x41414141      0x41414141      0x41414141      0x41414141
0x7fffffffe550: 0x48530041      0x3d4c4c45      0x6e69622f      0x7361622f
</code>```

Also for buffer overflow exploit, If I use first location, my exploit doesn't work, but if I use second location it works.

So May I know why is my buffer stored in two different locations?

答:
Your buffer isn’t stored in two places. You’re just copying the data yourself in your code. There’s the input that’s given to main and then your buffer where you copy the input. That’s two copies of it but only one is your buffer.

Using gdb to show where argv[1] is stored will also show this:

```<code>p argv[1]
$1 = 0x7ffffffee2ce 'A' <repeats 600 times>
</code>```

The address will of course be different on different systems.

Body:
Code:

#include <stdio.h>

    int main(int argc, char *argv[]){
    char buf[512];
    strcpy(buf, argv[1]);
    return 0;
}

Compilation:

gcc -g -z execstack buf.c -o buf -fno-stack-protector

Question:

So Basically using gdb I set a breakpoint on line return 0; and run the script as follow: run $(python -c 'print "A"*600'), and then when I do x/600x $rsp, I get my buffer start at:

0x7fffffffdcf0: 0xffffdfe8      0x00007fff      0xf7fd3298      0x00000002
0x7fffffffdd00: 0x41414141      0x41414141      0x41414141      0x41414141
0x7fffffffdd10: 0x41414141      0x41414141      0x41414141      0x41414141

// it goes on... until
0x7fffffffdf50: 0x41414141      0x41414141      0x00000000      0x00000000

But then when I go further down the stack, I also see:

0x7fffffffe2f0: 0x776f6c66      0x6675622f      0x41414100      0x41414141
0x7fffffffe300: 0x41414141      0x41414141      0x41414141      0x41414141

// It goes until
0x7fffffffe540: 0x41414141      0x41414141      0x41414141      0x41414141
0x7fffffffe550: 0x48530041      0x3d4c4c45      0x6e69622f      0x7361622f

Also for buffer overflow exploit, If I use first location, my exploit doesn't work, but if I use second location it works.

So May I know why is my buffer stored in two different locations?

Body:
Your buffer isn’t stored in two places. You’re just copying the data yourself in your code. There’s the input that’s given to main and then your buffer where you copy the input. That’s two copies of it but only one is your buffer.

Using gdb to show where argv[1] is stored will also show this:

p argv[1]
$1 = 0x7ffffffee2ce 'A' <repeats 600 times>

The address will of course be different on different systems.