问:
Android: Problem to access google tasks with OAuth
As google tasks has no public api I want to write workaround and request data like a browser and then parse results to further display.

To access data I've implemented a OAuth authentication with google to access this url: https://mail.google.com/

For OAuth I've used sign-post library and it works well.

The problem is when I am trying to access https://mail.google.com/tasks/ig with signed request it returns me login page instead of desired list with tasks.

To be more specific here is my code:

```<code>public class GoogleOAuthActivity extends Activity {
    private static final String TAG = GoogleOAuthActivity.class.getSimpleName();
    private CommonsHttpOAuthProvider provider;
    private CommonsHttpOAuthConsumer consumer;

    @Override
    @SuppressWarnings("unchecked")
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        provider = new CommonsHttpOAuthProvider(OAuthPrefs.GET_REQUEST_TOKEN_URL, OAuthPrefs.GET_ACCESS_TOKEN_URL,
                OAuthPrefs.TOKEN_AUTHORIZATION_URL);
        consumer = new CommonsHttpOAuthConsumer(OAuthPrefs.CONSUMER_KEY, OAuthPrefs.CONSUMER_SECRET);
        consumer.setMessageSigner(new HmacSha1MessageSigner());

        Log.v(TAG, "Starting google authentication activity");
        new RequestGoogleOAuth(this, provider, consumer).execute();
    }

    @Override
    @SuppressWarnings("unchecked")
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        final Uri uri = intent.getData();
        if (uri != null && uri.getScheme().equals(OAuthPrefs.CALLBACK_SCHEME)) {
            Log.v("OAUTH MAIN", "STARTING STAGE TWO");
            new ConfirmGoogleOAuthTask(this, provider, consumer).execute(uri);
            finish();
        }
    }

}
</code>```

The first OAuth stage

```<code>public class RequestGoogleOAuth extends OAuthGoogleTask {
    public static final String TAG = RequestGoogleOAuth.class.getSimpleName();

    public RequestGoogleOAuth(Context context, CommonsHttpOAuthProvider provider, CommonsHttpOAuthConsumer consumer) {
        super(context, provider, consumer);
    }

    protected Object doInBackground(Object... params) {
        final String TAG = getClass().getName();
        try {
            final String url = provider.retrieveRequestToken(consumer, OAuthPrefs.CALLBACK_URL);
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
                    & Intent.FLAG_ACTIVITY_NO_HISTORY & Intent.FLAG_FROM_BACKGROUND);
            context.startActivity(intent);
            Log.v(TAG, "Request google authentication");
        } catch (Exception e) {
            Log.e(TAG, "ERROR during google authentication request", e);
        }
        return null;
    }
}
</code>```

The second OAuth stage and attempt to access google tasks

```<code>public class ConfirmGoogleOAuthTask extends OAuthGoogleTask {
    public ConfirmGoogleOAuthTask(Context context, CommonsHttpOAuthProvider provider, CommonsHttpOAuthConsumer consumer) {
        super(context, provider, consumer);
    }

    @Override
    public Object doInBackground(Object... params) {
        final Uri uri = (Uri) params[0];
        final String TAG = getClass().getName();

        final SharedPreferences prefs = context.getSharedPreferences(OAuthPrefs.PREF_NAME, Context.MODE_PRIVATE);
        final String oauthVerifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);

        try {
            provider.retrieveAccessToken(consumer, oauthVerifier);
            final Editor edit = prefs.edit();
            edit.putString(OAuth.OAUTH_TOKEN, consumer.getToken());
            edit.putString(OAuth.OAUTH_TOKEN_SECRET, consumer.getTokenSecret());
            edit.commit();

            CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(OAuthPrefs.CONSUMER_KEY, OAuthPrefs.CONSUMER_SECRET);
            consumer.setMessageSigner(new HmacSha1MessageSigner());
            consumer.setTokenWithSecret(consumer.getToken(), consumer.getTokenSecret());

            HttpClient httpClient = HttpUtils.createHttpClient();
            HttpGet httpGet = new HttpGet(consumer.sign("https://mail.google.com/tasks/ig"));
            HttpResponse response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            Log.d(TAG, "Status code = " + statusCode);
            if (statusCode == HttpStatus.SC_OK) {
                String xml = ConvertUtils.convertStreamToString(response.getEntity().getContent(), true);
                Log.d(TAG, "XML = " + xml);
            }

            Log.v(TAG, "Successfully receive access token");
        } catch (Exception e) {
            Log.e(TAG, "ERROR during request for access token", e);
        }
        return null;
    }
}
</code>```

At this line:

```<code>String xml = ConvertUtils.convertStreamToString(response.getEntity().getContent(), true);
                    Log.d(TAG, "XML = " + xml);
</code>```

I can see that I receive "Login page"

I think the reason is that google doesn't provide access to this service and even I've already authenticated with OAuth it restricts my access to this resource (even I've defined scope as https://mail.google.com/). I am not sure how to implement it right now but it looks like I need to simulate browser exactly how it interacts with google (retrieve and send appropriate coockies). But I am asking, because I am not sure how to be int this situation, because as I've mentioned google tasks API has no public API (soap, rest or any other) so it's not obvious for me how to implement client for this feature...

If somebody has examples where app access google resources without public API I will be very happy to see that.

Thanks, hoply somebody knows the answer!

答:
[updated on 5/11 to recommend the API, 4/6 to use normal ClientLogin instead of cookies]

there's now a Google Tasks API! use that instead, it's a lot easier and your code will be more maintainable. consider the rest of this answer for posterity only.

unfortunately, you're on the right track. there's no API for google tasks at all yet, OAuth or otherwise, so you'll have to do a bit of HTML scraping. :/ afaik, that's what all other third party tasks clients do right now. ClientLogin does work for auth, though, so that's something at least.

here's some shell script code that does this: http://privacylog.blogspot.com/2010/09/updated-google-tasks-api.html . details below.

first, POST to www.google.com/accounts/ClientLogin as described in http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html#Request to get an auth token. use goanna_mobile as the service name. (this is important!)

then, GET https://mail.google.com/tasks/m and pass the Authorization:GoogleLogin header with the auth token you received above. you'll get HTML back. extract the ids of the individual task lists. they're of the form 04291568652951293844:0:0.

you'll then send POSTs with JSON-encoded body to https://mail.google.com/tasks/r/d to get the contents of each list. here's an example body:

```<code>r={action_list:
   [{action_type: get_all,
     action_id: 5,
     list_id: 0429158965...:0:0,
     get_deleted: false,
     date_start: 1969-12-31,
     get_archived: true
    }],
   client_version: 1256686
  }
</code>```

important notes:

the latest_sync_point: 0 to get all tasks

the = in r= is not url encoded to r%3D

include the header 'AT: 1'. without it tasks returns 401 Unauthorized.

the output is more JSON, e.g.:

```<code>{latest_sync_point: 1263000002293000, response_time:1263077227, results:[], tasks:
  [{id: 04291589652955....:0:38,
    last_modified: 1263000002281,
    name: foo bar
    notes: ,
    type: TASK,
    deleted: false,
    list_id: [0429158965...:0:0],
    completed: false
   },
   {id: 0429158965295...:0:37,
    last_modified: 1262929947949,
    name: baz
    notes: ,
    type: TASK,
    deleted:false,
    list_id: [0429158965295...:0:0],
    completed: false
   },
   ...
</code>```

Body:
As google tasks has no public api I want to write workaround and request data like a browser and then parse results to further display.

To access data I've implemented a OAuth authentication with google to access this url: https://mail.google.com/

For OAuth I've used sign-post library and it works well.

The problem is when I am trying to access https://mail.google.com/tasks/ig with signed request it returns me login page instead of desired list with tasks.

To be more specific here is my code:

public class GoogleOAuthActivity extends Activity {
    private static final String TAG = GoogleOAuthActivity.class.getSimpleName();
    private CommonsHttpOAuthProvider provider;
    private CommonsHttpOAuthConsumer consumer;

    @Override
    @SuppressWarnings("unchecked")
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        provider = new CommonsHttpOAuthProvider(OAuthPrefs.GET_REQUEST_TOKEN_URL, OAuthPrefs.GET_ACCESS_TOKEN_URL,
                OAuthPrefs.TOKEN_AUTHORIZATION_URL);
        consumer = new CommonsHttpOAuthConsumer(OAuthPrefs.CONSUMER_KEY, OAuthPrefs.CONSUMER_SECRET);
        consumer.setMessageSigner(new HmacSha1MessageSigner());

        Log.v(TAG, "Starting google authentication activity");
        new RequestGoogleOAuth(this, provider, consumer).execute();
    }

    @Override
    @SuppressWarnings("unchecked")
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        final Uri uri = intent.getData();
        if (uri != null && uri.getScheme().equals(OAuthPrefs.CALLBACK_SCHEME)) {
            Log.v("OAUTH MAIN", "STARTING STAGE TWO");
            new ConfirmGoogleOAuthTask(this, provider, consumer).execute(uri);
            finish();
        }
    }

}

The first OAuth stage

public class RequestGoogleOAuth extends OAuthGoogleTask {
    public static final String TAG = RequestGoogleOAuth.class.getSimpleName();

    public RequestGoogleOAuth(Context context, CommonsHttpOAuthProvider provider, CommonsHttpOAuthConsumer consumer) {
        super(context, provider, consumer);
    }

    protected Object doInBackground(Object... params) {
        final String TAG = getClass().getName();
        try {
            final String url = provider.retrieveRequestToken(consumer, OAuthPrefs.CALLBACK_URL);
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
                    & Intent.FLAG_ACTIVITY_NO_HISTORY & Intent.FLAG_FROM_BACKGROUND);
            context.startActivity(intent);
            Log.v(TAG, "Request google authentication");
        } catch (Exception e) {
            Log.e(TAG, "ERROR during google authentication request", e);
        }
        return null;
    }
}

The second OAuth stage and attempt to access google tasks

public class ConfirmGoogleOAuthTask extends OAuthGoogleTask {
    public ConfirmGoogleOAuthTask(Context context, CommonsHttpOAuthProvider provider, CommonsHttpOAuthConsumer consumer) {
        super(context, provider, consumer);
    }

    @Override
    public Object doInBackground(Object... params) {
        final Uri uri = (Uri) params[0];
        final String TAG = getClass().getName();

        final SharedPreferences prefs = context.getSharedPreferences(OAuthPrefs.PREF_NAME, Context.MODE_PRIVATE);
        final String oauthVerifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);

        try {
            provider.retrieveAccessToken(consumer, oauthVerifier);
            final Editor edit = prefs.edit();
            edit.putString(OAuth.OAUTH_TOKEN, consumer.getToken());
            edit.putString(OAuth.OAUTH_TOKEN_SECRET, consumer.getTokenSecret());
            edit.commit();

            CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(OAuthPrefs.CONSUMER_KEY, OAuthPrefs.CONSUMER_SECRET);
            consumer.setMessageSigner(new HmacSha1MessageSigner());
            consumer.setTokenWithSecret(consumer.getToken(), consumer.getTokenSecret());

            HttpClient httpClient = HttpUtils.createHttpClient();
            HttpGet httpGet = new HttpGet(consumer.sign("https://mail.google.com/tasks/ig"));
            HttpResponse response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            Log.d(TAG, "Status code = " + statusCode);
            if (statusCode == HttpStatus.SC_OK) {
                String xml = ConvertUtils.convertStreamToString(response.getEntity().getContent(), true);
                Log.d(TAG, "XML = " + xml);
            }

            Log.v(TAG, "Successfully receive access token");
        } catch (Exception e) {
            Log.e(TAG, "ERROR during request for access token", e);
        }
        return null;
    }
}

At this line:

String xml = ConvertUtils.convertStreamToString(response.getEntity().getContent(), true);
                    Log.d(TAG, "XML = " + xml);

I can see that I receive "Login page"

I think the reason is that google doesn't provide access to this service and even I've already authenticated with OAuth it restricts my access to this resource (even I've defined scope as https://mail.google.com/). I am not sure how to implement it right now but it looks like I need to simulate browser exactly how it interacts with google (retrieve and send appropriate coockies). But I am asking, because I am not sure how to be int this situation, because as I've mentioned google tasks API has no public API (soap, rest or any other) so it's not obvious for me how to implement client for this feature...

If somebody has examples where app access google resources without public API I will be very happy to see that.

Thanks, hoply somebody knows the answer!

Body:
[updated on 5/11 to recommend the API, 4/6 to use normal ClientLogin instead of cookies]

there's now a Google Tasks API! use that instead, it's a lot easier and your code will be more maintainable. consider the rest of this answer for posterity only.

unfortunately, you're on the right track. there's no API for google tasks at all yet, OAuth or otherwise, so you'll have to do a bit of HTML scraping. :/ afaik, that's what all other third party tasks clients do right now. ClientLogin does work for auth, though, so that's something at least.

here's some shell script code that does this: http://privacylog.blogspot.com/2010/09/updated-google-tasks-api.html . details below.

first, POST to www.google.com/accounts/ClientLogin as described in http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html#Request to get an auth token. use goanna_mobile as the service name. (this is important!)

then, GET https://mail.google.com/tasks/m and pass the Authorization:GoogleLogin header with the auth token you received above. you'll get HTML back. extract the ids of the individual task lists. they're of the form 04291568652951293844:0:0.

you'll then send POSTs with JSON-encoded body to https://mail.google.com/tasks/r/d to get the contents of each list. here's an example body:

r={action_list:
   [{action_type: get_all,
     action_id: 5,
     list_id: 0429158965...:0:0,
     get_deleted: false,
     date_start: 1969-12-31,
     get_archived: true
    }],
   client_version: 1256686
  }

important notes:

the latest_sync_point: 0 to get all tasks

the = in r= is not url encoded to r%3D

include the header 'AT: 1'. without it tasks returns 401 Unauthorized.

the output is more JSON, e.g.:

{latest_sync_point: 1263000002293000, response_time:1263077227, results:[], tasks:
  [{id: 04291589652955....:0:38,
    last_modified: 1263000002281,
    name: foo bar
    notes: ,
    type: TASK,
    deleted: false,
    list_id: [0429158965...:0:0],
    completed: false
   },
   {id: 0429158965295...:0:37,
    last_modified: 1262929947949,
    name: baz
    notes: ,
    type: TASK,
    deleted:false,
    list_id: [0429158965295...:0:0],
    completed: false
   },
   ...


来源: stackexchange

问:
Method that takes in integers or strings. C++
So right now I'm trying to make a graphic C header file that could create shapes like triangle's, boxes, and circles in C++. Its supposed to help kids in my class, but I also want to be able for them to type stuff in the shapes. But I was wondering if there was a place holder for a integer in case you don't to cout<< a int.

For instance

the method (called up):

```<code> //goes to coordinates 5,6 (creates side of 5 with a char called 'X')
 triangle(5,6,5,'X',"",5);
</code>```

Will make a triangle with 2 sides of 5 units of X and have a regular base. But what if the user just wanted to print out the string w/o the integer. Then they would type

```<code>triangle(5,6,5,'X',"I love code", );
</code>```

But an error would pop up and say that it needs one more parameter.

I've done some searching on boolean methods, like in java when you can type

```<code>public static void randommethod bool(/*params*\){

  /*Enter code if its either true or false*/

}
</code>```

But I've come up empty with any trying to find a method like that in C++.

答:
Judging by the title you probably want to be able to pass either int or string which will be printed as message. You can template your triangle function to accept anything:

```<code>#include <iostream>

template <typename T>
void triangle(int x, int y, int z, char c, T anything)
{
    std::cout << anything << std::endl;
}

int main()
{
    triangle(5, 6, 5, 'X', "I love code");
    triangle(5, 6, 5, 'X', 5);

    return 0;
}
</code>```

Will print:

```<code>I love code
5
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So right now I'm trying to make a graphic C header file that could create shapes like triangle's, boxes, and circles in C++. Its supposed to help kids in my class, but I also want to be able for them to type stuff in the shapes. But I was wondering if there was a place holder for a integer in case you don't to cout<< a int.

For instance

the method (called up):

 //goes to coordinates 5,6 (creates side of 5 with a char called 'X')
 triangle(5,6,5,'X',"",5);

Will make a triangle with 2 sides of 5 units of X and have a regular base. But what if the user just wanted to print out the string w/o the integer. Then they would type

triangle(5,6,5,'X',"I love code", );

But an error would pop up and say that it needs one more parameter.

I've done some searching on boolean methods, like in java when you can type

public static void randommethod bool(/*params*\){

  /*Enter code if its either true or false*/

}

But I've come up empty with any trying to find a method like that in C++.

Body:
Judging by the title you probably want to be able to pass either int or string which will be printed as message. You can template your triangle function to accept anything:

#include <iostream>

template <typename T>
void triangle(int x, int y, int z, char c, T anything)
{
    std::cout << anything << std::endl;
}

int main()
{
    triangle(5, 6, 5, 'X', "I love code");
    triangle(5, 6, 5, 'X', 5);

    return 0;
}

Will print:

I love code
5


问:
Use Google Ads API PHP Client without composer?
Is it possible to use Google's API's without using a composer? When using shared hosting web servers one has not usually not access to use composer.

https://github.com/googleads/googleads-php-lib/blob/master/README.md

答:
Took me days to find a solution to this one.

Firstly, don't get the most recent Google API PHP Client.

The 2.x versions began using Composer, and frankly they also started becoming too big to be uploaded to a shared host. I'm sure hosts love that. For some, you then have to pay to get the PHP Client.

Upload the PHP Client, yes, but the two-year old version that came without Composer: google-api-php-client v1.1.8. Download the zip file, but you need only upload the content you see here under a folder called: Google

Next, follow this article, PHP server-side YouTube V3 OAuth API video upload guide, as your guide. He's using a even older version, but ignore that. This article will get you through it. It's a Life-saver.

I don't know why I couldn't get the autoload.php to work with its spl_autoload_register('google_api_php_client_autoload');. For now, I just determined what I needed through trial and error and included the following 'require statements' at the start of my code:

```<code><?php

require_once $_SERVER['DOCUMENT_ROOT'].'/src/Google/autoload.php';

require_once $_SERVER['DOCUMENT_ROOT'].'/src/Google/Config.php';

require_once $_SERVER['DOCUMENT_ROOT'].'/src/Google/Auth/Abstract.php';

require_once $_SERVER['DOCUMENT_ROOT'].'/src/Google/Auth/OAuth2.php';

require_once $_SERVER['DOCUMENT_ROOT'].'/src/Google/Http/Request.php';

require_once $_SERVER['DOCUMENT_ROOT'].'/src/Google/Utils.php';

require_once $_SERVER['DOCUMENT_ROOT'].'/src/Google/Client.php';

require_once $_SERVER['DOCUMENT_ROOT'].'/src/Google/Service/YouTube.php';

include_once($_SERVER['DOCUMENT_ROOT'].'/src/CookieAPI.php');

session_start();
</code>```

There!

You win!

Body:
Took me days to find a solution to this one.

Firstly, don't get the most recent Google API PHP Client.

The 2.x versions began using Composer, and frankly they also started becoming too big to be uploaded to a shared host. I'm sure hosts love that. For some, you then have to pay to get the PHP Client.

Upload the PHP Client, yes, but the two-year old version that came without Composer: google-api-php-client v1.1.8. Download the zip file, but you need only upload the content you see here under a folder called: Google

Next, follow this article, PHP server-side YouTube V3 OAuth API video upload guide, as your guide. He's using a even older version, but ignore that. This article will get you through it. It's a Life-saver.

I don't know why I couldn't get the autoload.php to work with its spl_autoload_register('google_api_php_client_autoload');. For now, I just determined what I needed through trial and error and included the following 'require statements' at the start of my code:

<?php

require_once $_SERVER['DOCUMENT_ROOT'].'/src/Google/autoload.php';

require_once $_SERVER['DOCUMENT_ROOT'].'/src/Google/Config.php';

require_once $_SERVER['DOCUMENT_ROOT'].'/src/Google/Auth/Abstract.php';

require_once $_SERVER['DOCUMENT_ROOT'].'/src/Google/Auth/OAuth2.php';

require_once $_SERVER['DOCUMENT_ROOT'].'/src/Google/Http/Request.php';

require_once $_SERVER['DOCUMENT_ROOT'].'/src/Google/Utils.php';

require_once $_SERVER['DOCUMENT_ROOT'].'/src/Google/Client.php';

require_once $_SERVER['DOCUMENT_ROOT'].'/src/Google/Service/YouTube.php';

include_once($_SERVER['DOCUMENT_ROOT'].'/src/CookieAPI.php');

session_start();

There!

You win!


问:
How to put some array elements from the middle to last in Javascript
I have this following JS object array whose elements are just columns of a HTML table :

```<code>var my_cols = [
  {
    "id": "name",
    "header": [
      "Name",
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "type",
    "header": [
      "Type",
      {
        "content": "textFilter"
      }
    ],
    "width": 180,
    "sort": "string"
  },
  {
    "id": "dob",
    "header": [
      "DOB",
      {
        "content": "textFilter"
      }
    ],
    "width": 100,
    "sort": "string"
  },
  {
    "id": "merged_a",
    "header": [
      {
        "text": "merged_a",
        "colspan": 3
      },
      {
        "text": "port"
      },
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "merged_b",
    "header": [
      null,
      {
        "text": "merged_b"
      },
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "merged_c",
    "header": [
      null,
      {
        "text": "merged_c"
      },
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "place",
    "header": [
      "place",
      {
        "content": "textFilter"
      }
    ],
    "width": 300,
    "sort": "string"
  },
  {
    "id": "address",
    "header": [
      "address",
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "phone",
    "header": [
      "phone",
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  }
];
</code>```

I want to put elements with id as 'merged_a' , 'merged_b', and 'merged_c' at the end of the entire array my_cols. I have written the below code so far, however it is not giving me the exact result:

```<code>var my_cols= [{"id":"name","header":["Name",{"content":"textFilter"}],"width":200,"sort":"string"},
{"id":"type","header":["Type",{"content":"textFilter"}],"width":180,"sort":"string"},
{"id":"dob","header":["DOB",{"content":"textFilter"}],"width":100,"sort":"string"},
{"id":"merged_a","header":[{"text":"merged_a","colspan":3},{"text":"port"},{"content":"textFilter"}],"width":200,"sort":"string"},
{"id":"merged_b","header":[null,{"text":"merged_b"},{"content":"textFilter"}],"width":200,"sort":"string"},
{"id":"merged_c","header":[null,{"text":"merged_c"},{"content":"textFilter"}],"width":200,"sort":"string"},
{"id":"place","header":["place",{"content":"textFilter"}],"width":300,"sort":"string"},
{"id":"address","header":["address",{"content":"textFilter"}],"width":200,"sort":"string"},
{"id":"phone","header":["phone",{"content":"textFilter"}],"width":200,"sort":"string"}];
</code>```

My effort

 var my_cols = [
   { "id": "name", "header": [ "Name", { "content": "textFilter" } ], "width": 200, "sort": "string" },
   { "id": "type", "header": [ "Type", { "content": "textFilter" } ], "width": 180, "sort": "string" },
   { "id": "dob", "header": [ "DOB", { "content": "textFilter" } ], "width": 100, "sort": "string" },
   { "id": "merged_a", "header": [{ "text": "merged_a", "colspan": 3 }, { "text": "port" }, { "content": "textFilter" } ], "width": 200, "sort": "string" },
   { "id": "merged_b", "header": [ null, { "text": "merged_b" }, { "content": "textFilter" } ], "width": 200, "sort": "string" },
   { "id": "merged_c", "header": [ null, { "text": "merged_c" }, { "content": "textFilter" } ], "width": 200, "sort": "string" },
   { "id": "place", "header": [ "place", { "content": "textFilter" } ], "width": 300, "sort": "string" },
   { "id": "address", "header": [ "address", { "content": "textFilter" } ], "width": 200, "sort": "string" },
   { "id": "phone", "header": [ "phone", { "content": "textFilter" } ], "width": 200, "sort": "string" }
 ];

for (var i in my_cols) {

  var col = my_cols[i];
  var a_col;
  var b_col;
  var c_col;
  if (col.hasOwnProperty('id')) {
    if (col['id'] == 'merged_a') {
      a_col = my_cols.splice(i, 1);
    }
    if (col['id'] == 'merged_b') {
      b_col = my_cols.splice(i, 1);
    }
    if (col['id'] == 'merged_c') {
      c_col = my_cols.splice(i, 1);
    }
  }

}

my_cols.push(a_col);
my_cols.push(b_col);
my_cols.push(c_col);

console.log("my_cols = " + JSON.stringify(my_cols));```

答:
Maybe not the most elegant way, but do the job.

The problem is when you splice the array, the index harms. This is why you not get the  merged_b. And move out var a_col... from the cycle.

```<code>  var my_cols = [
    {"id": "name", "header": ["Name", {"content": "textFilter"}], "width": 200, "sort": "string"},
    {"id": "type", "header": ["Type", {"content": "textFilter"}], "width": 180, "sort": "string"},
    {"id": "dob", "header": ["DOB", {"content": "textFilter"}], "width": 100, "sort": "string"},
    {"id": "merged_a", "header": [{"text": "merged_a", "colspan": 3}, {"text": "port"}, {"content": "textFilter"}], "width": 200, "sort": "string"},
    {"id": "merged_b", "header": [null, {"text": "merged_b"}, {"content": "textFilter"}], "width": 200, "sort": "string"},
    {"id": "merged_c", "header": [null, {"text": "merged_c"}, {"content": "textFilter"}], "width": 200, "sort": "string"},
    {"id": "place", "header": ["place", {"content": "textFilter"}], "width": 300, "sort": "string"},
    {"id": "address", "header": ["address", {"content": "textFilter"}], "width": 200, "sort": "string"},
    {"id": "phone", "header": ["phone", {"content": "textFilter"}], "width": 200, "sort": "string"}
  ];

  var a_col;
  var b_col;
  var c_col;

  var indexes = {};

  for (var i in my_cols) {
    var col = my_cols[i];
    if (col.hasOwnProperty('id')) {
      if (col['id'] === 'merged_a') {
        a_col = my_cols[i];
        indexes.a = i;
      }
      if (col['id'] === 'merged_b') {
        b_col = my_cols[i];
        indexes.b = i;
      }
      if (col['id'] === 'merged_c') {
        c_col = my_cols[i];
        indexes.c = i;
      }
    }
  }

  indexes = dict_reverse(indexes)
  for (i in indexes) {
     my_cols.splice(indexes[i],1);
  }

  my_cols.push(a_col);
  my_cols.push(b_col);
  my_cols.push(c_col);

  console.log(my_cols);

  function dict_reverse(obj) {
    new_obj = {}
    rev_obj = Object.keys(obj).reverse();
    rev_obj.forEach(function (i) {
      new_obj[i] = obj[i];
    });
    return new_obj;
  }
</code>```

Body:
I have this following JS object array whose elements are just columns of a HTML table :

var my_cols = [
  {
    "id": "name",
    "header": [
      "Name",
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "type",
    "header": [
      "Type",
      {
        "content": "textFilter"
      }
    ],
    "width": 180,
    "sort": "string"
  },
  {
    "id": "dob",
    "header": [
      "DOB",
      {
        "content": "textFilter"
      }
    ],
    "width": 100,
    "sort": "string"
  },
  {
    "id": "merged_a",
    "header": [
      {
        "text": "merged_a",
        "colspan": 3
      },
      {
        "text": "port"
      },
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "merged_b",
    "header": [
      null,
      {
        "text": "merged_b"
      },
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "merged_c",
    "header": [
      null,
      {
        "text": "merged_c"
      },
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "place",
    "header": [
      "place",
      {
        "content": "textFilter"
      }
    ],
    "width": 300,
    "sort": "string"
  },
  {
    "id": "address",
    "header": [
      "address",
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "phone",
    "header": [
      "phone",
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  }
];

I want to put elements with id as 'merged_a' , 'merged_b', and 'merged_c' at the end of the entire array my_cols. I have written the below code so far, however it is not giving me the exact result:

var my_cols= [{"id":"name","header":["Name",{"content":"textFilter"}],"width":200,"sort":"string"},
{"id":"type","header":["Type",{"content":"textFilter"}],"width":180,"sort":"string"},
{"id":"dob","header":["DOB",{"content":"textFilter"}],"width":100,"sort":"string"},
{"id":"merged_a","header":[{"text":"merged_a","colspan":3},{"text":"port"},{"content":"textFilter"}],"width":200,"sort":"string"},
{"id":"merged_b","header":[null,{"text":"merged_b"},{"content":"textFilter"}],"width":200,"sort":"string"},
{"id":"merged_c","header":[null,{"text":"merged_c"},{"content":"textFilter"}],"width":200,"sort":"string"},
{"id":"place","header":["place",{"content":"textFilter"}],"width":300,"sort":"string"},
{"id":"address","header":["address",{"content":"textFilter"}],"width":200,"sort":"string"},
{"id":"phone","header":["phone",{"content":"textFilter"}],"width":200,"sort":"string"}];

My effort

 var my_cols = [
   { "id": "name", "header": [ "Name", { "content": "textFilter" } ], "width": 200, "sort": "string" },
   { "id": "type", "header": [ "Type", { "content": "textFilter" } ], "width": 180, "sort": "string" },
   { "id": "dob", "header": [ "DOB", { "content": "textFilter" } ], "width": 100, "sort": "string" },
   { "id": "merged_a", "header": [{ "text": "merged_a", "colspan": 3 }, { "text": "port" }, { "content": "textFilter" } ], "width": 200, "sort": "string" },
   { "id": "merged_b", "header": [ null, { "text": "merged_b" }, { "content": "textFilter" } ], "width": 200, "sort": "string" },
   { "id": "merged_c", "header": [ null, { "text": "merged_c" }, { "content": "textFilter" } ], "width": 200, "sort": "string" },
   { "id": "place", "header": [ "place", { "content": "textFilter" } ], "width": 300, "sort": "string" },
   { "id": "address", "header": [ "address", { "content": "textFilter" } ], "width": 200, "sort": "string" },
   { "id": "phone", "header": [ "phone", { "content": "textFilter" } ], "width": 200, "sort": "string" }
 ];

for (var i in my_cols) {

  var col = my_cols[i];
  var a_col;
  var b_col;
  var c_col;
  if (col.hasOwnProperty('id')) {
    if (col['id'] == 'merged_a') {
      a_col = my_cols.splice(i, 1);
    }
    if (col['id'] == 'merged_b') {
      b_col = my_cols.splice(i, 1);
    }
    if (col['id'] == 'merged_c') {
      c_col = my_cols.splice(i, 1);
    }
  }

}

my_cols.push(a_col);
my_cols.push(b_col);
my_cols.push(c_col);

console.log("my_cols = " + JSON.stringify(my_cols));

Body:
Maybe not the most elegant way, but do the job.

The problem is when you splice the array, the index harms. This is why you not get the  merged_b. And move out var a_col... from the cycle.

  var my_cols = [
    {"id": "name", "header": ["Name", {"content": "textFilter"}], "width": 200, "sort": "string"},
    {"id": "type", "header": ["Type", {"content": "textFilter"}], "width": 180, "sort": "string"},
    {"id": "dob", "header": ["DOB", {"content": "textFilter"}], "width": 100, "sort": "string"},
    {"id": "merged_a", "header": [{"text": "merged_a", "colspan": 3}, {"text": "port"}, {"content": "textFilter"}], "width": 200, "sort": "string"},
    {"id": "merged_b", "header": [null, {"text": "merged_b"}, {"content": "textFilter"}], "width": 200, "sort": "string"},
    {"id": "merged_c", "header": [null, {"text": "merged_c"}, {"content": "textFilter"}], "width": 200, "sort": "string"},
    {"id": "place", "header": ["place", {"content": "textFilter"}], "width": 300, "sort": "string"},
    {"id": "address", "header": ["address", {"content": "textFilter"}], "width": 200, "sort": "string"},
    {"id": "phone", "header": ["phone", {"content": "textFilter"}], "width": 200, "sort": "string"}
  ];

  var a_col;
  var b_col;
  var c_col;

  var indexes = {};

  for (var i in my_cols) {
    var col = my_cols[i];
    if (col.hasOwnProperty('id')) {
      if (col['id'] === 'merged_a') {
        a_col = my_cols[i];
        indexes.a = i;
      }
      if (col['id'] === 'merged_b') {
        b_col = my_cols[i];
        indexes.b = i;
      }
      if (col['id'] === 'merged_c') {
        c_col = my_cols[i];
        indexes.c = i;
      }
    }
  }

  indexes = dict_reverse(indexes)
  for (i in indexes) {
     my_cols.splice(indexes[i],1);
  }

  my_cols.push(a_col);
  my_cols.push(b_col);
  my_cols.push(c_col);

  console.log(my_cols);

  function dict_reverse(obj) {
    new_obj = {}
    rev_obj = Object.keys(obj).reverse();
    rev_obj.forEach(function (i) {
      new_obj[i] = obj[i];
    });
    return new_obj;
  }


问:
Generated image not showing in print-out of report
I am trying to print out a generated barcode on a report using RDLC, but all I get is a small red X instead.

Here's my object.

```<code>    [XmlType]
[XmlRoot(IsNullable = false)]
[Serializable]
public class Voucher
{
    [XmlIgnore]
    public Bitmap BarcodeImg { get; set; }

    [XmlElement("BarcodeImg")]
    public byte[] BarcodeImgSerialized
    {
        get
        {
            if (BarcodeImg == null) return new byte[] { };
            using (var Stream = new MemoryStream())
            {
                BarcodeImg.Save(Stream, ImageFormat.Bmp);
                return Stream.ToArray();
            }
        }
        set
        {
            if (value == null) { BarcodeImg = new Bitmap(50, 50); }
            else
            {
                using (var Stream = new MemoryStream(value))
                {
                    BarcodeImg = new Bitmap(Stream);
                }
            }
        }
    }

    public string BarcodeStr { get; set; } = string.Empty;

    public Voucher() { }
}
</code>```

In my report, called "Report_Voucher", I have the Voucher object listed as a dataset. My image is of the name "Barcode", the MIMEType being image/BMP, an external image source, and the expression being

```<code>=First(Fields!BarcodeImg.Value, "Voucher")
</code>```

I've also tried BarcodeImgSerialized.

Here's my form code...

```<code>public partial class Form_Main : Form
{
    LocalReport Report;
    List<Stream> Streams = new List<Stream>();

    public Form_Main()
    {
        InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        Voucher V = CreateVoucher();
        DataSet Set = CreateDataSet(V);

        this.RV_Main.ProcessingMode = ProcessingMode.Local;
        this.Report = RV_Main.LocalReport;
        Report.ReportPath = @"..\..\Report_Voucher.rdlc";
        Report.DataSources.Add(new ReportDataSource("Voucher", Set.Tables[0]));
        var DeviceInfo =
            @"<DeviceInfo>
                <OutputFormat>EMF</OutputFormat>
                <PageWidth>8.5in</PageWidth>
                <PageHeight>11in</PageHeight>
                <MarginTop>0.25in</MarginTop>
                <MarginLeft>0.25in</MarginLeft>
                <MarginRight>0.25in</MarginRight>
                <MarginBottom>0.25in</MarginBottom>
            </DeviceInfo>";
        var Warnings = new Warning[] { };
        Report.EnableExternalImages = true;
        Report.Render("Image", DeviceInfo, CreateStream, out Warnings);
        Streams.ForEach(x => x.Position = 0);
        this.RV_Main.Refresh();
    }
    private DataSet CreateDataSet(Voucher Voucher)
    {
        var Set = new DataSet();
        var Serializer = new XmlSerializer(typeof(Voucher));

        using (var MStream = new MemoryStream())
        {
            Serializer.Serialize(MStream, Voucher);
            MStream.Seek(0, SeekOrigin.Begin);
            Set.ReadXml(MStream);
        }

        return Set;
    }
    private Voucher CreateVoucher()
    {
        var BarcodeStr = "12345678901234";
        var Writer = new BarcodeWriter
        {
            Format = BarcodeFormat.ITF,
            Options = new EncodingOptions
            {
                Height = 80,
                Width = 400,
                Margin = 0,
                PureBarcode = true,
            }
        };
        var Barcode = Writer.Write(BarcodeStr);

        var Voucher = new Voucher()
        {
            BarcodeStr = BarcodeStr,
            BarcodeImg = Barcode,
        };

        return Voucher;
    }
    private Stream CreateStream(string name, string fileNameExtension, Encoding encoding, string mimeType, bool willSeek)
    {
        var stream = new MemoryStream();
        Streams.Add(stream);
        return stream;
    }
    private void Btn_PrintReport_Click(object sender, EventArgs e)
    {
        if (this.Streams == null || this.Streams.Count == 0) { return; }
        var Document = new PrintDocument();
        Document.DefaultPageSettings.Landscape = true;
        if (!Document.PrinterSettings.IsValid) { return; }
        else
        {
            Document.PrintPage += Document_PrintPage;
            Document.Print();
        }
    }
    private void Document_PrintPage(object sender, PrintPageEventArgs e)
    {
        var Stream = this.Streams.First();
        var Page = new Metafile(Stream);

        var AdjustedRect = new Rectangle(
            e.PageBounds.Left - (int)e.PageSettings.HardMarginX,
            e.PageBounds.Top - (int)e.PageSettings.HardMarginY,
            e.PageBounds.Width,
            e.PageBounds.Height);

        e.Graphics.FillRectangle(Brushes.White, AdjustedRect);
        e.Graphics.DrawImage(Page, AdjustedRect);
        Stream.Dispose();
        Page.Dispose();
    }
}
</code>```

I've tried an obnoxious number of tweaks to try to get this barcode to show up, from how the serialization was done, what the report captures as the variable for the image (byte arrays, object, Bitmap), etc., and nothing I've read seems to be a fix. Does anyone know of a fix for this?

答:
The solution was to wrap the expression in the FromBase64String call:</p>

```<code>=System.Convert.FromBase64String(First(Fields!BarcodeImg.Value, "Voucher"));
</code>```

Body:
I am trying to print out a generated barcode on a report using RDLC, but all I get is a small red X instead.

Here's my object.

    [XmlType]
[XmlRoot(IsNullable = false)]
[Serializable]
public class Voucher
{
    [XmlIgnore]
    public Bitmap BarcodeImg { get; set; }

    [XmlElement("BarcodeImg")]
    public byte[] BarcodeImgSerialized
    {
        get
        {
            if (BarcodeImg == null) return new byte[] { };
            using (var Stream = new MemoryStream())
            {
                BarcodeImg.Save(Stream, ImageFormat.Bmp);
                return Stream.ToArray();
            }
        }
        set
        {
            if (value == null) { BarcodeImg = new Bitmap(50, 50); }
            else
            {
                using (var Stream = new MemoryStream(value))
                {
                    BarcodeImg = new Bitmap(Stream);
                }
            }
        }
    }

    public string BarcodeStr { get; set; } = string.Empty;

    public Voucher() { }
}

In my report, called "Report_Voucher", I have the Voucher object listed as a dataset. My image is of the name "Barcode", the MIMEType being image/BMP, an external image source, and the expression being

=First(Fields!BarcodeImg.Value, "Voucher")

I've also tried BarcodeImgSerialized.

Here's my form code...

public partial class Form_Main : Form
{
    LocalReport Report;
    List<Stream> Streams = new List<Stream>();

    public Form_Main()
    {
        InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        Voucher V = CreateVoucher();
        DataSet Set = CreateDataSet(V);

        this.RV_Main.ProcessingMode = ProcessingMode.Local;
        this.Report = RV_Main.LocalReport;
        Report.ReportPath = @"..\..\Report_Voucher.rdlc";
        Report.DataSources.Add(new ReportDataSource("Voucher", Set.Tables[0]));
        var DeviceInfo =
            @"<DeviceInfo>
                <OutputFormat>EMF</OutputFormat>
                <PageWidth>8.5in</PageWidth>
                <PageHeight>11in</PageHeight>
                <MarginTop>0.25in</MarginTop>
                <MarginLeft>0.25in</MarginLeft>
                <MarginRight>0.25in</MarginRight>
                <MarginBottom>0.25in</MarginBottom>
            </DeviceInfo>";
        var Warnings = new Warning[] { };
        Report.EnableExternalImages = true;
        Report.Render("Image", DeviceInfo, CreateStream, out Warnings);
        Streams.ForEach(x => x.Position = 0);
        this.RV_Main.Refresh();
    }
    private DataSet CreateDataSet(Voucher Voucher)
    {
        var Set = new DataSet();
        var Serializer = new XmlSerializer(typeof(Voucher));

        using (var MStream = new MemoryStream())
        {
            Serializer.Serialize(MStream, Voucher);
            MStream.Seek(0, SeekOrigin.Begin);
            Set.ReadXml(MStream);
        }

        return Set;
    }
    private Voucher CreateVoucher()
    {
        var BarcodeStr = "12345678901234";
        var Writer = new BarcodeWriter
        {
            Format = BarcodeFormat.ITF,
            Options = new EncodingOptions
            {
                Height = 80,
                Width = 400,
                Margin = 0,
                PureBarcode = true,
            }
        };
        var Barcode = Writer.Write(BarcodeStr);

        var Voucher = new Voucher()
        {
            BarcodeStr = BarcodeStr,
            BarcodeImg = Barcode,
        };

        return Voucher;
    }
    private Stream CreateStream(string name, string fileNameExtension, Encoding encoding, string mimeType, bool willSeek)
    {
        var stream = new MemoryStream();
        Streams.Add(stream);
        return stream;
    }
    private void Btn_PrintReport_Click(object sender, EventArgs e)
    {
        if (this.Streams == null || this.Streams.Count == 0) { return; }
        var Document = new PrintDocument();
        Document.DefaultPageSettings.Landscape = true;
        if (!Document.PrinterSettings.IsValid) { return; }
        else
        {
            Document.PrintPage += Document_PrintPage;
            Document.Print();
        }
    }
    private void Document_PrintPage(object sender, PrintPageEventArgs e)
    {
        var Stream = this.Streams.First();
        var Page = new Metafile(Stream);

        var AdjustedRect = new Rectangle(
            e.PageBounds.Left - (int)e.PageSettings.HardMarginX,
            e.PageBounds.Top - (int)e.PageSettings.HardMarginY,
            e.PageBounds.Width,
            e.PageBounds.Height);

        e.Graphics.FillRectangle(Brushes.White, AdjustedRect);
        e.Graphics.DrawImage(Page, AdjustedRect);
        Stream.Dispose();
        Page.Dispose();
    }
}

I've tried an obnoxious number of tweaks to try to get this barcode to show up, from how the serialization was done, what the report captures as the variable for the image (byte arrays, object, Bitmap), etc., and nothing I've read seems to be a fix. Does anyone know of a fix for this?

Body:
The solution was to wrap the expression in the FromBase64String call:

=System.Convert.FromBase64String(First(Fields!BarcodeImg.Value, "Voucher"));


问:
Server-GUI freezes when waiting for connections
I'm trying to create a multithreaded server, connecting to it through a client works fine, but the GUI is frozen. Probably since it is constantly listening for incoming connections it is stuck in a while loop. So, do i need to create a thread for the multithreaded server (which itself will be creating threads) or how would i go about fixing this?

MultiThreadedServer:

```<code>public class MultiThreadServer{

    public static final int PORT = 2000;
    //function below is called by the GUI.
    public void startServer() throws IOException {
        ServerSocket s = new ServerSocket(PORT);
        System.out.println("Server socket: " + s);
        System.out.println("Server listening...");
        try { while(true) {
            // Blocks until a connection occurs:
            Socket socket = s.accept();
            System.out.println("Connection accepted.");
            System.out.println("The new socket: " + socket);
            try {
                ClientThread t = new ClientThread(socket);
                System.out.println("New thread started.");
                System.out.println("The new thread: " + t);

                }
                catch(IOException e) {
                    System.out.println("===Socket Closed===");
                    socket.close();
                }
            }
        }
        finally { System.out.println("===ServerSocket Closed==="); s.close(); }
        }
    }
}
</code>```

ServerGUI:

```<code>public class ServerGUI extends Application implements Initializable{

    @FXML private MenuItem startConn;

    @Override
    public void start(Stage stage) throws Exception {
        try {
            Parent root = FXMLLoader.load(getClass().getResource("ServerGUI.fxml"));
            stage.setScene(new Scene(root));
            stage.show();
        } catch (IOException ex) {
            ex.printStackTrace();
            System.exit(0);
        }
    }
    public static void main(String[] args) {
        launch(args);
    }
    @Override
    public void initialize(URL location, ResourceBundle resources) {

        startConn.setOnAction(e -> {
            try {
                MultiThreadServer mts = new MultiThreadServer();
                mts.startServer();
                System.out.println("Starting Server...");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        });
    }
}
</code>```

答:
As i suspected, a new thread for the server was required.

MultiThreadServer:

public Runnable startServer() throws IOException {

After making the function Runnable i added this:

ServerGUI:

```<code>startConn.setOnAction(e -> {
            Thread t1 = new Thread(new Runnable() {
                public void run()
                {
                    MultiThreadServer mts = new MultiThreadServer();

                    try {
                        mts.startServer();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }});
                t1.start();
</code>```

Thanks to user BackSlash for providing reference-link.

Body:
I'm trying to create a multithreaded server, connecting to it through a client works fine, but the GUI is frozen. Probably since it is constantly listening for incoming connections it is stuck in a while loop. So, do i need to create a thread for the multithreaded server (which itself will be creating threads) or how would i go about fixing this?

MultiThreadedServer:

public class MultiThreadServer{

    public static final int PORT = 2000;
    //function below is called by the GUI.
    public void startServer() throws IOException {
        ServerSocket s = new ServerSocket(PORT);
        System.out.println("Server socket: " + s);
        System.out.println("Server listening...");
        try { while(true) {
            // Blocks until a connection occurs:
            Socket socket = s.accept();
            System.out.println("Connection accepted.");
            System.out.println("The new socket: " + socket);
            try {
                ClientThread t = new ClientThread(socket);
                System.out.println("New thread started.");
                System.out.println("The new thread: " + t);

                }
                catch(IOException e) {
                    System.out.println("===Socket Closed===");
                    socket.close();
                }
            }
        }
        finally { System.out.println("===ServerSocket Closed==="); s.close(); }
        }
    }
}

ServerGUI:

public class ServerGUI extends Application implements Initializable{

    @FXML private MenuItem startConn;

    @Override
    public void start(Stage stage) throws Exception {
        try {
            Parent root = FXMLLoader.load(getClass().getResource("ServerGUI.fxml"));
            stage.setScene(new Scene(root));
            stage.show();
        } catch (IOException ex) {
            ex.printStackTrace();
            System.exit(0);
        }
    }
    public static void main(String[] args) {
        launch(args);
    }
    @Override
    public void initialize(URL location, ResourceBundle resources) {

        startConn.setOnAction(e -> {
            try {
                MultiThreadServer mts = new MultiThreadServer();
                mts.startServer();
                System.out.println("Starting Server...");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        });
    }
}

Body:
As i suspected, a new thread for the server was required.

MultiThreadServer:

public Runnable startServer() throws IOException {

After making the function Runnable i added this:

ServerGUI:

startConn.setOnAction(e -> {
            Thread t1 = new Thread(new Runnable() {
                public void run()
                {
                    MultiThreadServer mts = new MultiThreadServer();

                    try {
                        mts.startServer();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }});
                t1.start();

Thanks to user BackSlash for providing reference-link.


问:
Why 'strong name key file' is copied into project?
I want to sign one assembly in my project (to be used by another team). From my experience, soon I will need to sign other projects too and I want to sign them all with one file.

I have done the following:

Right click on my project, go to properties, go to "Signing" tab, checked "Sign the assembly" check-box, entered key file name (MyKey), clicked 'ok'.

my file (MyKey.snk) was saved inside the folder project.

I moved generated key file 1 level up, into solution folder;

opened 'Signing' tab again, and in 'Chose a strong name key file' selected file from new location;

and the MyKey.snk file was copied into project folder.

Is this ok? Can I prevent key file from copying into project folder?

Thanks a lot.

P.S. I work in VS 2008

答:
I believe VS will always want to see the snk file in the project, but it's fine if it's added as a linked file...

Remove the snk that was copied into the project

Right-click on the project in VS and pick Add > Existing Item...

Browse to the solution's snk and from the Add button's menu select Add As Link

Go to project properties Signing tab and you should be able to select the linked snk

ContentLicense: CC BY-SA 2.5


问:
Spring Boot: Profiles ignored in PropertySourcesPlaceholderConfigurer loaded file
I have a library that is a Spring Boot project. The library has a library.yml file that contains dev and prod props for its configuration:

library.yml

```<code>---
spring:
    profiles:
        active: dev
---
spring:
    profiles: dev
env: dev
---
spring:
    profiles: prod
env: prod
</code>```

Another application uses this library and loads the props using:

```<code>@Bean
public static PropertySourcesPlaceholderConfigurer dataProperties() {
  PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
  YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
  yaml.setResources(new ClassPathResource("library.yml"));
  propertySourcesPlaceholderConfigurer.setProperties(yaml.getObject());
  return propertySourcesPlaceholderConfigurer;
}
</code>```

And its application.yml says to use dev props:

```<code>---
spring:
    profiles:
        active: dev
</code>```

But when I check the value of env, I get "prod". Why?

How can I tell Spring Boot to use the active (e.g. dev) profile props in library.yml?

Note: I prefer to use .yml instead .properties files.

答:
By default, the PropertySourcesPlaceholderConfigurer knows nothing about only getting profile specific props. If you have a prop defined multiple times in a file such as env, it will bind the value associated with the last occurrence of that prop (in this case prod).

To make it bind props matching a specific profile, set a profile document matcher. The profile document matcher will need to know the active profile which can be obtained from the environment. Here's the code:

```<code>@Bean
public static PropertySourcesPlaceholderConfigurer dataProperties(Environment environment) {
  PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
  YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
  SpringProfileDocumentMatcher matcher = new SpringProfileDocumentMatcher();
  matcher.addActiveProfiles(environment.getActiveProfiles());
  yaml.setDocumentMatchers(matcher);
  yaml.setResources(new ClassPathResource("library.yml"));
  propertySourcesPlaceholderConfigurer.setProperties(yaml.getObject());
  return propertySourcesPlaceholderConfigurer;
}
</code>```

Body:
I have a library that is a Spring Boot project. The library has a library.yml file that contains dev and prod props for its configuration:

library.yml

---
spring:
    profiles:
        active: dev
---
spring:
    profiles: dev
env: dev
---
spring:
    profiles: prod
env: prod

Another application uses this library and loads the props using:

@Bean
public static PropertySourcesPlaceholderConfigurer dataProperties() {
  PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
  YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
  yaml.setResources(new ClassPathResource("library.yml"));
  propertySourcesPlaceholderConfigurer.setProperties(yaml.getObject());
  return propertySourcesPlaceholderConfigurer;
}

And its application.yml says to use dev props:

---
spring:
    profiles:
        active: dev

But when I check the value of env, I get "prod". Why?

How can I tell Spring Boot to use the active (e.g. dev) profile props in library.yml?

Note: I prefer to use .yml instead .properties files.

Body:
By default, the PropertySourcesPlaceholderConfigurer knows nothing about only getting profile specific props. If you have a prop defined multiple times in a file such as env, it will bind the value associated with the last occurrence of that prop (in this case prod).

To make it bind props matching a specific profile, set a profile document matcher. The profile document matcher will need to know the active profile which can be obtained from the environment. Here's the code:

@Bean
public static PropertySourcesPlaceholderConfigurer dataProperties(Environment environment) {
  PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
  YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
  SpringProfileDocumentMatcher matcher = new SpringProfileDocumentMatcher();
  matcher.addActiveProfiles(environment.getActiveProfiles());
  yaml.setDocumentMatchers(matcher);
  yaml.setResources(new ClassPathResource("library.yml"));
  propertySourcesPlaceholderConfigurer.setProperties(yaml.getObject());
  return propertySourcesPlaceholderConfigurer;
}


问:
How to change jQuery panel href?
I have an  record with an href to a panel. In differing states, I would like the button to open different panels.  I've tried changing the href, but that doesn't appear to be enough, as the button always opens the original panel.

The a record is defined like this ...

```<code>  <li><a href="#panel1" id="Xpanel" class="icon fa-crop"> </a>
</code>```

When clicked, panel1 is displayed and works great ...

I'm changing the href for the a record like so ...

```<code>   var id = document.getElementById('Xpanel');
   $(id).attr('href', "#panel2");
</code>```

In the Safari debugger, I can see that all is changing, but the button always opens the original #panel1.

Do I need to rebind the  records href somehow ???

答: It sounds like you are creating an event listener on Xpanel with a locally scoped variable, i.e. Xpanel's href at the time. If you update the href the event listener doesn't use the updated value when it fires; it uses the original value when the listener was created.

Title: How to change jQuery panel href?

Body:
I have an  record with an href to a panel. In differing states, I would like the button to open different panels.  I've tried changing the href, but that doesn't appear to be enough, as the button always opens the original panel.

The a record is defined like this ...

When clicked, panel1 is displayed and works great ...

I'm changing the href for the a record like so ...

   var id = document.getElementById('Xpanel');
   $(id).attr('href', "#panel2");

In the Safari debugger, I can see that all is changing, but the button always opens the original #panel1.

Do I need to rebind the  records href somehow ???


问:
SQL Server - deduplicate and return table with single address
I am a bit stuck with this one.

I have the following situation:

```<code>Table
----------------------------------------
ID  | Street         | Zipcode | Surname
----------------------------------------
001 |Summer Street 2 | 0001    | Smith
002 |Summer Street 2 | 0001    | Smith
003 |Winter Street 1 | 0002    | Muller
004 |Autumn Street 5 | 0004    | Jones
005 |Winter Street 1 | 0002    | Muller
</code>```

Final Table should de-duplicate, it does not really matter which of the duplicate ids is chosen:

```<code>----------------------------------------
ID  | Street         | Zipcode | Surname
----------------------------------------
001 |Summer Street 2 | 0001    | Smith
003 |Winter Street 1 | 0002    | Muller
004 |Autumn Street 5 | 0004    | Jones
</code>```

I am able to select all duplicates by the following statement and store it in another. But I don´t know how to proceed from here ti get to the desired final table. As well I have the feeling that working with three tables at the end is a dirty solution.

```<code>SELECT
Address,
Postcode,
Surname
FROM
    Table
GROUP BY
   Address,
   Postcode,
   Surname
HAVING
    COUNT(*) > 1
</code>```

It is important to know that I am only allowed start statements with Select.

答:
You could use a little CTE "magic":</p>

```<code>WITH Dups AS (
    SELECT *,
           ROW_NUMBER() OVER (PARTITION BY [Address], Postcode, Surname
                              ORDER BY ID) AS RN
    FROM YourTable)
SELECT *
FROM Dups
WHERE RN = 1;
</code>```

Body:
I am a bit stuck with this one.

I have the following situation:

Table
----------------------------------------
ID  | Street         | Zipcode | Surname
----------------------------------------
001 |Summer Street 2 | 0001    | Smith
002 |Summer Street 2 | 0001    | Smith
003 |Winter Street 1 | 0002    | Muller
004 |Autumn Street 5 | 0004    | Jones
005 |Winter Street 1 | 0002    | Muller

Final Table should de-duplicate, it does not really matter which of the duplicate ids is chosen:

----------------------------------------
ID  | Street         | Zipcode | Surname
----------------------------------------
001 |Summer Street 2 | 0001    | Smith
003 |Winter Street 1 | 0002    | Muller
004 |Autumn Street 5 | 0004    | Jones

I am able to select all duplicates by the following statement and store it in another. But I don´t know how to proceed from here ti get to the desired final table. As well I have the feeling that working with three tables at the end is a dirty solution.

SELECT
Address,
Postcode,
Surname
FROM
    Table
GROUP BY
   Address,
   Postcode,
   Surname
HAVING
    COUNT(*) > 1

It is important to know that I am only allowed start statements with Select.

Body:
You could use a little CTE "magic":

WITH Dups AS (
    SELECT *,
           ROW_NUMBER() OVER (PARTITION BY [Address], Postcode, Surname
                              ORDER BY ID) AS RN
    FROM YourTable)
SELECT *
FROM Dups
WHERE RN = 1;


问:
Looking for good bonus quiz to test efficiency (specifically efficiency related to time)
I am doing a Introductory to Computer Science lab once a week.  I was hoping to have a quick contest at the end of my next lab.  I want to give them a block of code like this:

```<code>public class EfficientCode{

    public static void main(){
        long startTime, endTime, executionTime;
        startTime = System.currentTimeMillis();

        yourEfficientMethod():
        endTime = System.currentTimeMillis();
        executionTime = endTime – startTime;

    }

    public static void doSomething(){
        // you do this part.
    }

}
</code>```

They will implement the doSomething method and the person with the fastest code will get a handful of bonus marks.

The problem is that the question needs to be somewhat simple.  The students have a good grasp of: loops, if/else, Strings, adding, arrays, etc.

Here are my ideas for what the question could be:

find all the perfect numbers between 1 and 1,000,000.  (A perfect number is a number where all of the number's factors add up to the number.  Ie: 6 = 3 + 2 + 1)

find all prime numbers between 1 and 1,000,000

I think in order for there to be a measurable difference in performance between methods you must do something many times.

答: Sorting an array of numbers might also be a good idea, since there are a whole bunch of algorithms for it (insertion, selection, quick, heap, etc.) that all have different performance characteristics.  This would also give students a chance to learn about big-O notation, etc.</p>

Body:
I am doing a Introductory to Computer Science lab once a week.  I was hoping to have a quick contest at the end of my next lab.  I want to give them a block of code like this:

public class EfficientCode{

    public static void main(){
        long startTime, endTime, executionTime;
        startTime = System.currentTimeMillis();

        yourEfficientMethod():
        endTime = System.currentTimeMillis();
        executionTime = endTime – startTime;

    }

    public static void doSomething(){
        // you do this part.
    }

}

They will implement the doSomething method and the person with the fastest code will get a handful of bonus marks.

The problem is that the question needs to be somewhat simple.  The students have a good grasp of: loops, if/else, Strings, adding, arrays, etc.

Here are my ideas for what the question could be:

find all the perfect numbers between 1 and 1,000,000.  (A perfect number is a number where all of the number's factors add up to the number.  Ie: 6 = 3 + 2 + 1)

find all prime numbers between 1 and 1,000,000

I think in order for there to be a measurable difference in performance between methods you must do something many times.


问:
Why am I getting "Closing delimiter C not found" error when upgrading from PHP 5 to PHP 7

I am using the php7cc tool https://github.com/sstalle/php7cc to help upgrade to PHP7.  It is returning an error that I do not know how to fix because it does not give a line number and I do not exactly know what it wants me to fix.  I get a

```<code>"text" : "Closing delimiter C not found",
              "line" : null
</code>```

error from the json returned from php7cc.  This is the page that is returning it:

```<code><?php
class geo
{
var $postcode = "";
var $lat = 0;
var $lng = 0;

function setPostcode($postcode)
{
    $this->postcode = preg_replace("/[^a-zA-Z0-9]/", "", strtoupper(trim($postcode)));
}

function getPostcode()
{
    return $this->postcode;
}

function getLatLong($postcode="")
{
    if($postcode)
        $this->setPostcode($postcode);

    if($this->isValidPostCode())
    {
        if($_SESSION['GEO'][$this->postcode])
            return $_SESSION['GEO'][$this->postcode];

        $url = "http://maps.google.co.uk/maps/api/geocode/json?address=".$this->postcode."&sensor=false&region=uk";
        $jsonData = file_get_contents($url);

        if($jsonData)
        {
            $data = json_decode($jsonData);

            $this->lng = $data->results[0]->geometry->location->lng;
            $this->lat = $data->results[0]->geometry->location->lat;

            if($this->lng && $this->lat)
                $result = array("postcode"=>$this->postcode, "lat"=>$this->lat, "lng"=>$this->lng);
            else
                $result = array("error"=>"Postcode doesn't exist");

            $_SESSION['GEO'][$this->postcode] = $result;
            return $_SESSION['GEO'][$this->postcode];
        }
        return array("error", "Unable to fetch lat/long");
    }
    else
    {
        return array("error"=>"Invalid postcode");
    }
}

function isValidPostCode()
{
    // Permitted letters depend upon their position in the postcode.
    $alpha1 = "[abcdefghijklmnoprstuwyz]";                          // Character 1
    $alpha2 = "[abcdefghklmnopqrstuvwxy]";                          // Character 2
    $alpha3 = "[abcdefghjkstuw]";                                   // Character 3
    $alpha4 = "[abehmnprvwxy]";                                     // Character 4
    $alpha5 = "[abdefghjlnpqrstuwxyz]";                             // Character 5

    // Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
    $pcexp[0] = '^('.$alpha1.'{1}'.$alpha2.'{0,1}[0-9]{1,2})([0-9]{1}'.$alpha5.'{2})$';

    // Expression for postcodes: ANA NAA
    $pcexp[1] =  '^('.$alpha1.'{1}[0-9]{1}'.$alpha3.'{1})([0-9]{1}'.$alpha5.'{2})$';

    // Expression for postcodes: AANA NAA
    $pcexp[2] =  '^('.$alpha1.'{1}'.$alpha2.'[0-9]{1}'.$alpha4.')([0-9]{1}'.$alpha5.'{2})$';

    // Exception for the special postcode GIR 0AA
    $pcexp[3] =  '^(gir)(0aa)$';

    // Standard BFPO numbers
    $pcexp[4] = '^(bfpo)([0-9]{1,4})$';

    // c/o BFPO numbers
    $pcexp[5] = '^(bfpo)(c\/o[0-9]{1,3})$';

    // Load up the string to check, converting into lowercase and removing spaces
    $postcode = strtolower($this->postcode);

    // Assume we are not going to find a valid postcode
    $valid = false;

    // Check the string against the six types of postcodes
    foreach ($pcexp as $regexp)
    {
        if (preg_match($regexp,$postcode, $matches))
        {

          // Load new postcode back into the form element
          $toCheck = strtoupper ($matches[1] . ' ' . $matches [2]);

          // Take account of the special BFPO c/o format
          $toCheck = preg_replace ('C/O', 'c/o ', $toCheck);

          // Remember that we have found that the code is valid and break from loop
          $valid = true;
          break;
        }
    }

    // Return with the reformatted valid postcode in uppercase if the postcode was
    // valid
    if ($valid){return true;} else {return false;};
}
}
?>
</code>```

I did not write this code.  my guess is somthing to do with the preg_replace ('C/O', 'c/o ', $toCheck); but I don't really know.

答:
I have tried to simplify your example to test it.

The only obvious thing I found is your regex strings do not have delimiters, e.g.

```<code>$pattern="/^([0-9]+)$/";
</code>```

See: PHP-Delimiters

Plus, in preg_replace there is also an unescaped / if you add the standard delimiters. This is what probably causing the error.

```<code><?php

isValidPostCode();

function isValidPostCode()
{
    // Permitted letters depend upon their position in the postcode.
    $alpha1 = "[abcdefghijklmnoprstuwyz]";                          // Character 1
    $alpha2 = "[abcdefghklmnopqrstuvwxy]";                          // Character 2
    $alpha3 = "[abcdefghjkstuw]";                                   // Character 3
    $alpha4 = "[abehmnprvwxy]";                                     // Character 4
    $alpha5 = "[abdefghjlnpqrstuwxyz]";                             // Character 5

    // Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
    $pcexp[0] = '/^('.$alpha1.'{1}'.$alpha2.'{0,1}[0-9]{1,2})([0-9]{1}'.$alpha5.'{2})$/';

    // Expression for postcodes: ANA NAA
    $pcexp[1] =  '/^('.$alpha1.'{1}[0-9]{1}'.$alpha3.'{1})([0-9]{1}'.$alpha5.'{2})$/';

    // Expression for postcodes: AANA NAA
    $pcexp[2] =  '/^('.$alpha1.'{1}'.$alpha2.'[0-9]{1}'.$alpha4.')([0-9]{1}'.$alpha5.'{2})$/';

    // Exception for the special postcode GIR 0AA
    $pcexp[3] =  '/^(gir)(0aa)$/';

    // Standard BFPO numbers
    $pcexp[4] = '/^(bfpo)([0-9]{1,4})$/';

    // c/o BFPO numbers
    $pcexp[5] = '/^(bfpo)(c\/o[0-9]{1,3})$/';

    // Load up the string to check, converting into lowercase and removing spaces
    $postcode = strtolower("AANN NAA C/0 dks");

    // Assume we are not going to find a valid postcode
    $valid = false;

    // Check the string against the six types of postcodes
    foreach ($pcexp as $regexp)
    {
        if (preg_match($regexp,$postcode, $matches))
        {

          // Load new postcode back into the form element
          $toCheck = strtoupper ($matches[1] . ' ' . $matches [2]);

          // Take account of the special BFPO c/o format
          $toCheck = preg_replace ('/C\/O/', 'c/o ', $toCheck);

          // Remember that we have found that the code is valid and break from loop
          $valid = true;
          break;
        }
    }

    // Return with the reformatted valid postcode in uppercase if the postcode was
    // valid
    if ($valid){return true;} else {return false;};
}
</code>```

Body:
I am using the php7cc tool https://github.com/sstalle/php7cc to help upgrade to PHP7.  It is returning an error that I do not know how to fix because it does not give a line number and I do not exactly know what it wants me to fix.  I get a

"text" : "Closing delimiter C not found",
              "line" : null

error from the json returned from php7cc.  This is the page that is returning it:

<?php
class geo
{
var $postcode = "";
var $lat = 0;
var $lng = 0;

function setPostcode($postcode)
{
    $this->postcode = preg_replace("/[^a-zA-Z0-9]/", "", strtoupper(trim($postcode)));
}

function getPostcode()
{
    return $this->postcode;
}

function getLatLong($postcode="")
{
    if($postcode)
        $this->setPostcode($postcode);

    if($this->isValidPostCode())
    {
        if($_SESSION['GEO'][$this->postcode])
            return $_SESSION['GEO'][$this->postcode];

        $url = "http://maps.google.co.uk/maps/api/geocode/json?address=".$this->postcode."&sensor=false&region=uk";
        $jsonData = file_get_contents($url);

        if($jsonData)
        {
            $data = json_decode($jsonData);

            $this->lng = $data->results[0]->geometry->location->lng;
            $this->lat = $data->results[0]->geometry->location->lat;

            if($this->lng && $this->lat)
                $result = array("postcode"=>$this->postcode, "lat"=>$this->lat, "lng"=>$this->lng);
            else
                $result = array("error"=>"Postcode doesn't exist");

            $_SESSION['GEO'][$this->postcode] = $result;
            return $_SESSION['GEO'][$this->postcode];
        }
        return array("error", "Unable to fetch lat/long");
    }
    else
    {
        return array("error"=>"Invalid postcode");
    }
}

function isValidPostCode()
{
    // Permitted letters depend upon their position in the postcode.
    $alpha1 = "[abcdefghijklmnoprstuwyz]";                          // Character 1
    $alpha2 = "[abcdefghklmnopqrstuvwxy]";                          // Character 2
    $alpha3 = "[abcdefghjkstuw]";                                   // Character 3
    $alpha4 = "[abehmnprvwxy]";                                     // Character 4
    $alpha5 = "[abdefghjlnpqrstuwxyz]";                             // Character 5

    // Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
    $pcexp[0] = '^('.$alpha1.'{1}'.$alpha2.'{0,1}[0-9]{1,2})([0-9]{1}'.$alpha5.'{2})$';

    // Expression for postcodes: ANA NAA
    $pcexp[1] =  '^('.$alpha1.'{1}[0-9]{1}'.$alpha3.'{1})([0-9]{1}'.$alpha5.'{2})$';

    // Expression for postcodes: AANA NAA
    $pcexp[2] =  '^('.$alpha1.'{1}'.$alpha2.'[0-9]{1}'.$alpha4.')([0-9]{1}'.$alpha5.'{2})$';

    // Exception for the special postcode GIR 0AA
    $pcexp[3] =  '^(gir)(0aa)$';

    // Standard BFPO numbers
    $pcexp[4] = '^(bfpo)([0-9]{1,4})$';

    // c/o BFPO numbers
    $pcexp[5] = '^(bfpo)(c\/o[0-9]{1,3})$';

    // Load up the string to check, converting into lowercase and removing spaces
    $postcode = strtolower($this->postcode);

    // Assume we are not going to find a valid postcode
    $valid = false;

    // Check the string against the six types of postcodes
    foreach ($pcexp as $regexp)
    {
        if (preg_match($regexp,$postcode, $matches))
        {

          // Load new postcode back into the form element
          $toCheck = strtoupper ($matches[1] . ' ' . $matches [2]);

          // Take account of the special BFPO c/o format
          $toCheck = preg_replace ('C/O', 'c/o ', $toCheck);

          // Remember that we have found that the code is valid and break from loop
          $valid = true;
          break;
        }
    }

    // Return with the reformatted valid postcode in uppercase if the postcode was
    // valid
    if ($valid){return true;} else {return false;};
}
}
?>

I did not write this code.  my guess is somthing to do with the preg_replace ('C/O', 'c/o ', $toCheck); but I don't really know.

Body:
I have tried to simplify your example to test it.

The only obvious thing I found is your regex strings do not have delimiters, e.g.

$pattern="/^([0-9]+)$/";

See: PHP-Delimiters

Plus, in preg_replace there is also an unescaped / if you add the standard delimiters. This is what probably causing the error.

<?php

isValidPostCode();

function isValidPostCode()
{
    // Permitted letters depend upon their position in the postcode.
    $alpha1 = "[abcdefghijklmnoprstuwyz]";                          // Character 1
    $alpha2 = "[abcdefghklmnopqrstuvwxy]";                          // Character 2
    $alpha3 = "[abcdefghjkstuw]";                                   // Character 3
    $alpha4 = "[abehmnprvwxy]";                                     // Character 4
    $alpha5 = "[abdefghjlnpqrstuwxyz]";                             // Character 5

    // Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
    $pcexp[0] = '/^('.$alpha1.'{1}'.$alpha2.'{0,1}[0-9]{1,2})([0-9]{1}'.$alpha5.'{2})$/';

    // Expression for postcodes: ANA NAA
    $pcexp[1] =  '/^('.$alpha1.'{1}[0-9]{1}'.$alpha3.'{1})([0-9]{1}'.$alpha5.'{2})$/';

    // Expression for postcodes: AANA NAA
    $pcexp[2] =  '/^('.$alpha1.'{1}'.$alpha2.'[0-9]{1}'.$alpha4.')([0-9]{1}'.$alpha5.'{2})$/';

    // Exception for the special postcode GIR 0AA
    $pcexp[3] =  '/^(gir)(0aa)$/';

    // Standard BFPO numbers
    $pcexp[4] = '/^(bfpo)([0-9]{1,4})$/';

    // c/o BFPO numbers
    $pcexp[5] = '/^(bfpo)(c\/o[0-9]{1,3})$/';

    // Load up the string to check, converting into lowercase and removing spaces
    $postcode = strtolower("AANN NAA C/0 dks");

    // Assume we are not going to find a valid postcode
    $valid = false;

    // Check the string against the six types of postcodes
    foreach ($pcexp as $regexp)
    {
        if (preg_match($regexp,$postcode, $matches))
        {

          // Load new postcode back into the form element
          $toCheck = strtoupper ($matches[1] . ' ' . $matches [2]);

          // Take account of the special BFPO c/o format
          $toCheck = preg_replace ('/C\/O/', 'c/o ', $toCheck);

          // Remember that we have found that the code is valid and break from loop
          $valid = true;
          break;
        }
    }

    // Return with the reformatted valid postcode in uppercase if the postcode was
    // valid
    if ($valid){return true;} else {return false;};
}


问:
Unable to access IDempiere - java.io.IOException: java.util.concurrent.TimeoutException: Idle timeout expired: 123000/123000 ms
I am Unable to access IDempiere Instance webui getting below error.

```<code>java.io.IOException: java.util.concurrent.TimeoutException: Idle timeout expired: 123000/123000 ms
        at org.eclipse.jetty.util.SharedBlockingCallback$Blocker.block(SharedBlockingCallback.java:226)
        at org.eclipse.jetty.server.HttpOutput.write(HttpOutput.java:164)
        at org.eclipse.jetty.server.HttpOutput.write(HttpOutput.java:436)
        at java.io.OutputStream.write(OutputStream.java:75)
        at org.zkoss.zk.ui.http.WpdExtendlet.service(WpdExtendlet.java:104)
        at org.zkoss.web.util.resource.ClassWebResource.web0(ClassWebResource.java:585)
        at org.zkoss.web.util.resource.ClassWebResource.web(ClassWebResource.java:571)
        at org.zkoss.web.util.resource.ClassWebResource.service(ClassWebResource.java:262)
        at org.zkoss.zk.au.http.DHtmlUpdateServlet.doGet(DHtmlUpdateServlet.java:427)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
        at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:837)
        at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:583)
        at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
        at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548)
        at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:226)
        at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1180)
        at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:511)
        at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
        at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1112)
        at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
    caused by: java.util.concurrent.TimeoutException: Idle timeout expired: 123000/123000 ms
        at org.eclipse.jetty.io.IdleTimeout.checkIdleTimeout(IdleTimeout.java:166)
        at org.eclipse.jetty.io.IdleTimeout$1.run(IdleTimeout.java:50)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
</code>```

Anyone please help us to resolve this issue.

答:
Request idle timed out at 123000 ms.

That means there was no activity (read or write) for 123000 ms and the connection was closed.

ContentLicense: CC BY-SA 4.0

Body:
I am Unable to access IDempiere Instance webui getting below error.

java.io.IOException: java.util.concurrent.TimeoutException: Idle timeout expired: 123000/123000 ms
        at org.eclipse.jetty.util.SharedBlockingCallback$Blocker.block(SharedBlockingCallback.java:226)
        at org.eclipse.jetty.server.HttpOutput.write(HttpOutput.java:164)
        at org.eclipse.jetty.server.HttpOutput.write(HttpOutput.java:436)
        at java.io.OutputStream.write(OutputStream.java:75)
        at org.zkoss.zk.ui.http.WpdExtendlet.service(WpdExtendlet.java:104)
        at org.zkoss.web.util.resource.ClassWebResource.web0(ClassWebResource.java:585)
        at org.zkoss.web.util.resource.ClassWebResource.web(ClassWebResource.java:571)
        at org.zkoss.web.util.resource.ClassWebResource.service(ClassWebResource.java:262)
        at org.zkoss.zk.au.http.DHtmlUpdateServlet.doGet(DHtmlUpdateServlet.java:427)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
        at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:837)
        at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:583)
        at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
        at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548)
        at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:226)
        at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1180)
        at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:511)
        at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
        at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1112)
        at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
    caused by: java.util.concurrent.TimeoutException: Idle timeout expired: 123000/123000 ms
        at org.eclipse.jetty.io.IdleTimeout.checkIdleTimeout(IdleTimeout.java:166)
        at org.eclipse.jetty.io.IdleTimeout$1.run(IdleTimeout.java:50)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)

Anyone please help us to resolve this issue.


答:
If your permissions are set so that you can only "...start statements with Select" I do not believe you will be able to do this. You need to do something like this:</p>

```<code>INSERT INTO [final].[table]
            ([Address]
             , [Postcode]
             , [Surname])
    SELECT [Address]
           , [Postcode]
           , [Surname]
    FROM   [Table]
    GROUP  BY [Address]
              , [Postcode]
              , [Surname]
    HAVING COUNT(*) > 1
</code>```

Title: SQL Server - deduplicate and return table with single address

Body:
If your permissions are set so that you can only "...start statements with Select" I do not believe you will be able to do this. You need to do something like this:

INSERT INTO [final].[table]
            ([Address]
             , [Postcode]
             , [Surname])
    SELECT [Address]
           , [Postcode]
           , [Surname]
    FROM   [Table]
    GROUP  BY [Address]
              , [Postcode]
              , [Surname]
    HAVING COUNT(*) > 1


问:
Predicting a multiple forward time step of a time series using LSTM
I want to predict certain values that are weekly predictable (low SNR). I need to predict the whole time series of a year formed by the weeks of the year (52 values - Figure 1)

My first idea was to develop a many-to-many LSTM model (Figure 2) using Keras over TensorFlow. I'm training the model with a 52 input layer (the given time series of previous year) and 52 predicted output layer (the time series of next year). The shape of train_X is (X_examples, 52, 1), in other words, X_examples to train, 52 timesteps of 1 feature each. I understand that Keras will consider the 52 inputs as a time series of the same domain. The shape of the train_Y are the same (y_examples, 52, 1).
I added a TimeDistributed layer. My thought was that the algorithm will predict the values as a time series instead of isolated values (am I correct?)

The model's code in Keras is:

```<code>y = y.reshape(y.shape[0], 52, 1)
X = X.reshape(X.shape[0], 52, 1)
# design network
model = Sequential()
model.add(LSTM(n_neurons, input_shape=(X.shape[1], X.shape[2]), return_sequences=True))
model.add(TimeDistributed(Dense(1)))
model.compile(loss='mean_squared_error', optimizer='adam')
# fit network
model.fit(X, y, epochs=n_epochs, batch_size=n_batch, verbose=2)
</code>```

The problem is that the algorithm is not learning the example. It is predicting values very similar to the attributes' values. Am I modeling the problem correctly?

Second question:
Another idea is to train the algorithm with 1 input and 1 output, but then during the test how will I predict the whole 2015 time series without looking to the '1 input'? The test data will have a different shape than the training data.

答:
Sharing the same concerns about having too little data, you can do that like this.

First, it's a good idea to keep your values between -1 and +1, so I'd normalize them first.

For the LSTM model, you must make sure you're using return_sequences=True.

There is nothing "wrong" with your model, but it may need more or less layers or units to achieve what you desire. (There is no clear answer to this, though).

Training the model to predict the next step:

All you need is to pass Y as a shifted X:

```<code>entireData = arrayWithShape((samples,52,1))
X = entireData[:,:-1,:]
y = entireData[:,1:,:]
</code>```

Train the model using these.

Predicting the future:

Now, for predicting the future, since we need to use predicted elements as input for more predicted elements, we are going to use a loop and make the model stateful=True.

Create a model equal to the previous one, with these changes:

All LSTM layers must have stateful=True

The batch input shape must be (batch_size,None, 1) - This allows variable lengths

Copy the weights of the previously trained model:

```<code>newModel.set_weights(oldModel.get_weights())
</code>```

Predict only one sample at a time and never forget to call model.reset_states() before starting any sequence.

First predict with the sequence you already know (this will make sure the model prepares its states properly for predicting the future)

```<code>model.reset_states()
predictions = model.predict(entireData)
</code>```

By the way we trained, the last step in predictions will be the first future element:

```<code>futureElement = predictions[:,-1:,:]

futureElements = []
futureElements.append(futureElement)
</code>```

Now we make a loop where this element is the input. (Because of stateful, the model will understand it's a new input step of the previous sequence instead of a new sequence)

```<code>for i in range(howManyPredictions):
    futureElement = model.predict(futureElement)
    futureElements.append(futureElement)
</code>```

This link contains a complete example predicting the future of two features: https://github.com/danmoller/TestRepo/blob/master/TestBookLSTM.ipynb

Body:
I want to predict certain values that are weekly predictable (low SNR). I need to predict the whole time series of a year formed by the weeks of the year (52 values - Figure 1)

My first idea was to develop a many-to-many LSTM model (Figure 2) using Keras over TensorFlow. I'm training the model with a 52 input layer (the given time series of previous year) and 52 predicted output layer (the time series of next year). The shape of train_X is (X_examples, 52, 1), in other words, X_examples to train, 52 timesteps of 1 feature each. I understand that Keras will consider the 52 inputs as a time series of the same domain. The shape of the train_Y are the same (y_examples, 52, 1).
I added a TimeDistributed layer. My thought was that the algorithm will predict the values as a time series instead of isolated values (am I correct?)

The model's code in Keras is:

y = y.reshape(y.shape[0], 52, 1)
X = X.reshape(X.shape[0], 52, 1)
# design network
model = Sequential()
model.add(LSTM(n_neurons, input_shape=(X.shape[1], X.shape[2]), return_sequences=True))
model.add(TimeDistributed(Dense(1)))
model.compile(loss='mean_squared_error', optimizer='adam')
# fit network
model.fit(X, y, epochs=n_epochs, batch_size=n_batch, verbose=2)

The problem is that the algorithm is not learning the example. It is predicting values very similar to the attributes' values. Am I modeling the problem correctly?

Second question:
Another idea is to train the algorithm with 1 input and 1 output, but then during the test how will I predict the whole 2015 time series without looking to the '1 input'? The test data will have a different shape than the training data.

Body:
Sharing the same concerns about having too little data, you can do that like this.

First, it's a good idea to keep your values between -1 and +1, so I'd normalize them first.

For the LSTM model, you must make sure you're using return_sequences=True.

There is nothing "wrong" with your model, but it may need more or less layers or units to achieve what you desire. (There is no clear answer to this, though).

Training the model to predict the next step:

All you need is to pass Y as a shifted X:

entireData = arrayWithShape((samples,52,1))
X = entireData[:,:-1,:]
y = entireData[:,1:,:]

Train the model using these.

Predicting the future:

Now, for predicting the future, since we need to use predicted elements as input for more predicted elements, we are going to use a loop and make the model stateful=True.

Create a model equal to the previous one, with these changes:

All LSTM layers must have stateful=True

The batch input shape must be (batch_size,None, 1) - This allows variable lengths

Copy the weights of the previously trained model:

newModel.set_weights(oldModel.get_weights())

Predict only one sample at a time and never forget to call model.reset_states() before starting any sequence.

First predict with the sequence you already know (this will make sure the model prepares its states properly for predicting the future)

model.reset_states()
predictions = model.predict(entireData)

By the way we trained, the last step in predictions will be the first future element:

futureElement = predictions[:,-1:,:]

futureElements = []
futureElements.append(futureElement)

Now we make a loop where this element is the input. (Because of stateful, the model will understand it's a new input step of the previous sequence instead of a new sequence)

for i in range(howManyPredictions):
    futureElement = model.predict(futureElement)
    futureElements.append(futureElement)

This link contains a complete example predicting the future of two features: https://github.com/danmoller/TestRepo/blob/master/TestBookLSTM.ipynb


答:
Assuming they are always perfect duplicates except for the ID, just use an aggregate on ID to choose one of the rows.  For example MIN():

```<code>SELECT MIN(ID) ID, Address, Postcode, Surname
FROM Table
GROUP BY Address, Postcode, Surname
</code>```

Edit:  A little extra explanation:

The only difference in your duplicate rows is the ID column, otherwise they are identical.  If you use an aggregate function, such as MIN() which chooses the minimum value, and GROUP BY the other columns, then you will no longer have duplicates in your result set.

These rows:

```<code>001 |Summer Street 2 | 0001 | Smith
002 |Summer Street 2 | 0001 | Smith
</code>```

Will group and roll up to this row:

```<code>001 |Summer Street 2 | 0001 | Smith
</code>```

Because 001 is the MIN(ID) between the two.

Note: This approach isn't always possible if you need a specific ID, but since you said it doesn't matter which row is chosen, this is the simplest way.

Body:
Assuming they are always perfect duplicates except for the ID, just use an aggregate on ID to choose one of the rows.  For example MIN():

SELECT MIN(ID) ID, Address, Postcode, Surname
FROM Table
GROUP BY Address, Postcode, Surname

Edit:  A little extra explanation:

The only difference in your duplicate rows is the ID column, otherwise they are identical.  If you use an aggregate function, such as MIN() which chooses the minimum value, and GROUP BY the other columns, then you will no longer have duplicates in your result set.

These rows:

001 |Summer Street 2 | 0001 | Smith
002 |Summer Street 2 | 0001 | Smith

Will group and roll up to this row:

001 |Summer Street 2 | 0001 | Smith

Because 001 is the MIN(ID) between the two.

Note: This approach isn't always possible if you need a specific ID, but since you said it doesn't matter which row is chosen, this is the simplest way.


问:
matlab fitensemble plot roc error
I'm building a model with adaboost and trying to the roc plot to work. here's my codes:

```<code>ens=fitensemble(X,y,'AdaBoostM1',100,'Tree');

[ytest, scores] = predict(ens,Xtest);

figure
[xx,yy] = perfcurve(label, scores(:,2),'yes');
plot(xx,yy)
xlabel('FPR')
ylabel('TPR')
title('ROC');
</code>```

However, this is giving me an error:

```<code>Error using perfcurve>membership (line 693)
Positive class is not found in the input data.
</code>```

my training data size is 1000x19 and testing data size is 100x19.

Here's the source from matlab:
https://www.mathworks.com/matlabcentral/fileexchange/42744-machine-learning-with-matlab?focused=6797233&tab=example

答:
Solved it. had to change the label format from logical to numeric, since my label are 0s and 1s.

Here's the corrected code:

```<code>ens=fitensemble(X,y,'AdaBoostM1',100,'Tree');

[ytest, scores] = predict(ens,Xtest);

figure
[xx,yy] = perfcurve(label, scores(:,2),1);
plot(xx,yy)
xlabel('FPR')
ylabel('TPR')
title('ROC');
</code>```

Title: matlab fitensemble plot roc error

Body:
I'm building a model with adaboost and trying to the roc plot to work. here's my codes:

ens=fitensemble(X,y,'AdaBoostM1',100,'Tree');

[ytest, scores] = predict(ens,Xtest);

figure
[xx,yy] = perfcurve(label, scores(:,2),'yes');
plot(xx,yy)
xlabel('FPR')
ylabel('TPR')
title('ROC');

However, this is giving me an error:

Error using perfcurve>membership (line 693)
Positive class is not found in the input data.

my training data size is 1000x19 and testing data size is 100x19.

Here's the source from matlab:
https://www.mathworks.com/matlabcentral/fileexchange/42744-machine-learning-with-matlab?focused=6797233&tab=example

Body:
Solved it. had to change the label format from logical to numeric, since my label are 0s and 1s.

Here's the corrected code:

ens=fitensemble(X,y,'AdaBoostM1',100,'Tree');

[ytest, scores] = predict(ens,Xtest);

figure
[xx,yy] = perfcurve(label, scores(:,2),1);
plot(xx,yy)
xlabel('FPR')
ylabel('TPR')
title('ROC');


问:
Android: how to show and move ImageView in TableLayout
I have a grid of TextViews shown inside a TableLayout. When the user taps a TextView I need to change the cell's background by adding an ImageView that will go to another cell when other cells will be clicked.

Which is the best way to do this in Android?

答:
TextView can have an image (drawable) as a background. So it is easy to do it with
textView.setBackgroundDrawable(R.drawable.myimage);

You can move the image into any cell-textView with this method and set the previous to another image or nothing with
textView.setBackgroundDrawable(null);

You cannot animate this movement in the table, because each row is one view an may limit the animation of its children views to its constrains.