问:
Stored procedure expects parameter though parameter is provided
I am using VS 2015 and SQL Server 2016.

In my C# code, I am assigning the parameters which my stored procedure expects, but am getting an error as my stored procedure is expecting a parameter.

My stored procedure:

```<code>CREATE PROCEDURE [dbo].[SDDeleteTAR]
    @TARKey int
AS
BEGIN
    DELETE technical_assistance_requests
    WHERE request_id = @TARKey
END
</code>```

My C# code:

```<code>Label id = (Label)e.Item.FindControl("REQUEST_ID");
var x = id.Text;
int rid = Convert.ToInt32(x);

string cs = ConfigurationManager.AppSettings.Get("connectionString").ToString();

using (SqlConnection con = new SqlConnection(cs))
{
    SqlCommand cmd = new SqlCommand("SDDeleteTAR", con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@RequestID", rid);

    con.Open();
    cmd.ExecuteNonQuery();
}
</code>```

When I run this, I get this error:

Procedure or function 'SDDeleteTAR' expects parameter '@TARKey', which was not supplied.

I am passing the required parameters and executing my command type as CommandType.StoredProcedure, and am not able to resolve this.

I also checked the same issue in StackOverflow here but the submitter is missing the command type declaration.

Any help is appreciated, in pointing out where I am going wrong.

答: You should change @RequestID to @TARKey. Because your stored procedure expects a parameter with that name.

Body:
I am using VS 2015 and SQL Server 2016.

In my C# code, I am assigning the parameters which my stored procedure expects, but am getting an error as my stored procedure is expecting a parameter.

My stored procedure:

CREATE PROCEDURE [dbo].[SDDeleteTAR]
    @TARKey int
AS
BEGIN
    DELETE technical_assistance_requests
    WHERE request_id = @TARKey
END

My C# code:

Label id = (Label)e.Item.FindControl("REQUEST_ID");
var x = id.Text;
int rid = Convert.ToInt32(x);

string cs = ConfigurationManager.AppSettings.Get("connectionString").ToString();

using (SqlConnection con = new SqlConnection(cs))
{
    SqlCommand cmd = new SqlCommand("SDDeleteTAR", con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@RequestID", rid);

    con.Open();
    cmd.ExecuteNonQuery();
}

When I run this, I get this error:

Procedure or function 'SDDeleteTAR' expects parameter '@TARKey', which was not supplied.

I am passing the required parameters and executing my command type as CommandType.StoredProcedure, and am not able to resolve this.

I also checked the same issue in StackOverflow here but the submitter is missing the command type declaration.

Any help is appreciated, in pointing out where I am going wrong.


来源: stackexchange

问:
while loop which executes five times and each time displaying a random digit
I'm trying to create program segment that uses a single while loop which executes its loop body five times, each time displaying a random digit from this set of values. { 1 , 2 , 3 , 4 , 5 , 6 }
The while loop executes only once enter code here

```<code>public static void main(String[] args){
        int num = 0;
        int count = 0;
        while (count < 5)
            count ++;
        num = (int)(Math.random()* 6);

    System.out.println(num);
</code>```

I also tried to do that with arrays.

```<code> public static void main(String[] args){
            int[] num = { 1 , 2 , 3 , 4 , 5 , 6 };
            int count = 0;
            while (count < 5)
                count++;
            num [count] = (int)(Math.random()* 6);
            System.out.println(num);
</code>```

Any tips will be helpful.

答:
You need to put the last two lines inside the while loop

eg:

```<code>int[] num = { 1 , 2 , 3 , 4 , 5 , 6 };
int count = 0;
while (count < 5) {
    count++;
    num = (int)(Math.random()* 6);
    System.out.println(num);
}
</code>```

Another solution would be to use a 'for' loop:

```<code>for(int i = 0; i < 5; i++) {
    num = (int)(Math.random()* 6);
    System.out.println(num);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to create program segment that uses a single while loop which executes its loop body five times, each time displaying a random digit from this set of values. { 1 , 2 , 3 , 4 , 5 , 6 }
The while loop executes only once enter code here

public static void main(String[] args){
        int num = 0;
        int count = 0;
        while (count < 5)
            count ++;
        num = (int)(Math.random()* 6);

    System.out.println(num);

I also tried to do that with arrays.

 public static void main(String[] args){
            int[] num = { 1 , 2 , 3 , 4 , 5 , 6 };
            int count = 0;
            while (count < 5)
                count++;
            num [count] = (int)(Math.random()* 6);
            System.out.println(num);

Any tips will be helpful.

Body:
You need to put the last two lines inside the while loop

eg:

int[] num = { 1 , 2 , 3 , 4 , 5 , 6 };
int count = 0;
while (count < 5) {
    count++;
    num = (int)(Math.random()* 6);
    System.out.println(num);
}

Another solution would be to use a 'for' loop:

for(int i = 0; i < 5; i++) {
    num = (int)(Math.random()* 6);
    System.out.println(num);
}


问:
Youtube Analytics - Creating Requests
I am trying to make a request to the youtube analytics api. and am having some trouble forming the requests so they are accepted. I am using the Google APIs Node.js Client

https://github.com/google/google-api-nodejs-client

and my code is as follows

```<code>import { Meteor } from 'meteor/meteor';
import google from 'googleapis';
import KEY_FILE from './keyFile.json';
import { CHANNEL_ID } from './channelId.js';

//api's
const analytics = google.youtubeAnalytics('v1');

//fetch youtube analytics
export function youtubeAnalytics(start, end){
  //initalise request data
  const startDate = `${start.getFullYear()}-${('0'+(start.getMonth()+1)).slice(-2)}-${('0'+(start.getDate())).slice(-2)}`;
  const endDate = `${end.getFullYear()}-${('0'+(end.getMonth()+1)).slice(-2)}-${('0'+(end.getDate())).slice(-2)}`;
  const scopes = [
    'https://www.googleapis.com/auth/youtube',
    'https://www.googleapis.com/auth/youtube.readonly',
    'https://www.googleapis.com/auth/yt-analytics-monetary.readonly',
    'https://www.googleapis.com/auth/yt-analytics-monetary.readonly'
  ];

  //generate authorisation token
  var AUTH = new google.auth.JWT(
    KEY_FILE.client_email,
    null,
    KEY_FILE.private_key,
    scopes,
    null
   );

  //authorize request
  AUTH.authorize(function (err, tokens) {
    if (err) {
      console.log(err);
      return;
    }

    //create request
    const analyticsRequest = {
      auth: AUTH,
      'start-date': startDate,
      'end-date': endDate,
      ids: `channel==${CHANNEL_ID}`,
      metrics: 'views',
    };

    //make request
    analytics.reports.query(analyticsRequest, function (err, data) {
      if (err) {
        console.error('Error: ' + err);
        return false;
      }
      if (data) {
        console.log(data);
        return data;
      }
    });
  });
  return false;
}

Meteor.methods({youtubeAnalytics});
</code>```

I keep getting the following error

```<code>Error: Error: Invalid query. Query did not conform to the expectations.
</code>```

I think its to do with my request object

```<code>const analyticsRequest = {
  auth: AUTH,
  'start-date': startDate,
  'end-date': endDate,
  ids: `channel==${CHANNEL_ID}`,
  metrics: 'views',
};
</code>```

but all the examples i've found say that this request object should work.  Ive simplified it down as much as i could.  My original request (the one that i actually want) was as follows.

```<code>const analyticsRequest = {
   auth: AUTH,
   'start-date': startDate,
   'end-date': endDate,
   ids: `channel==${CHANNEL_ID}`,
   metrics: 'views',
   dimensions: 'video',
   sort: '-views',
   'max-results': '200'
}
</code>```

after that i need to do another request to get all the associated info on the videos listed which uses a different api endpoint.

```<code>//api's
const youtube = google.youtube('v3');

/*
  do processing of analytics data to create batchRequest
  which is a string of comma separated video ids
*/

videoRequest = {
   auth: AUTH,
   part: 'id,snippet',
   id: batchRequest;
}

youtubeApiData.search.list(videosRequest, function (err, data) {
   if (err) {
      console.error('Error: ' + err);
      return false;
   }
   if (data) {
      console.log(data);
      return data;
   }
});
</code>```

So In Summary

I need to do a request to various google api's and am having trouble forming the request so they are accepted (I have not got past the first request from youtube analytics).

can someone point me in the right direction?

答:
Figured it out.  Cant do a Service account request for this API.  I setup account verification through accounts-google

https://guide.meteor.com/accounts.html

merging it on the base account using accounts meld

https://atmospherejs.com/splendido/accounts-meld

which gives me a access token attached to the user then did a OAuth 2.0 call instead.  Did something similar for facebook as well.

One problem that i am still having is that the 'fetch retention for videos' section is super inefficient.  its making one call per video.  There is batch requests available for the google api but i cant seem to find a proper example using the 'googleapis' package.  if anyone has an example that would be much appreciated.

here is the new code.

```<code>import { Meteor } from 'meteor/meteor';
import google from 'googleapis';
import { CHANNEL_ID, USER_ID, KEY_FILE, API_KEY, CLIENT_ID, CLIENT_SECRET } from './keys.js';

//api's
const fetchAnalytics = google.youtubeAnalytics('v1');
const fetchYoutube = google.youtube('v3');
const OAuth2 = google.auth.OAuth2;

export function youtubeAnalytics(start, end){
  //requires login to generate authorisation
  const user = Meteor.user();
  if(user && user.services && user.services.google && user.services.google.accessToken){
    //-------------------- general setup -------------------- //

    //convert async functions to sync functions
    const fetchYoutubeSync = Meteor.wrapAsync(fetchYoutube.search.list);
    const fetchAnalyticsSync = Meteor.wrapAsync(fetchAnalytics.reports.query);

    // set up default values
    const analytics = {views: [], retention: []};
    const videos = [];

    const startDate = `${start.getFullYear()}-${('0'+(start.getMonth()+1)).slice(-2)}-${('0'+(start.getDate())).slice(-2)}`;
    const endDate = `${end.getFullYear()}-${('0'+(end.getMonth()+1)).slice(-2)}-${('0'+(end.getDate())).slice(-2)}`;
    const startDateLong = `${start.getFullYear()}-${('0'+(start.getMonth()+1)).slice(-2)}-${('0'+(start.getDate())).slice(-2)}T00:00:00.0+00:00`;
    const endDateLong = `${end.getFullYear()}-${('0'+(end.getMonth()+1)).slice(-2)}-${('0'+(end.getDate())).slice(-2)}T00:00:00.0+00:00`;

    // generate authorisation tokens
    const oauth2Client = new OAuth2(CLIENT_ID, CLIENT_SECRET,'');
    oauth2Client.setCredentials({access_token: user.services.google.accessToken});
    google.options({
      auth: oauth2Client
    });

    //-------------------- fetch videos between dates -------------------- //

    let fetch = true;
    let next = '';
    while (fetch) {
      //create video request
      let videosRequest = {
        auth: oauth2Client,
        part: 'id,snippet',
        type: 'video',
        channelId: CHANNEL_ID,
        publishedAfter: startDateLong,
        publishedBefore: endDateLong,
        maxResults: 50,
        pageToken: next,
      }
      //make video request
      let response = fetchYoutubeSync(videosRequest);
      //store video request
      videos.push.apply(videos, response.items);
      //check if more data is available
      if(response.nextPageToken){ next = response.nextPageToken; }
      else{ fetch = false;}
    }

    //-------------------- create batch request objects -------------------- //
    if(videos.length > 0){
      //process videos
      let batchRequestViews = '';
      let batchRequestRetention = [];
      let first = true;
      for(let i = 0; i < videos.length; i += 1){
        let id = false;
        if(videos[i].id.kind === 'youtube#video'){ id = videos[i].id.videoId;}
        if(id){
          //views processing
          if(first){ first = false; batchRequestViews = id;}
          else{ batchRequestViews = `${batchRequestViews},${id}`}
          //retention processing
          let request = {
            auth: oauth2Client,
            'start-date': startDate,
            'end-date': endDate,
            ids: `channel==${CHANNEL_ID}`,
            metrics: 'audienceWatchRatio',
            dimensions: 'elapsedVideoTimeRatio',
            filters: `video==${id}`
          };
          batchRequestRetention.push(request);
        }
      }

      //-------------------- fetch views for videos  -------------------- //

      // create views request
      const analyticsRequestViews = {
        auth: oauth2Client,
        'start-date': startDate,
        'end-date': endDate,
        ids: `channel==${CHANNEL_ID}`,
        metrics: 'views',
        dimensions: 'video',
        filters: `video==${batchRequestViews}`
      };
      // make and store views request
      analytics.views = fetchAnalyticsSync(analyticsRequestViews).rows;

      //-------------------- fetch retention for videos  -------------------- //

      //make retention batch request
      if(batchRequestRetention && batchRequestRetention.length > 0){
        for(let i = 0; i < batchRequestRetention.length; i += 1){
          //fetch retention request
          let request = batchRequestRetention[i];
          //make retention request
          let response = fetchAnalyticsSync(request);
          //store response
          analytics.retention.push({id: request.filters.substring(7), response});
        }
      }

      //-------------------- return results  -------------------- //
      return {videos, analytics};
    }
  }
  return false;
}

Meteor.methods({youtubeAnalytics});
</code>```

Title: Youtube Analytics - Creating Requests

Body:
I am trying to make a request to the youtube analytics api. and am having some trouble forming the requests so they are accepted. I am using the Google APIs Node.js Client

https://github.com/google/google-api-nodejs-client

and my code is as follows

import { Meteor } from 'meteor/meteor';
import google from 'googleapis';
import KEY_FILE from './keyFile.json';
import { CHANNEL_ID } from './channelId.js';

//api's
const analytics = google.youtubeAnalytics('v1');

//fetch youtube analytics
export function youtubeAnalytics(start, end){
  //initalise request data
  const startDate = `${start.getFullYear()}-${('0'+(start.getMonth()+1)).slice(-2)}-${('0'+(start.getDate())).slice(-2)}`;
  const endDate = `${end.getFullYear()}-${('0'+(end.getMonth()+1)).slice(-2)}-${('0'+(end.getDate())).slice(-2)}`;
  const scopes = [
    'https://www.googleapis.com/auth/youtube',
    'https://www.googleapis.com/auth/youtube.readonly',
    'https://www.googleapis.com/auth/yt-analytics-monetary.readonly',
    'https://www.googleapis.com/auth/yt-analytics-monetary.readonly'
  ];

  //generate authorisation token
  var AUTH = new google.auth.JWT(
    KEY_FILE.client_email,
    null,
    KEY_FILE.private_key,
    scopes,
    null
   );

  //authorize request
  AUTH.authorize(function (err, tokens) {
    if (err) {
      console.log(err);
      return;
    }

    //create request
    const analyticsRequest = {
      auth: AUTH,
      'start-date': startDate,
      'end-date': endDate,
      ids: `channel==${CHANNEL_ID}`,
      metrics: 'views',
    };

    //make request
    analytics.reports.query(analyticsRequest, function (err, data) {
      if (err) {
        console.error('Error: ' + err);
        return false;
      }
      if (data) {
        console.log(data);
        return data;
      }
    });
  });
  return false;
}

Meteor.methods({youtubeAnalytics});

I keep getting the following error

Error: Error: Invalid query. Query did not conform to the expectations.

I think its to do with my request object

const analyticsRequest = {
  auth: AUTH,
  'start-date': startDate,
  'end-date': endDate,
  ids: `channel==${CHANNEL_ID}`,
  metrics: 'views',
};

but all the examples i've found say that this request object should work.  Ive simplified it down as much as i could.  My original request (the one that i actually want) was as follows.

const analyticsRequest = {
   auth: AUTH,
   'start-date': startDate,
   'end-date': endDate,
   ids: `channel==${CHANNEL_ID}`,
   metrics: 'views',
   dimensions: 'video',
   sort: '-views',
   'max-results': '200'
}

after that i need to do another request to get all the associated info on the videos listed which uses a different api endpoint.

//api's
const youtube = google.youtube('v3');

/*
  do processing of analytics data to create batchRequest
  which is a string of comma separated video ids
*/

videoRequest = {
   auth: AUTH,
   part: 'id,snippet',
   id: batchRequest;
}

youtubeApiData.search.list(videosRequest, function (err, data) {
   if (err) {
      console.error('Error: ' + err);
      return false;
   }
   if (data) {
      console.log(data);
      return data;
   }
});

So In Summary

I need to do a request to various google api's and am having trouble forming the request so they are accepted (I have not got past the first request from youtube analytics).

can someone point me in the right direction?

Body:
Figured it out.  Cant do a Service account request for this API.  I setup account verification through accounts-google

https://guide.meteor.com/accounts.html

merging it on the base account using accounts meld

https://atmospherejs.com/splendido/accounts-meld

which gives me a access token attached to the user then did a OAuth 2.0 call instead.  Did something similar for facebook as well.

One problem that i am still having is that the 'fetch retention for videos' section is super inefficient.  its making one call per video.  There is batch requests available for the google api but i cant seem to find a proper example using the 'googleapis' package.  if anyone has an example that would be much appreciated.

here is the new code.

import { Meteor } from 'meteor/meteor';
import google from 'googleapis';
import { CHANNEL_ID, USER_ID, KEY_FILE, API_KEY, CLIENT_ID, CLIENT_SECRET } from './keys.js';

//api's
const fetchAnalytics = google.youtubeAnalytics('v1');
const fetchYoutube = google.youtube('v3');
const OAuth2 = google.auth.OAuth2;

export function youtubeAnalytics(start, end){
  //requires login to generate authorisation
  const user = Meteor.user();
  if(user && user.services && user.services.google && user.services.google.accessToken){
    //-------------------- general setup -------------------- //

    //convert async functions to sync functions
    const fetchYoutubeSync = Meteor.wrapAsync(fetchYoutube.search.list);
    const fetchAnalyticsSync = Meteor.wrapAsync(fetchAnalytics.reports.query);

    // set up default values
    const analytics = {views: [], retention: []};
    const videos = [];

    const startDate = `${start.getFullYear()}-${('0'+(start.getMonth()+1)).slice(-2)}-${('0'+(start.getDate())).slice(-2)}`;
    const endDate = `${end.getFullYear()}-${('0'+(end.getMonth()+1)).slice(-2)}-${('0'+(end.getDate())).slice(-2)}`;
    const startDateLong = `${start.getFullYear()}-${('0'+(start.getMonth()+1)).slice(-2)}-${('0'+(start.getDate())).slice(-2)}T00:00:00.0+00:00`;
    const endDateLong = `${end.getFullYear()}-${('0'+(end.getMonth()+1)).slice(-2)}-${('0'+(end.getDate())).slice(-2)}T00:00:00.0+00:00`;

    // generate authorisation tokens
    const oauth2Client = new OAuth2(CLIENT_ID, CLIENT_SECRET,'');
    oauth2Client.setCredentials({access_token: user.services.google.accessToken});
    google.options({
      auth: oauth2Client
    });

    //-------------------- fetch videos between dates -------------------- //

    let fetch = true;
    let next = '';
    while (fetch) {
      //create video request
      let videosRequest = {
        auth: oauth2Client,
        part: 'id,snippet',
        type: 'video',
        channelId: CHANNEL_ID,
        publishedAfter: startDateLong,
        publishedBefore: endDateLong,
        maxResults: 50,
        pageToken: next,
      }
      //make video request
      let response = fetchYoutubeSync(videosRequest);
      //store video request
      videos.push.apply(videos, response.items);
      //check if more data is available
      if(response.nextPageToken){ next = response.nextPageToken; }
      else{ fetch = false;}
    }

    //-------------------- create batch request objects -------------------- //
    if(videos.length > 0){
      //process videos
      let batchRequestViews = '';
      let batchRequestRetention = [];
      let first = true;
      for(let i = 0; i < videos.length; i += 1){
        let id = false;
        if(videos[i].id.kind === 'youtube#video'){ id = videos[i].id.videoId;}
        if(id){
          //views processing
          if(first){ first = false; batchRequestViews = id;}
          else{ batchRequestViews = `${batchRequestViews},${id}`}
          //retention processing
          let request = {
            auth: oauth2Client,
            'start-date': startDate,
            'end-date': endDate,
            ids: `channel==${CHANNEL_ID}`,
            metrics: 'audienceWatchRatio',
            dimensions: 'elapsedVideoTimeRatio',
            filters: `video==${id}`
          };
          batchRequestRetention.push(request);
        }
      }

      //-------------------- fetch views for videos  -------------------- //

      // create views request
      const analyticsRequestViews = {
        auth: oauth2Client,
        'start-date': startDate,
        'end-date': endDate,
        ids: `channel==${CHANNEL_ID}`,
        metrics: 'views',
        dimensions: 'video',
        filters: `video==${batchRequestViews}`
      };
      // make and store views request
      analytics.views = fetchAnalyticsSync(analyticsRequestViews).rows;

      //-------------------- fetch retention for videos  -------------------- //

      //make retention batch request
      if(batchRequestRetention && batchRequestRetention.length > 0){
        for(let i = 0; i < batchRequestRetention.length; i += 1){
          //fetch retention request
          let request = batchRequestRetention[i];
          //make retention request
          let response = fetchAnalyticsSync(request);
          //store response
          analytics.retention.push({id: request.filters.substring(7), response});
        }
      }

      //-------------------- return results  -------------------- //
      return {videos, analytics};
    }
  }
  return false;
}

Meteor.methods({youtubeAnalytics});


问:
Excel VLOOKUP referencing a range
I'm using Microsoft Excel 2013.
I've been given these tables of postcode ranges, and associated zone number, as follows:

and I want to separate the postcodes, so it looks like this:

I've tried VLOOKUP, but it doesn't quite do what I want... as it looks uses the first column as a reference, and this doesn't seem changable.

Thanks in advance!

答:
With the gaps in the post codes, you'll need to construct the list of postcodes carefully, to include only those that are actually in a valid range. Then you can use a Vlookup with TRUE as the fourth parameter.

```<code>=VLOOKUP(E2,A:C,3,TRUE)
</code>```

According to your screenshot, there is no postcode with numbers 300 to 799, so you can't have 300 in the list. It will return a zone because Vlookup with the TRUE parameter returns the result for the next smallest match if no exact match is found. In the case of the missing post codes that would be a wrong result, right? So, don't use the numbers that are not valid post codes. Also note that the data must be sorted ascending by the values in the first column.

Edit: If you want to use all numbers from 0 to the end and run a formula, you need to check first if a number exists in a given range. So you could do something like this:

```<code>=IF(E2<=INDEX(B:B,MATCH(E2,A:A,1)),VLOOKUP(E2,A:C,3,1),"not in range")
</code>```

You should not start your list with 0, though, but with your smallest post code. Otherwise the formula will need to get even more complicated.

Title: Excel VLOOKUP referencing a range

Body:
With the gaps in the post codes, you'll need to construct the list of postcodes carefully, to include only those that are actually in a valid range. Then you can use a Vlookup with TRUE as the fourth parameter.

=VLOOKUP(E2,A:C,3,TRUE)

According to your screenshot, there is no postcode with numbers 300 to 799, so you can't have 300 in the list. It will return a zone because Vlookup with the TRUE parameter returns the result for the next smallest match if no exact match is found. In the case of the missing post codes that would be a wrong result, right? So, don't use the numbers that are not valid post codes. Also note that the data must be sorted ascending by the values in the first column.

Edit: If you want to use all numbers from 0 to the end and run a formula, you need to check first if a number exists in a given range. So you could do something like this:

=IF(E2<=INDEX(B:B,MATCH(E2,A:A,1)),VLOOKUP(E2,A:C,3,1),"not in range")

You should not start your list with 0, though, but with your smallest post code. Otherwise the formula will need to get even more complicated.


问:
Help refactor this messed-up-nested-if of a method
Ok I want some opinions how I can fix this mess of a method!

It has WAY to many nested 'if' statements.

But realize I have to know exactly where the method fails, currently in each of the respective 'else' clause I am logging the error (the failed 'if' condition').

Note: ignore any logic behind the things, please focus on the style and structure as I have made all the function names up etc.

Here is the skeleton structure:

```<code>   public void MyMethod()
{

   try
   {
    bool tryAgain = false;

    string filename = DownloadFile();

    if( IsFileFormatOk(filename) )
    {

        blah = GetBlah(filename);

        if(blah.ID > 0)
        {

            if(ImportFile(filename)
            {

                string username = GetUserFromFile(filename);

                if(isValidUser(username))
                {

                    // few more levels to go
                    //
                    //
                    //

                }
                else
                {
                    LogError(filename, ...); // specific to this if statement
                    tryAgain = true;
                }

            }
            else
            {

                LogError(filename, ...); // specific to this if statement
                tryAgain = true;
            }

        }
        else
        {
            LogError(filename, ...); // specific to this if statement
            tryAgain = true;
        }

    }
    else
    {
        LogError(filename, ...); // specific to this if statement
        tryAgain = true;
    }

   }
   catch
   {
   }
   finally
   {
    if(tryAgain)
    {
        // blah
    }
   }

}
</code>```

答:
For these kind of questions, http://refactormycode.com/ is very useful.

Although the SO people are really committed to refactoring some code, too. ;)

OwnerDisplayName: Blankman

ContentLicense: CC BY-SA 2.5

Body:
Ok I want some opinions how I can fix this mess of a method!

It has WAY to many nested 'if' statements.

But realize I have to know exactly where the method fails, currently in each of the respective 'else' clause I am logging the error (the failed 'if' condition').

Note: ignore any logic behind the things, please focus on the style and structure as I have made all the function names up etc.

Here is the skeleton structure:

   public void MyMethod()
{

   try
   {
    bool tryAgain = false;

    string filename = DownloadFile();

    if( IsFileFormatOk(filename) )
    {

        blah = GetBlah(filename);

        if(blah.ID > 0)
        {

            if(ImportFile(filename)
            {

                string username = GetUserFromFile(filename);

                if(isValidUser(username))
                {

                    // few more levels to go
                    //
                    //
                    //

                }
                else
                {
                    LogError(filename, ...); // specific to this if statement
                    tryAgain = true;
                }

            }
            else
            {

                LogError(filename, ...); // specific to this if statement
                tryAgain = true;
            }

        }
        else
        {
            LogError(filename, ...); // specific to this if statement
            tryAgain = true;
        }

    }
    else
    {
        LogError(filename, ...); // specific to this if statement
        tryAgain = true;
    }

   }
   catch
   {
   }
   finally
   {
    if(tryAgain)
    {
        // blah
    }
   }

}

LastEditorDisplayName: Blankman

OwnerDisplayName: blindgaenger


问:
Android MapView Draw Button on POI click
How can i do that? </p>

<p>When i click on a POI, i want to draw a button in the bottom of my mapview, with a setonclicklistener. </p>

答: The best way is to already have a button added to your layout and have the button not visible. Then when the user clicks on the POI you should show the button.</p>

Body:
How can i do that?

When i click on a POI, i want to draw a button in the bottom of my mapview, with a setonclicklistener.


问:
fit controls to screen vba
i'm trying to fit the user form to screen on diifernet screens.

the userform was first managed in my work screen and i fit it to my screen but  when i'm trying the userform on other screens part of it vanished.

i can't put the whole code in here but i will put just the sub that suppose to fit to screen:

```<code>Private Sub UserForm_Initialize()
Dim w As Long, h As Long
Application.Visible = False

With Me
        rMaxHeight = Application.Height
        rMaxWidth = Application.Width
        If .Height > Application.Height - 10 Then
        rNormalHeight = rMaxHeight * 0.85
        Else
        rNormalHeight = Me.Height
        End If
        If .Width > Application.Width - 10 Then
        rNormalWidth = rMaxWidth * 0.85
        Else
        rNormalWidth = Me.Width
        End If

        .StartUpPosition = 1
        .Left = 0
        .Top = 0
         FitSize
...

Private Sub FitSize()
Dim h, w
Dim c As Control
Dim PHeight, PWidth As Double

PHeight = rNormalHeight / Me.Height
PWidth = rNormalWidth / Me.Width
h = 0: w = 0

If PHeight = 1 And PWidth = 1 Then Exit Sub

    For Each c In Me.Controls
        If c.Visible Then
            If c.Top + c.Height > h Then h = (c.Top + c.Height) ' * PHeight

            If c.Left + c.Width > w Then w = (c.Left + c.Width) ' * PWidth

            If Not TypeName(c) = "Image" Or TypeName(c) = "ListBox" Then   c.FontSize = c.FontSize * ((PHeight + PWidth) / 2)
        End If
    Next c

    If h > 0 And w > 0 Then
        With Me
            .Width = w + 40
            .Height = h + 40
        End With
    End If
End Sub
</code>```

hope you could help me with that

Thank you all
sefi

答:
You can either Re-position every single control in the UserForm with VBA or simply enable ScrollBars for the UserForm object so they can access all the elements with a bit of scrolling.

Change the ScrollBars property of the UserForm to like 3 - fmScrollBarsBoth as the default is 0 - fmScrollBarsNone

Then you need to figure out how tall and wide it needs to be:

ScrollHeight

ScrollWidth

Title: fit controls to screen vba

Body:
i'm trying to fit the user form to screen on diifernet screens.

the userform was first managed in my work screen and i fit it to my screen but  when i'm trying the userform on other screens part of it vanished.

i can't put the whole code in here but i will put just the sub that suppose to fit to screen:

Private Sub UserForm_Initialize()
Dim w As Long, h As Long
Application.Visible = False

With Me
        rMaxHeight = Application.Height
        rMaxWidth = Application.Width
        If .Height > Application.Height - 10 Then
        rNormalHeight = rMaxHeight * 0.85
        Else
        rNormalHeight = Me.Height
        End If
        If .Width > Application.Width - 10 Then
        rNormalWidth = rMaxWidth * 0.85
        Else
        rNormalWidth = Me.Width
        End If

        .StartUpPosition = 1
        .Left = 0
        .Top = 0
         FitSize
...

Private Sub FitSize()
Dim h, w
Dim c As Control
Dim PHeight, PWidth As Double

PHeight = rNormalHeight / Me.Height
PWidth = rNormalWidth / Me.Width
h = 0: w = 0

If PHeight = 1 And PWidth = 1 Then Exit Sub

    For Each c In Me.Controls
        If c.Visible Then
            If c.Top + c.Height > h Then h = (c.Top + c.Height) ' * PHeight

            If c.Left + c.Width > w Then w = (c.Left + c.Width) ' * PWidth

            If Not TypeName(c) = "Image" Or TypeName(c) = "ListBox" Then   c.FontSize = c.FontSize * ((PHeight + PWidth) / 2)
        End If
    Next c

    If h > 0 And w > 0 Then
        With Me
            .Width = w + 40
            .Height = h + 40
        End With
    End If
End Sub

hope you could help me with that

Thank you all
sefi


问:
using php to get a json feed
I'm trying to use php to get an external json feed to use within my site, I've tried using get_file_contents and also CURL. But both are returning the same thing.

```<code>�~�X�ݘ]O�0��'��\�fԳ�o�JK7>�h�!M ��l�S�d�B���iKHC�Pi�M���W��G>���I�YD��G��F���,F��O��3a7�E�C��GC���MB������Q�&�׿���O���ك+��tzf�c�/ ���<-���"1�!(۩�[F��w�m��a�8t}*�y��fBr�O;�{cۉ�s�B��~���l�� ��v��@^&��@���,ӊ#ԙ��/MO����$ǈ��%,]�9Js��z�[I�<8w6�%���Ջ�b�y�;ӄ�f"UM�!�ipC�) �|���~����}p���w�R�7D�eޑ��Oΐ��LS�5��.�{[j�� 3|D�h�FB'b��=���G~H.�}D����� �4�ՇpGA;� VMl��<�|�,6�R,N}J�ߘ��d�x�a��.�O܊���Z���j�x����W燭���n��+<Ό�* �4 _N|�}�5�a��Aմ�����p��1V]��j����hxA<7,I. &Ϭ2�~y�LD�+6��z�QLQ�9T��A��V�5���L&�,�JǊfi��q5J��� +P��:�<�:���Q⋊ �[*0�Z(Q E��K�u��Ҍ�[�d�W��� �2&�˒���+�R�|�\"n6]_ �����z���(���������b3%,�T��r��U@��Z-�[��]լ(�k6S֚N��-;�{E��?�VET4`���V ��1�c���%�XJ�[L�0����ė��`$S�n�d\�\�k}�Z�G��B7 �^4J��k���?���W;
</code>```

If I add json_decode, it echoes out nothing at all.

Here's the code I'm using:

```<code>        $apistr = 'https://remitradar.com/JsonRequests.aspx?action=getOnlineQuotes&companyKey=23e9b66aspp6z&countryFrom=AU&countryTo=FJ&currencyFrom=AUD&currencyTo=FJD&amount=200';

        #get file contents
        $json = file_get_contents($apistr);
        echo '```';print_r($json);echo '```';

        #curl 1
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$apistr);
        curl_setopt($ch,CURLOPT_BINARYTRANSFER,true);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        $jsonData = json_decode(curl_exec($ch));
        curl_close($ch);
        echo '```CURL 1';print_r($jsonData);echo '```';

        #curl 2
        $ch = curl_init($apistr);
        curl_setopt($ch,CURLOPT_MUTE,1);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-Type:text/xml'));
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        $output = json_decode(curl_exec($ch));
        curl_close($ch);
        echo '```CURL 2';print_r($output);echo '```';
</code>```

I'm not sure if the problem is on my end, or their end. But going to the URL directly works fine.

答:
Their server uses gzip compression
You must handle this

```<code>    #curl 1
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$apistr);
    //curl_setopt($ch,CURLOPT_BINARYTRANSFER,true);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_ENCODING , "gzip");  // handle gzip

    $data = curl_exec($ch);
    $data = json_decode($data);
    curl_close($ch);
    echo '```CURL 1';print_r($data);echo '```';
</code>```

Title: using php to get a json feed

Body:
I'm trying to use php to get an external json feed to use within my site, I've tried using get_file_contents and also CURL. But both are returning the same thing.

�~�X�ݘ]O�0��'��\�fԳ�o�JK7>�h�!M ��l�S�d�B���iKHC�Pi�M���W��G>���I�YD��G��F���,F��O��3a7�E�C��GC���MB������Q�&�׿���O���ك+��tzf�c�/ ���<-���"1�!(۩�[F��w�m��a�8t}*�y��fBr�O;�{cۉ�s�B��~���l�� ��v��@^&��@���,ӊ#ԙ��/MO����$ǈ��%,]�9Js��z�[I�<8w6�%���Ջ�b�y�;ӄ�f"UM�!�ipC�) �|���~����}p���w�R�7D�eޑ��Oΐ��LS�5��.�{[j�� 3|D�h�FB'b��=���G~H.�}D����� �4�ՇpGA;� VMl��<�|�,6�R,N}J�ߘ��d�x�a��.�O܊���Z���j�x����W燭���n��+<Ό�* �4 _N|�}�5�a��Aմ�����p��1V]��j����hxA<7,I. &Ϭ2�~y�LD�+6��z�QLQ�9T��A��V�5���L&�,�JǊfi��q5J��� +P��:�<�:���Q⋊ �[*0�Z(Q E��K�u��Ҍ�[�d�W��� �2&�˒���+�R�|�\"n6]_ �����z���(���������b3%,�T��r��U@��Z-�[��]լ(�k6S֚N��-;�{E��?�VET4`���V ��1�c���%�XJ�[L�0����ė��`$S�n�d\�\�k}�Z�G��B7 �^4J��k���?���W;

If I add json_decode, it echoes out nothing at all.

Here's the code I'm using:

        $apistr = 'https://remitradar.com/JsonRequests.aspx?action=getOnlineQuotes&companyKey=23e9b66aspp6z&countryFrom=AU&countryTo=FJ&currencyFrom=AUD&currencyTo=FJD&amount=200';

        #get file contents
        $json = file_get_contents($apistr);
        echo '
';print_r($json);echo '
';

        #curl 1
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$apistr);
        curl_setopt($ch,CURLOPT_BINARYTRANSFER,true);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        $jsonData = json_decode(curl_exec($ch));
        curl_close($ch);
        echo '
CURL 1';print_r($jsonData);echo '
';

        #curl 2
        $ch = curl_init($apistr);
        curl_setopt($ch,CURLOPT_MUTE,1);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-Type:text/xml'));
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        $output = json_decode(curl_exec($ch));
        curl_close($ch);
        echo '
CURL 2';print_r($output);echo '
';

I'm not sure if the problem is on my end, or their end. But going to the URL directly works fine.

Body:
Their server uses gzip compression
You must handle this

    #curl 1
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$apistr);
    //curl_setopt($ch,CURLOPT_BINARYTRANSFER,true);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_ENCODING , "gzip");  // handle gzip

    $data = curl_exec($ch);
    $data = json_decode($data);
    curl_close($ch);
    echo '<pre>CURL 1';print_r($data);echo '</pre>';


问:
C function call with struct array
So I'm trying to do some practice in C by trying to create a dynamic array of structs, but I'm running into some difficulty when trying to pass the struct into different functions for different operations.

My code so far:

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

struct node {
char *str;
int len;
};
//& gives address of value, * gives value at address
int main(void) {
    struct node **strarray = NULL;
    int count = 0, i = 0;

    printf("hello\n");
    strarray = (struct node **)realloc(strarray, (count + 1) * sizeof(struct node *));

    /* allocate memory for one `struct node` */
    strarray[count] = (struct node *)malloc(sizeof(struct node));

    strarray = init(strarray);
    return 0;
}

struct node ** init(struct node ** strarray){ //this is the line that's causing problems

    int i = 0, count = 0;
    char line[1024];

    if(fgets(line, 1024, stdin) != NULL) {
        /* add ONE element to the array */
        strarray = (struct node **)realloc(strarray, (count + 1) * sizeof(struct node *));

        /* allocate memory for one `struct node` */
        strarray[count] = (struct node *)malloc(sizeof(struct node));

        /* copy the data into the new element (structure) */
        strarray[count]->str = strdup(line);
        strarray[count]->len = strlen(line);
        count++;
        return **strarray;
    }

}
void printarray(){
    for(i = 0; i < count; i++) {
        printf("--\n");
        printf("[%d]->str: %s", i, strarray[i]->str);
        printf("[%d]->len: %d\n", i, strarray[i]->len);
    }
}
</code>```

I haven't worked on the printarray method yet, I'm trying to get the function declaration and the pass to work. Currently, I'm getting a conflicting types for ‘init’
struct node** init(struct node** strarray)
error which I have tried many fixes to, but no avail.

答:
You're problem is that you're derefenrecing the variable you're returning.
Do

```<code>return strarray
</code>```

Instead of

```<code>return **strarray
</code>```

Here is the whole function:

```<code>struct node ** init(struct node ** strarray){

int i = 0, count = 0;
char line[1024];

if(fgets(line, 1024, stdin) != NULL) {
    /* add ONE element to the array */
    strarray = (struct node **)realloc(strarray, (count + 1) * sizeof(struct node *));

    /* allocate memory for one `struct node` */
    strarray[count] = (struct node *)malloc(sizeof(struct node));

    /* copy the data into the new element (structure) */
    strarray[count]->str = strdup(line);
    strarray[count]->len = strlen(line);
    count++;
    return strarray;
}
}
</code>```

Title: C function call with struct array

Body:
So I'm trying to do some practice in C by trying to create a dynamic array of structs, but I'm running into some difficulty when trying to pass the struct into different functions for different operations.

My code so far:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct node {
char *str;
int len;
};
//& gives address of value, * gives value at address
int main(void) {
    struct node **strarray = NULL;
    int count = 0, i = 0;

    printf("hello\n");
    strarray = (struct node **)realloc(strarray, (count + 1) * sizeof(struct node *));

    /* allocate memory for one `struct node` */
    strarray[count] = (struct node *)malloc(sizeof(struct node));

    strarray = init(strarray);
    return 0;
}

struct node ** init(struct node ** strarray){ //this is the line that's causing problems

    int i = 0, count = 0;
    char line[1024];

    if(fgets(line, 1024, stdin) != NULL) {
        /* add ONE element to the array */
        strarray = (struct node **)realloc(strarray, (count + 1) * sizeof(struct node *));

        /* allocate memory for one `struct node` */
        strarray[count] = (struct node *)malloc(sizeof(struct node));

        /* copy the data into the new element (structure) */
        strarray[count]->str = strdup(line);
        strarray[count]->len = strlen(line);
        count++;
        return **strarray;
    }

}
void printarray(){
    for(i = 0; i < count; i++) {
        printf("--\n");
        printf("[%d]->str: %s", i, strarray[i]->str);
        printf("[%d]->len: %d\n", i, strarray[i]->len);
    }
}

I haven't worked on the printarray method yet, I'm trying to get the function declaration and the pass to work. Currently, I'm getting a conflicting types for ‘init’
struct node** init(struct node** strarray)
error which I have tried many fixes to, but no avail.

Body:
You're problem is that you're derefenrecing the variable you're returning.
Do

return strarray

Instead of

return **strarray

Here is the whole function:

struct node ** init(struct node ** strarray){

int i = 0, count = 0;
char line[1024];

if(fgets(line, 1024, stdin) != NULL) {
    /* add ONE element to the array */
    strarray = (struct node **)realloc(strarray, (count + 1) * sizeof(struct node *));

    /* allocate memory for one `struct node` */
    strarray[count] = (struct node *)malloc(sizeof(struct node));

    /* copy the data into the new element (structure) */
    strarray[count]->str = strdup(line);
    strarray[count]->len = strlen(line);
    count++;
    return strarray;
}
}


问:
Resolve JSON field types dynamically using Gson
I have the following API response:

```<code>{
   "data":{
      "categoryFields":[
         {
            "name":"brand",
            "label":"Marca",
            "values":[
               {
                  "key":53,
                  "value":"Alfa Romeo"
               },
               {
                  "key":55,
                  "value":"Audi"
               }
            ]
         },
         {
            "name":"year",
            "label":"Año", ,
            "dataType":"select",
            "values":[
               {
                  "key":2017,
                  "value":2017
               },
               {
                  "key":2016,
                  "value":2016
               }
            ]
         },

      ]
   }
}
</code>```

Ok, in the first categoryField the values are:

```<code>"key":53 INT,
"value":"Alfa Romeo", STRING
</code>```

In the second categoryField the values are:

```<code> "key":2017, INT
 "value":2017, INT
</code>```

Also there's another type:

```<code> "key":"string", STRING
 "value":"String", STRING
</code>```

I need a class that can handle those types of data. Something like:

public class Value {

    @SerializedName("key")
    @Expose
    private DYNAMIC_TYPE key;

    @SerializedName("value")
    @Expose
    private DYNAMIC_TYPE value;

}
```

How can I do that? Or there's a Gson function to help me with that?

答:
solution </p>

```<code>public class CategoryValueDeserializer implements JsonDeserializer<CategoryValue> {
    @Override
    public CategoryValue deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

        final JsonObject jsonObject = json.getAsJsonObject();

        final JsonElement jsonKey = jsonObject.get("key");
        final String key = jsonKey.getAsString();

        final JsonElement jsonValue = jsonObject.get("value");
        final String value = jsonValue.getAsString();

        CategoryValue categoryValue = new CategoryValue();
        categoryValue.setKey(key);
        categoryValue.setValue(value);

        return categoryValue;

    }
}
</code>```

<p>//retrofit </p>

```<code> final Gson gson = new GsonBuilder()
                .registerTypeAdapter(Response.class, new CategoryValueDeserializer())
                .create();

        Retrofit.Builder builder = new Retrofit.Builder()
                .baseUrl(END_POINT)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create());
</code>```

Body:
I have the following API response:

{
   "data":{
      "categoryFields":[
         {
            "name":"brand",
            "label":"Marca",
            "values":[
               {
                  "key":53,
                  "value":"Alfa Romeo"
               },
               {
                  "key":55,
                  "value":"Audi"
               }
            ]
         },
         {
            "name":"year",
            "label":"Año", ,
            "dataType":"select",
            "values":[
               {
                  "key":2017,
                  "value":2017
               },
               {
                  "key":2016,
                  "value":2016
               }
            ]
         },

      ]
   }
}

Ok, in the first categoryField the values are:

"key":53 INT,
"value":"Alfa Romeo", STRING

In the second categoryField the values are:

 "key":2017, INT
 "value":2017, INT

Also there's another type:

 "key":"string", STRING
 "value":"String", STRING

I need a class that can handle those types of data. Something like:

public class Value {

    @SerializedName("key")
    @Expose
    private DYNAMIC_TYPE key;

    @SerializedName("value")
    @Expose
    private DYNAMIC_TYPE value;

}

How can I do that? Or there's a Gson function to help me with that?

Body:
solution

public class CategoryValueDeserializer implements JsonDeserializer<CategoryValue> {
    @Override
    public CategoryValue deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

        final JsonObject jsonObject = json.getAsJsonObject();

        final JsonElement jsonKey = jsonObject.get("key");
        final String key = jsonKey.getAsString();

        final JsonElement jsonValue = jsonObject.get("value");
        final String value = jsonValue.getAsString();

        CategoryValue categoryValue = new CategoryValue();
        categoryValue.setKey(key);
        categoryValue.setValue(value);

        return categoryValue;

    }
}

//retrofit

 final Gson gson = new GsonBuilder()
                .registerTypeAdapter(Response.class, new CategoryValueDeserializer())
                .create();

        Retrofit.Builder builder = new Retrofit.Builder()
                .baseUrl(END_POINT)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create());


问:
Troubleshooting Amazon's Alexa Skill Kit (ASK) Lambda interaction
I'm starting with ASK development. I'm a little confused by some behavior and I would like to know how to debug errors from the "service simulator" console. How can I get more information on the The remote endpoint could not be called, or the response it returned was invalid. errors?

Here's my situation:

I have a skill and three Lambda functions (ARN:A, ARN:B, ARN:C). If I set the skill's endpoint to ARN:A and try to test it from the skill's service simulator, I get an error response: The remote endpoint could not be called, or the response it returned was invalid.
I copy the lambda request, I head to the lambda console for ARN:A, I set the test even, paste the request from the service simulator, I test it and I get a perfectly fine ASK response. Then I head to the lambda console for ARN:B and I make a dummy handler that returns exactly the same response that ARN:A gave me from the console (literally copy and paste). I set my skill's endpoint to ARN:B, test it using the service simulator and I get the anticipated response (therefore, the response is well formatted) albeit static. I head to the lambda console again and copy and paste the code from ARN:A into a new ARN:C. Set the skill's endpoint to ARN:C and it works perfectly fine. Problem with ARN:C is that it doesn't have the proper permissions to persist data into DynamoDB (I'm still getting familiar with the system, not sure wether I can share an IAM role between different lambdas, I believe not).
How can I figure out what's going on with ARN:A? Is that logged somewhere? I can't find any entry in cloudwatch/logs related to this particular lambda or for the skill.

Not sure if relevant, I'm using python for my lambda runtime, the code is (for now) inline on the web editor and I'm using boto3 for persisting to DynamoDB.

答:
Unrelated to python, but I have found the same issue occurs for me if I do not have a handler for a specified intent:

```<code>  # lets pretend intentName is actually 'FooBarIntent'
  if (intentName == 'TestIntent') {
    handleTestRequest(intent, session, callback);
  } else {
    throw "Invalid intent";
  }
</code>```

From here, amazon was barking that my lambda was invalid. For others it could indicate an error is being thrown earlier in the stack.

You can also log out your lambda errors with aws cloudwatch which will reveal any warnings or errors.

check out my repo, alexa lambda starter kit for a a simple hello world ask/lambda example.

Body:
Unrelated to python, but I have found the same issue occurs for me if I do not have a handler for a specified intent:

  # lets pretend intentName is actually 'FooBarIntent'
  if (intentName == 'TestIntent') {
    handleTestRequest(intent, session, callback);
  } else {
    throw "Invalid intent";
  }

From here, amazon was barking that my lambda was invalid. For others it could indicate an error is being thrown earlier in the stack.

You can also log out your lambda errors with aws cloudwatch which will reveal any warnings or errors.

check out my repo, alexa lambda starter kit for a a simple hello world ask/lambda example.


问:
Cloud Function for Firebase Type Error - Cannot Read Property
I'm trying to write a Cloud Function that creates a record whenever someone uses our legacy app to create a record (we have changed the Firebase backend architecture and want to slowly migrate users). However, I'm getting the following error in my logs:

```<code>TypeError: Cannot read property 'update' of undefined
    at exports.makeNewComment.functions.database.ref.onWrite.event (/user_code/index.js:14:92)
    at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:35:20
    at process._tickDomainCallback (internal/process/next_tick.js:129:7)
</code>```

Here is the script in question:

```<code>//required modules
var functions = require('firebase-functions');
const admin = require('firebase-admin');

// Listens for new comments added to /comments/ and adds it to /post-comments/

exports.makeNewComment = functions.database.ref('comments/{commentId}').onWrite(event => {
  // Grab the current value of what was written to the Realtime Database.
  const commentId = event.params.commentId;
  const comment = event.data.val();
  // You must return a Promise when performing asynchronous tasks inside a Functions such as
  // writing to the Firebase Realtime Database.
  //return event.data.ref.parent.child('post-comments').set(comment);
  return functions.database.ref('post-comments/' + comment['postID'] + '/' + commentId).update(comment).then(url => {
    return functions.database.ref('user-comments/' + comment['postedBy'] + '/' + commentId).update(comment);
  });
});

//initialize
admin.initializeApp(functions.config().firebase);
</code>```

Thanks!

答:
Based on Doug's answer, you can replace functions.database.ref with event.data.ref.root.

```<code>var functions = require('firebase-functions');
const admin = require('firebase-admin');

exports.makeNewComment = functions.database.ref('comments/{commentId}').onWrite(event => {

  const commentId = event.params.commentId;
  const comment = event.data.val();

  return event.data.ref.root.child('post-comments/' + comment['postID'] + '/' + commentId).update(comment).then(url => {
    return event.data.ref.root.child('user-comments/' + comment['postedBy'] + '/' + commentId).update(comment);
  });
});

admin.initializeApp(functions.config().firebase);
</code>```

Body:
I'm trying to write a Cloud Function that creates a record whenever someone uses our legacy app to create a record (we have changed the Firebase backend architecture and want to slowly migrate users). However, I'm getting the following error in my logs:

TypeError: Cannot read property 'update' of undefined
    at exports.makeNewComment.functions.database.ref.onWrite.event (/user_code/index.js:14:92)
    at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:35:20
    at process._tickDomainCallback (internal/process/next_tick.js:129:7)

Here is the script in question:

//required modules
var functions = require('firebase-functions');
const admin = require('firebase-admin');

// Listens for new comments added to /comments/ and adds it to /post-comments/

exports.makeNewComment = functions.database.ref('comments/{commentId}').onWrite(event => {
  // Grab the current value of what was written to the Realtime Database.
  const commentId = event.params.commentId;
  const comment = event.data.val();
  // You must return a Promise when performing asynchronous tasks inside a Functions such as
  // writing to the Firebase Realtime Database.
  //return event.data.ref.parent.child('post-comments').set(comment);
  return functions.database.ref('post-comments/' + comment['postID'] + '/' + commentId).update(comment).then(url => {
    return functions.database.ref('user-comments/' + comment['postedBy'] + '/' + commentId).update(comment);
  });
});

//initialize
admin.initializeApp(functions.config().firebase);

Thanks!

Body:
Based on Doug's answer, you can replace functions.database.ref with event.data.ref.root.

var functions = require('firebase-functions');
const admin = require('firebase-admin');

exports.makeNewComment = functions.database.ref('comments/{commentId}').onWrite(event => {

  const commentId = event.params.commentId;
  const comment = event.data.val();

  return event.data.ref.root.child('post-comments/' + comment['postID'] + '/' + commentId).update(comment).then(url => {
    return event.data.ref.root.child('user-comments/' + comment['postedBy'] + '/' + commentId).update(comment);
  });
});

admin.initializeApp(functions.config().firebase);


问:
Difference between Swift 2 and 3? How to all a class's method within another?
I believe I have a pretty simple question here, but due to my lack of experience with Swift, I have been unable to find the answer.

Here are two classes I created:

My controller:

```<code>import UIKit

class ViewController: UIViewController {

    @IBOutlet private weak var display: UILabel!

    private var userIsInTheMIddleOfTyping = false

    private var brain  = CalculatorBrain()

    private var displayValue: Double {

    get {

        return Double(display.text!)!

    }

    set {

        display.text = String(newValue)

    }

    }

    @IBAction private func performOperation(_ sender: UIButton) {

        if userIsInTheMIddleOfTyping{

            brain.setOperand(displayValue)

            userIsInTheMIddleOfTyping = false

        }

        if let mathematicalSymbol = sender.currentTitle {

            brain.performOperation(mathematicalSymbol)

        }

        displayValue = brain.result

        }

    }
</code>```

My model:

```<code>import Foundation

class CalculatorBrain{

    private var accumulator = 0.0

    func  setOperand(operand: Double){

        accumulator = operand

    }

    func performOperation(symbol: String){

        switch symbol{

            case "π": accumulator = M_PI

            case "√": accumulator = sqrt(accumulator)

            default: break
        }

    }

    var result: Double{

        get {

            return accumulator
        }

    }

}
</code>```

For some reason I get an error in line: brain.setOperand(displayValue)

Any reason why?

答:
I tried your code and everything was fine, excepted two things:

```<code>brain.setOperand(operand: displayValue)
brain.performOperation(symbol: mathematicalSymbol)
</code>```

In Swift 3, the first parameter need a external parameter by default.

Body:
I believe I have a pretty simple question here, but due to my lack of experience with Swift, I have been unable to find the answer.

Here are two classes I created:

My controller:

import UIKit

class ViewController: UIViewController {

    @IBOutlet private weak var display: UILabel!

    private var userIsInTheMIddleOfTyping = false

    private var brain  = CalculatorBrain()

    private var displayValue: Double {

    get {

        return Double(display.text!)!

    }

    set {

        display.text = String(newValue)

    }

    }

    @IBAction private func performOperation(_ sender: UIButton) {

        if userIsInTheMIddleOfTyping{

            brain.setOperand(displayValue)

            userIsInTheMIddleOfTyping = false

        }

        if let mathematicalSymbol = sender.currentTitle {

            brain.performOperation(mathematicalSymbol)

        }

        displayValue = brain.result

        }

    }

My model:

import Foundation

class CalculatorBrain{

    private var accumulator = 0.0

    func  setOperand(operand: Double){

        accumulator = operand

    }

    func performOperation(symbol: String){

        switch symbol{

            case "π": accumulator = M_PI

            case "√": accumulator = sqrt(accumulator)

            default: break
        }

    }

    var result: Double{

        get {

            return accumulator
        }

    }

}

For some reason I get an error in line: brain.setOperand(displayValue)

Any reason why?

Body:
I tried your code and everything was fine, excepted two things:

brain.setOperand(operand: displayValue)
brain.performOperation(symbol: mathematicalSymbol)

In Swift 3, the first parameter need a external parameter by default.


问:
All Ruby tests raising: undefined method `authenticate' for nil:NilClass
Most of my tests are raising the following and I don't understand why. All methods call raise the 'authenticate' error. I've checked the code if there was a method called "authenticate" but there is no such method.

```<code>  1) Admin::CommentsController handling GET to index is successful
     Failure/Error: get :index
     undefined method `authenticate!' for nil:NilClass
     # ./spec/controllers/admin/comments_controller_spec.rb:9:in `block (3 levels) in <top (required)>'

  124) PostsController handling GET for a single post should render show template
     Failure/Error: get :show, :year => '2008', :month => '01', :day => '01', :slug => 'a-post'
     undefined method `authenticate' for nil:NilClass
     # ./app/controllers/application_controller.rb:18:in `set_current_user_for_model'
     # ./spec/controllers/posts_controller_spec.rb:131:in `do_get'
     # ./spec/controllers/posts_controller_spec.rb:140:in `block (3 levels) in <top (required)>'
</code>```

The project can be found over there => https://github.com/agilepandas/enki in case you'd like to run the tests your self.

答:
It looks like there are some updates to the source code.  The ApplicationController specifies that there needs to be an authenticate_user! filter run before any request.  This thread provides some background on issues with it:

http://groups.google.com/group/plataformatec-devise/browse_thread/thread/f7260ebe2d9f7316?fwc=1

Essentially, the authenticate_user! function is part of Rails 3 (using the new devise feature, of which I know little about).  If the app can't find the User model (either because of namespace issues or whatever reason) then the method will fail.  The "enki" application you linked to is now a Rails 3 application.  It could be experiencing a few growing pains as it converts over.

Body:
Most of my tests are raising the following and I don't understand why. All methods call raise the 'authenticate' error. I've checked the code if there was a method called "authenticate" but there is no such method.

  1) Admin::CommentsController handling GET to index is successful
     Failure/Error: get :index
     undefined method `authenticate!' for nil:NilClass
     # ./spec/controllers/admin/comments_controller_spec.rb:9:in `block (3 levels) in <top (required)>'

  124) PostsController handling GET for a single post should render show template
     Failure/Error: get :show, :year => '2008', :month => '01', :day => '01', :slug => 'a-post'
     undefined method `authenticate' for nil:NilClass
     # ./app/controllers/application_controller.rb:18:in `set_current_user_for_model'
     # ./spec/controllers/posts_controller_spec.rb:131:in `do_get'
     # ./spec/controllers/posts_controller_spec.rb:140:in `block (3 levels) in <top (required)>'

The project can be found over there => https://github.com/agilepandas/enki in case you'd like to run the tests your self.


问:
Docker exit status 1 for Node app on AWS
I'm hosting a beta app on AWS using Express.js, Node, mongoose  and docker. Daily active users < 10, mainly friends of mine for testing. The app is down almost everyday for some reason. Initially I thought it was AWS's issue, so I stopped my app, changed it from free tier to t2.medium and started it again.

It didn't resolve the issue, I checked docker log for the container. It was not caused by OOMKilled.

```<code>"State": {
        "Status": "exited",
        "Running": false,
        "Paused": false,
        "Restarting": false,
        "OOMKilled": false,
        "Dead": false,
        "Pid": 0,
        "ExitCode": 1,
        "Error": "",
        "StartedAt": "2017-03-22T00:51:59.234643501Z",
        "FinishedAt": "2017-03-22T07:21:41.351927073Z"
    },

    "Config": {
        ...
        "AttachStdin": false,
        "AttachStdout": true,
        "AttachStderr": true,
        ...
    }
</code>```

I could set docker to always restart, but I want to figure out what's the root cause of it. Any suggestions?

答:
That happens to everyone.  Lots of things can kill Express applications, like weird HTTP requests.  The Docker log should show the exception.  Add an uncaughtException handler to log the issue.

```<code>process.on('uncaughtException', (e) => {
  console.error(e); // try console.log if that doesn't work
  process.exit(10);
});
</code>```

If you can't find an error in the Docker log, then instead of logging to the console, maybe you can log to a file (make sure it is in a volume that stays between Docker runs though).

People don't like admitting this but many applications actually just log the exception and eat it and keep going in the uncaughtException handler without exiting.  Because things like broken requests or other stuff that doesn't matter often kill the server you can usually get away with this.  But then once in a while you will get burned by something strange happening to the server state that it can't recover from and you will have no idea because you just ate the exception.

You may be able to have it autorestart the app https://docs.docker.com/docker-cloud/apps/autorestart/ which might be a good solution.

Otherwise look into an example of using pm2 along with Docker if possible, pm2 will handle restarting for you.

Body:
I'm hosting a beta app on AWS using Express.js, Node, mongoose  and docker. Daily active users < 10, mainly friends of mine for testing. The app is down almost everyday for some reason. Initially I thought it was AWS's issue, so I stopped my app, changed it from free tier to t2.medium and started it again.

It didn't resolve the issue, I checked docker log for the container. It was not caused by OOMKilled.

"State": {
        "Status": "exited",
        "Running": false,
        "Paused": false,
        "Restarting": false,
        "OOMKilled": false,
        "Dead": false,
        "Pid": 0,
        "ExitCode": 1,
        "Error": "",
        "StartedAt": "2017-03-22T00:51:59.234643501Z",
        "FinishedAt": "2017-03-22T07:21:41.351927073Z"
    },

    "Config": {
        ...
        "AttachStdin": false,
        "AttachStdout": true,
        "AttachStderr": true,
        ...
    }

I could set docker to always restart, but I want to figure out what's the root cause of it. Any suggestions?

Body:
That happens to everyone.  Lots of things can kill Express applications, like weird HTTP requests.  The Docker log should show the exception.  Add an uncaughtException handler to log the issue.

process.on('uncaughtException', (e) => {
  console.error(e); // try console.log if that doesn't work
  process.exit(10);
});

If you can't find an error in the Docker log, then instead of logging to the console, maybe you can log to a file (make sure it is in a volume that stays between Docker runs though).

People don't like admitting this but many applications actually just log the exception and eat it and keep going in the uncaughtException handler without exiting.  Because things like broken requests or other stuff that doesn't matter often kill the server you can usually get away with this.  But then once in a while you will get burned by something strange happening to the server state that it can't recover from and you will have no idea because you just ate the exception.

You may be able to have it autorestart the app https://docs.docker.com/docker-cloud/apps/autorestart/ which might be a good solution.

Otherwise look into an example of using pm2 along with Docker if possible, pm2 will handle restarting for you.


问:
Two Time htacces Rewrite
I need to do something like this :

1 Rewrite :

Force : localhost/main/ ==> localhost

2 Rewrite :

localhost/?api=test123&page=m1 ==> localhost/test123/m1

and if api is empty , just go page

localhost/m1 => Page : m1 ( in this url , user don't ask to api )

I have this htaccess :

RewriteCond %{REQUEST_URI} !main/
RewriteRule (.*) /main/$1 [L]
RewriteRule ([^/]*)/([^/]*)/$ /main/index.php?api=$2&page=$3 [L]```

Thanks and sorry for my poor english.

答:
It's the awnser :

RewriteRule ^page/([^/]*)/$ /main/index.php?page=$1 [QSA,L] [OR]
RewriteRule ^api/([^/]*)/$ /main/index.php?api=$1 [QSA,L] [OR]

RewriteCond %{REQUEST_URI} !main/
RewriteRule (.*) /main/$1```

Title: Two Time htacces Rewrite

Body:
I need to do something like this :

1 Rewrite :

Force : localhost/main/ ==> localhost

2 Rewrite :

localhost/?api=test123&page=m1 ==> localhost/test123/m1

and if api is empty , just go page

localhost/m1 => Page : m1 ( in this url , user don't ask to api )

I have this htaccess :

RewriteCond %{REQUEST_URI} !main/
RewriteRule (.*) /main/$1 [L]
RewriteRule ([^/]*)/([^/]*)/$ /main/index.php?api=$2&page=$3 [L]

Thanks and sorry for my poor english.


问:
CSS cloud animation issue
the css animation (loop) ist not correct.
I made the example faster, so you can see it after every 5. second.
How can I fix that?

Demo:

```<code>`https://jsfiddle.net/bt3vzwns/`
</code>```

答:
Don't set left: 100%, it'll push left 100% of your div's width.

Since your cloud.png is 1000px wide, try left: 1000px; demo here.

Title: CSS cloud animation issue

Body:
the css animation (loop) ist not correct.
I made the example faster, so you can see it after every 5. second.
How can I fix that?

Demo:

`https://jsfiddle.net/bt3vzwns/`


问:
SSL: no alternative certificate subject name matches target host name $name.storage.googleapis.com
I want to run tensorflow traning script in google cloud ml. One of the buckets from an external project. I have created cloud ml engine service account and add it as an user to this external project.

After that, have executed the following command in my terminal with gcloud initialised project:

```<code>gcloud auth activate-service-account --my-service-acc-key.json
</code>```

And then submit my job as:

```<code>gcloud ml-engine jobs submit training ..arguments
</code>```

Job was submitted successfully and was running until accessing resources from external bucket with file_io.FileIO('gs://external-bucket')

I got the following error SSL: no alternative certificate subject name matches target host ${bucket-name}.storage.googleapis.com instead.

Looks like something wrong with credentials, but can't find anything useful in documentation.

What could be a problem?

答:
Unfortunately domain buckets like bucketname.domainname.com are not properly supported by the GCS client library inside TensorFlow at the moment.

This problem was fixed in the TensorFlow Google repository today.

The fix should become available on TensorFlow github within 2-3 days from now, after which you should be able to either build TensorFlow from head or take a nightly Linux build and provide it as one of the package_uris when submitting a training job to Cloud ML Engine.

Alternatively you can wait until it gets picked up by the next official TensorFlow release supported by Cloud ML Engine.

Body:
I want to run tensorflow traning script in google cloud ml. One of the buckets from an external project. I have created cloud ml engine service account and add it as an user to this external project.

After that, have executed the following command in my terminal with gcloud initialised project:

gcloud auth activate-service-account --my-service-acc-key.json

And then submit my job as:

gcloud ml-engine jobs submit training ..arguments

Job was submitted successfully and was running until accessing resources from external bucket with file_io.FileIO('gs://external-bucket')

I got the following error SSL: no alternative certificate subject name matches target host ${bucket-name}.storage.googleapis.com instead.

Looks like something wrong with credentials, but can't find anything useful in documentation.

What could be a problem?


问:
Linq-to-Entities/Linq-to-SQL, Is One Data Polling Method More Efficient?
Are the following two examples different and if so, which is more efficient?

```<code>var user = (from u in db.Users where u.Id == userId select u).Single();
</code>```

and

```<code>var user = db.Users.Single(p => p.Id == userId);
</code>```

答:
They are functionally equivalent. There could be slight differences in how they are implemented in the various LINQ providers, but I would expect almost exactly equal performance. The LINQ to SQL provider for example produces the exact same SQL for both queries:

```<code>SELECT [t0].[Id], [t0].[Name]
FROM [dbo].[User] AS [t0]
WHERE [t0].[Id] = @p0
</code>```

I expect that the same applies to the Entity Framework.

If I had to pick one I'd choose the second version because it is more concise with no loss of clarity. In fact I would say it is more clear - there is less keyword noise so the business logic stands out more.

Body:
Are the following two examples different and if so, which is more efficient?

var user = (from u in db.Users where u.Id == userId select u).Single();

and

var user = db.Users.Single(p => p.Id == userId);

Body:
They are functionally equivalent. There could be slight differences in how they are implemented in the various LINQ providers, but I would expect almost exactly equal performance. The LINQ to SQL provider for example produces the exact same SQL for both queries:

SELECT [t0].[Id], [t0].[Name]
FROM [dbo].[User] AS [t0]
WHERE [t0].[Id] = @p0

I expect that the same applies to the Entity Framework.

If I had to pick one I'd choose the second version because it is more concise with no loss of clarity. In fact I would say it is more clear - there is less keyword noise so the business logic stands out more.


问:
PHP Remove empty value from array with unset not working correctly
I have a string containing sentences. I wish to break these sentences into an array, then modify each array item, including removing any array items that are empty.

Here's what I have:

```<code>//Explode string by dot
$items_array = explode(".", $raw_data);

//Loop through the array
foreach ($items_array as $i => $item) {

  //Remove any whitespace at front of item
  $item= ltrim($item);

  //Check if array item is empty and unset
  if($item === NULL){
    unset($items_array[$i]);
  }

  //Reinstate the dot
  $item .= '.';
}
</code>```

However, this does not work. I see extra '.' and if I put a print(strlen($item)); within the loop (after the unset) I see a few 0 results.

I know the if condition is being met because if I put a print in there it will trigger the same amount of times a 0 appears, eg:

```<code> if($item === NULL){
      print("no value");
      unset($raw_inclusions[$i]);
    }
</code>```

Have I done something wrong here?

Example $raw_data string. Assume I have no control over what is placed here.

```<code>$raw_data = "Brown fox. Lazy dog."
</code>```

Expected/desired result:

```<code>$items_array = array("Brown fox.", "Lazy dog.");
</code>```

Current result:

```<code>$items_array = array("Brown fox.", "Lazy dog.", ".");
</code>```

答:
It's actually pretty easy, you are just missing 1 line of code

Your Code

```<code>if($item === NULL){
    unset($items_array[$i]);
}
//Reinstate the dot
$item .= '.';
</code>```

Make it this

```<code>if($item === NULL){
    unset($items_array[$i]);
}
else // <- The else is important
//Reinstate the dot
   $item .= '.';
</code>```

And you need this line

```<code>$items_array[$i] = $item;
</code>```

for anything to work (including your original code)

Body:
I have a string containing sentences. I wish to break these sentences into an array, then modify each array item, including removing any array items that are empty.

Here's what I have:

//Explode string by dot
$items_array = explode(".", $raw_data);

//Loop through the array
foreach ($items_array as $i => $item) {

  //Remove any whitespace at front of item
  $item= ltrim($item);

  //Check if array item is empty and unset
  if($item === NULL){
    unset($items_array[$i]);
  }

  //Reinstate the dot
  $item .= '.';
}

However, this does not work. I see extra '.' and if I put a print(strlen($item)); within the loop (after the unset) I see a few 0 results.

I know the if condition is being met because if I put a print in there it will trigger the same amount of times a 0 appears, eg:

 if($item === NULL){
      print("no value");
      unset($raw_inclusions[$i]);
    }

Have I done something wrong here?

Example $raw_data string. Assume I have no control over what is placed here.

$raw_data = "Brown fox. Lazy dog."

Expected/desired result:

$items_array = array("Brown fox.", "Lazy dog.");

Current result:

$items_array = array("Brown fox.", "Lazy dog.", ".");

Body:
It's actually pretty easy, you are just missing 1 line of code

Your Code

if($item === NULL){
    unset($items_array[$i]);
}
//Reinstate the dot
$item .= '.';

Make it this

if($item === NULL){
    unset($items_array[$i]);
}
else // <- The else is important
//Reinstate the dot
   $item .= '.';

And you need this line

$items_array[$i] = $item;

for anything to work (including your original code)


问:
Google+ API - Pass User Email in Query String
I want to pass the name and email of the logged in Google+ API user into my URL. I have the following link on my web page:

```<code><a href="http://10.2.114.243/Default.aspx?name=<%= user.givenName %>&email=<%= user.email %>">Create Project</a>
</code>```

This passes the user's first name into the URL just fine. However, I cannot, despite much googling, determine what the value is for getting the user's email. I found Google's People Reference documentation and tried different combinations:

emails[0].value

emails[].value

emails.value

value

but each time, the value is passed in the query string as undefined or throws an error.

I was told I need to figure out what the JSON value is for the user's email.

答:
Well, it ended up needing to be user._json.email. The following is my final code, in case it helps anyone

```<code><% if (user != 1) { %>
        <% var firstName = user.displayName
        firstName = firstName.substring(0, firstName.indexOf('\ '));
        %>
        <a href="http://192.168.165.100/Default.aspx?name=<%= firstName %>&email=<%= user._json.email %>">Create Project</a>
<% } %>
</code>```

Body:
I want to pass the name and email of the logged in Google+ API user into my URL. I have the following link on my web page:

<a href="http://10.2.114.243/Default.aspx?name=<%= user.givenName %>&email=<%= user.email %>">Create Project

This passes the user's first name into the URL just fine. However, I cannot, despite much googling, determine what the value is for getting the user's email. I found Google's People Reference documentation and tried different combinations:

emails[0].value

emails[].value

emails.value

value

but each time, the value is passed in the query string as undefined or throws an error.

I was told I need to figure out what the JSON value is for the user's email.

Body:
Well, it ended up needing to be user._json.email. The following is my final code, in case it helps anyone

<% if (user != 1) { %>
        <% var firstName = user.displayName
        firstName = firstName.substring(0, firstName.indexOf('\ '));
        %>
        <a href="http://192.168.165.100/Default.aspx?name=<%= firstName %>&email=<%= user._json.email %>">Create Project</a>
<% } %>


问:
Initialize list inside of public class
I have this:

```<code>public class GetList {

    public List< KeyValuePair< string, string > > errors {
        get; set;
    }
}
</code>```

I would like to know how to add a constructor to get a new instance of the class and a new list to which I can add values

答:
Constructors are defined like so:

```<code>class ClassNameGoesHere {

    public ClassNameGoesHere() {
        // this is the constructor
    }
}
</code>```

You can initialize your errors property in the constructor:

```<code>class ClassNameGoesHere {

    public ClassNameGoesHere() {

        this.errors = new List< KeyValuePair< string, string > >();
    }
}
</code>```

However you should conform to C# idiomatic programming by making collection properties readonly (this doesn't mean the collection is immutable, it just prevents external code from replacing the collection entirely) as well as using established naming and capitalization conventions.

I would also use Tuple<String,String> instead of KeyValuePair<K,V> or define my own element type.

You can set a read-only property using a property initializer, which is equivalent to putting it in the constructor, but makes the code more compact, so the explicit constructor can be eliminated completely:

This is how I would do it:

```<code>class ClassNameGoesHere {

    public List<Tuple<String,String>> Errors { get; } = new List<Tuple<String,String>>();
}
</code>```

Title: Initialize list inside of public class

Body:
I have this:

public class GetList {

    public List< KeyValuePair< string, string > > errors {
        get; set;
    }
}

I would like to know how to add a constructor to get a new instance of the class and a new list to which I can add values

Body:
Constructors are defined like so:

class ClassNameGoesHere {

    public ClassNameGoesHere() {
        // this is the constructor
    }
}

You can initialize your errors property in the constructor:

class ClassNameGoesHere {

    public ClassNameGoesHere() {

        this.errors = new List< KeyValuePair< string, string > >();
    }
}

However you should conform to C# idiomatic programming by making collection properties readonly (this doesn't mean the collection is immutable, it just prevents external code from replacing the collection entirely) as well as using established naming and capitalization conventions.

I would also use Tuple<String,String> instead of KeyValuePair<K,V> or define my own element type.

You can set a read-only property using a property initializer, which is equivalent to putting it in the constructor, but makes the code more compact, so the explicit constructor can be eliminated completely:

This is how I would do it:

class ClassNameGoesHere {

    public List<Tuple<String,String>> Errors { get; } = new List<Tuple<String,String>>();
}


问:
ServerSocket accept() method
Who knows how the port is chosen when I'm using accept method of ServerSocket class? Is it possible to define a range for the ports the method can choose from? Can I 'take' ports one by one just in order?

```<code>ServerSocket sSocket = new ServerSocket(5050);
Socket socket = sSocket.accept();
</code>```

答:
The diagram is incorrect (and is listed in the unconfirmed errata on the O'Reilly site).

The client chooses its port at random (you don't need to do anything special in Java) and connects to the server on whichever port you specified. Using the netstat commandline tool you can see this.

First, just the listening server socket with no clients:

```
simon@lucifer:~$ netstat -n -a
Active Internet connections (including servers)
Proto Recv-Q Send-Q  Local Address          Foreign Address     (state)
...
tcp46      0      0  *.5050                 *.*                 LISTEN
...
```

(there are lots of other entries, I've just removed the unrelated ones)

Now with one client connecting from localhost (127.0.0.1):

```
simon@lucifer:~$ netstat -n -a
Active Internet connections (including servers)
Proto Recv-Q Send-Q  Local Address          Foreign Address     (state)
...
tcp4       0      0  127.0.0.1.64895        127.0.0.1.5050      ESTABLISHED <- 1
tcp4       0      0  127.0.0.1.5050         127.0.0.1.64895     ESTABLISHED <- 2
tcp46      0      0  *.5050                 *.*                 LISTEN      <- 3
...
```

Since the client is connecting from the same machine, we see two established connections - one from client to server (1), the other from server to client (2). They have opposite local and foreign addresses (since they're talking to each other) and you can see the server is still using port 5050 while the original server socket (3) continues to listen on the same port.

(this output is from a Mac, but Windows/Linux also have netstat giving similar output)

Title: ServerSocket accept() method

Body:
Who knows how the port is chosen when I'm using accept method of ServerSocket class? Is it possible to define a range for the ports the method can choose from? Can I 'take' ports one by one just in order?

ServerSocket sSocket = new ServerSocket(5050);
Socket socket = sSocket.accept();

Body:
The diagram is incorrect (and is listed in the unconfirmed errata on the O'Reilly site).

The client chooses its port at random (you don't need to do anything special in Java) and connects to the server on whichever port you specified. Using the netstat commandline tool you can see this.

First, just the listening server socket with no clients:

simon@lucifer:~$ netstat -n -a
Active Internet connections (including servers)
Proto Recv-Q Send-Q  Local Address          Foreign Address     (state)
...
tcp46      0      0  *.5050                 *.*                 LISTEN
...

(there are lots of other entries, I've just removed the unrelated ones)

Now with one client connecting from localhost (127.0.0.1):

simon@lucifer:~$ netstat -n -a
Active Internet connections (including servers)
Proto Recv-Q Send-Q  Local Address          Foreign Address     (state)
...
tcp4       0      0  127.0.0.1.64895        127.0.0.1.5050      ESTABLISHED <- 1
tcp4       0      0  127.0.0.1.5050         127.0.0.1.64895     ESTABLISHED <- 2
tcp46      0      0  *.5050                 *.*                 LISTEN      <- 3
...

Since the client is connecting from the same machine, we see two established connections - one from client to server (1), the other from server to client (2). They have opposite local and foreign addresses (since they're talking to each other) and you can see the server is still using port 5050 while the original server socket (3) continues to listen on the same port.

(this output is from a Mac, but Windows/Linux also have netstat giving similar output)

ContentLicense: CC BY-SA 4.0


问:
Detecting when ajax success function takes longer than 5 seconds and redirect
Hello I have this script that moves from one page through a href without page load.

It works perfectly, but I want to redirect to the requested page if Ajax takes longer than 5 seconds to respond, usually caused by probably slow internet connection.
In this case: Stop the script and load the page normally.

Firstly the href:

```<code><a href="new.php" rel="tab">new</a>
<a href="new1.php" rel="tab">New 1</a>
</code>```

This is the script:

```<code><script>
$(function(){
  $("a[rel='tab']").click(function(e){
    pageurl = $(this).attr('href'); //get the href clicked
    $.ajax({url:pageurl+'?rel=tab',
      success: function(data){
        $('#mole').html(data);
      }
    });
    if(pageurl!=window.location){
      window.history.pushState({
        path:pageurl
      },'',pageurl);
    }
    return false;
  });
});

$(window).bind('popstate', function(){
  $.ajax({
    url:location.pathname+'?rel=tab',
    success: function(data){
      // here how do I detect if the success takes longer than 5 seconds
      // stop the script and load the page normally which is the URL parameter in ajax
      $('#mole').html(data);
    }
  });
});
</script>
</code>```

答:
First, we need to add a timeout to the ajax handler so it will cancel the request after 5 seconds (here we use 5000 for milliseconds). Then, based on the docs, head to error and you can see the second param is textStatus. If it was a timeout, this will be equal to "timeout". This is probably your easiest path to what you need to do. Update the error handler as needed for your functionality.

```<code>$(window).bind('popstate', function() {
    var url = location.pathname + '?rel=tab';
    $.ajax({
        timeout: 5000,
        url: url,
        success: function(data) {
            $('#mole').html(data);
        },
        error: function(jqXHR, textStatus) {
            if (textStatus === 'timeout') {
                // we know the ajax failed due to a timeout,
                // do what you need here, below is an example.
                window.location = url;
            }
        }
    });
});
</code>```

Body:
Hello I have this script that moves from one page through a href without page load.

It works perfectly, but I want to redirect to the requested page if Ajax takes longer than 5 seconds to respond, usually caused by probably slow internet connection.
In this case: Stop the script and load the page normally.

Firstly the href:

new
New 1

This is the script:

Body:
First, we need to add a timeout to the ajax handler so it will cancel the request after 5 seconds (here we use 5000 for milliseconds). Then, based on the docs, head to error and you can see the second param is textStatus. If it was a timeout, this will be equal to "timeout". This is probably your easiest path to what you need to do. Update the error handler as needed for your functionality.

$(window).bind('popstate', function() {
    var url = location.pathname + '?rel=tab';
    $.ajax({
        timeout: 5000,
        url: url,
        success: function(data) {
            $('#mole').html(data);
        },
        error: function(jqXHR, textStatus) {
            if (textStatus === 'timeout') {
                // we know the ajax failed due to a timeout,
                // do what you need here, below is an example.
                window.location = url;
            }
        }
    });
});


问:
How to schedule jobs in a spark cluster using Kubernetes
I am rather new to both Spark and Kubernetes but i am trying to understand how this can work in a production envitonment. I am planning to use Kubernetes to deploy a Spark cluster. I will then use SparkStraeming to process data from Kafka and output the result to a database. Furthermore, i am planning to set up a scheduled Spark-batch-job that is run every night.

1. How do i schedule the nightly batch-runs?
I understand that Kubernetes has a cron-like feature (see documentation). But from my understanding, this is to schedule container deployments, i will already have my containers up and running (since i use the Spark-cluster for SparkStreaming), i just want to submit a job to the cluster every night.

2. Where do i store the SparkStreaming-application(s) (there might be many) and how do i start it?
Do i seperate the Spark-container from the SparkStreaming-application (i.e. should the container only contain a clean Spark-node, and keep the SparkStreaming-application in persistent storage and then push the job to the container using kubectl)?
Or should my docker-file clone my SparkStreaming-application from a repository and be responsible for starting it.

I have tried looking through the documentations but i am unsure on how to set it up. Any link or reference that answers my question is highly appreciated.

答:
You should absolutely use the CronJob resource for performing the backups... see also these repos for helping bootstrap spark on k8s

https://github.com/ramhiser/spark-kubernetes

https://github.com/navicore/spark-on-kubernetes


问:
Does not print all elements in Array
Hello I'm trying to get my array "numbers" to print out all even numbers for some reason I can't get it to call the array from earlier in my code so that the array can be used down below.</p>

```<code> import java.util.Random;

public class Main {
  public static void main(String [] args){
      int numbers[] = new int [10];
      for (int x = 0; x < numbers.length; x++){
      Random rand = new Random();
      numbers[x] = rand.nextInt(100)+1;
      System.out.print("" + numbers[x] + " ");
      }
    System.out.println("");
    System.out.print("The values at even indexes are: " + numbers[0] + " " + numbers[2] + " " + numbers[4] + " " + numbers[6] + " " + numbers[8]);
    System.out.println("");
    if(numbers[x] % 2 == 0){
      System.out.print(numbers[x]);
    }
  }
}
</code>```

答:
your problem that you put if(numbers[x] % 2 == 0) outside for loop so you can't iterate over array by index x:

```<code>for (int x = 0; x < numbers.length; x++){
    if(numbers[x] % 2 == 0){
      System.out.print(numbers[x]);
    }
}
</code>```

Title: Does not print all elements in Array

Body:
Hello I'm trying to get my array "numbers" to print out all even numbers for some reason I can't get it to call the array from earlier in my code so that the array can be used down below.

 import java.util.Random;

public class Main {
  public static void main(String [] args){
      int numbers[] = new int [10];
      for (int x = 0; x < numbers.length; x++){
      Random rand = new Random();
      numbers[x] = rand.nextInt(100)+1;
      System.out.print("" + numbers[x] + " ");
      }
    System.out.println("");
    System.out.print("The values at even indexes are: " + numbers[0] + " " + numbers[2] + " " + numbers[4] + " " + numbers[6] + " " + numbers[8]);
    System.out.println("");
    if(numbers[x] % 2 == 0){
      System.out.print(numbers[x]);
    }
  }
}

Body:
your problem that you put if(numbers[x] % 2 == 0) outside for loop so you can't iterate over array by index x:

for (int x = 0; x < numbers.length; x++){
    if(numbers[x] % 2 == 0){
      System.out.print(numbers[x]);
    }
}


问:
UITextField .text attribute always returns an empty string
I'm programming forms for my iOS app, and my UITextFields act strangely :

When the form is in update state (fields are already filled) I can edit and get the new input text (typed by user) with the .text attribute. But when the form is in insert mode the UITextFields are initially empty and I cannot get the text typed then by the user with the .text attribute because it always returns an empty string whatever the user types.
Here is a video showing the issue : https://youtu.be/tPJZ3sC-IFU

```<code>{
    __weak IBOutlet UITextField *txtLibelle; //linked by ctrl + drag to the storyboard
    NSString *libelleTemp;
}
- (void)viewDidLoad {
[super viewDidLoad];

    // ...

    [txtLibelle addTarget:self
                   action:@selector(editingChanged:)
         forControlEvents:UIControlEventEditingChanged];

    // ...

}

-(void) editingChanged:(id)sender {
    libelleTemp = txtLibelle.text;
    // libelleTemp is set to @"" whatever the user has typed in when I'm in insert mode
}

-(void)initWithLib:(NSString *)lib {
    libelleTemp = [NSString stringWithString:lib];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
    if (indexPath.section == 0) {
        txtLibelle.text = libelleTemp;
    }

    // ...

    return cell;
}
</code>```

The initWithLib: method is called from the previous view controller like this :

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UIStoryboard *accueilNavSB = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    FicheAlerteTableViewController *vc = [accueilNavSB instantiateViewControllerWithIdentifier:@"ficheAlerte"];
    NSString *libelle = @"";
    [vc initWithLib:libelle];
    [self.navigationController showViewController:vc sender:self];
}
</code>```

I already have relinked the field from the storyboard to my class, and in debug mode my UITextField is not nil.

My textfields are in a static UITableView, so I can see if the update worked scrolling the cell off the screen then scrolling it on.

Does anyone know why is this happening and how to solve the problem?

答: You are using the wrong action. UITextField's 'text' property will only be set once the editing has ended. So you need to wire your method to the "Editing Ended" event in Interface Builder.</p>

Body:
I'm programming forms for my iOS app, and my UITextFields act strangely :

When the form is in update state (fields are already filled) I can edit and get the new input text (typed by user) with the .text attribute. But when the form is in insert mode the UITextFields are initially empty and I cannot get the text typed then by the user with the .text attribute because it always returns an empty string whatever the user types.
Here is a video showing the issue : https://youtu.be/tPJZ3sC-IFU

{
    __weak IBOutlet UITextField *txtLibelle; //linked by ctrl + drag to the storyboard
    NSString *libelleTemp;
}
- (void)viewDidLoad {
[super viewDidLoad];

    // ...

    [txtLibelle addTarget:self
                   action:@selector(editingChanged:)
         forControlEvents:UIControlEventEditingChanged];

    // ...

}

-(void) editingChanged:(id)sender {
    libelleTemp = txtLibelle.text;
    // libelleTemp is set to @"" whatever the user has typed in when I'm in insert mode
}

-(void)initWithLib:(NSString *)lib {
    libelleTemp = [NSString stringWithString:lib];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
    if (indexPath.section == 0) {
        txtLibelle.text = libelleTemp;
    }

    // ...

    return cell;
}

The initWithLib: method is called from the previous view controller like this :

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UIStoryboard *accueilNavSB = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    FicheAlerteTableViewController *vc = [accueilNavSB instantiateViewControllerWithIdentifier:@"ficheAlerte"];
    NSString *libelle = @"";
    [vc initWithLib:libelle];
    [self.navigationController showViewController:vc sender:self];
}

I already have relinked the field from the storyboard to my class, and in debug mode my UITextField is not nil.

My textfields are in a static UITableView, so I can see if the update worked scrolling the cell off the screen then scrolling it on.

Does anyone know why is this happening and how to solve the problem?


问:
Is there any way to get specific range of words?
```<code>time='2017-03-29 08:28:55'
</code>```

I hope this str make like below with something. such as split or something

```<code>new_time='2017-03-29 08:28'
</code>```

How would I do?

答:
You can use array slice, try the following code for your example:</p>

```<code>>>> time='2017-03-29 08:28:55'
>>> time[:-3]
'2017-03-29 08:28'
</code>```

Body:
time='2017-03-29 08:28:55'

I hope this str make like below with something. such as split or something

new_time='2017-03-29 08:28'

How would I do?

Body:
You can use array slice, try the following code for your example:

>>> time='2017-03-29 08:28:55'
>>> time[:-3]
'2017-03-29 08:28'


问:
log4net: How to store data in DB
I am planning to replace few different logging mechanism with the only 1. Also I would like to store data not in file, but in DB.

For this purpose I am planning to choose log4net. But looking on the documentation I don't see a way to configure it to use DB as logs storage.

Am I missed something? Could you please point me if there is a way to store data in DB using log4net. And how to do that?

Thanks a lot!

答: Check here.  It will give you examples of how to set up your config for the database you are accessing.</p>

Title: log4net: How to store data in DB