问:
How to fix "double printing when I clicked twice on the pretty dialog button"
I debugging my application then I tried clicking twice and fast on the pretty dialog button and it print twice I expect that even I clicked twice it will not print twice.

I tried error handler codes but it was not working.

```<code>prettyDialog.addButton("YES",
R.color.navy_blue,
R.color.gold_yellow,
new PrettyDialogCallback() {
    @Override
    public void onClick() {

        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {

                raw_serial = String.valueOf(Build.SERIAL);
                serial_final = raw_serial.substring(raw_serial.length() - 7);

                nf = new DecimalFormat("000000");

                DateFormat dateFormat = new SimpleDateFormat("MMddyyyy");
                Date date = new Date();
                ticket_date = dateFormat.format(date).toString();

                DateFormat datetimeformat = new SimpleDateFormat("HHmmss");
                Date time = new Date();

                ticket_time = datetimeformat.format(time).toString();
                transaction_no = serial_final + ticket_date + ticket_time + nf.format(setting_last_transaction_no);
                trace_no = merchant_code + serial_final + ticket_date + ticket_time + nf.format(ref_trace_no);
                print_card_no = Cardno.substring(Cardno.length() - 4);
                String print_balance;
                print_balance = "P" + String.valueOf(Balance);
                int balancespace = 0;
                int balancelength = 0;
                balancelength = print_balance.length();
                balancespace = 13 - balancelength;
                for (int j = 0; j < balancespace; j++) {
                    print_balance = " " + print_balance;
                }
                int print = PrinterInterface.open();
                Log.e("print", String.valueOf(print));
                int querystatus = PrinterInterface.queryStatus();
                Log.e("querystatus", String.valueOf(querystatus));
                DateFormat dateformatforprint = new SimpleDateFormat("MMM.dd,yyyy");
                Date dateformatprint = new Date();
                String datetoprint = dateformatforprint.format(dateformatprint).toString();
                DateFormat timeformattoprint = new SimpleDateFormat("HH:mm");
                Date timeformat = new Date();
                String timetoprint = timeformattoprint.format(timeformat).toString();
                String finalStation = "";
                Log.e("asdasd", "asdasd");
                if (print >= 0) {
                    byte[] arryTitle = null;
                    byte[] arryTrx = null;
                    byte[] arrySubtitle = null;
                    byte[] arryBody1 = null;
                    byte[] arryspace1 = null;
                    byte[] arryFooter = null;
                    //test
                    try {
                        arryTitle = ("\n" + "TRIPKO" + "\n" + "\n").getBytes("UTF-8");
                        arryTrx = ("TRX: " + transaction_no + "\n" +
                                trace_no + "\n").getBytes("UTF-8");
                        arrySubtitle = ("Date & Time  : " + datetoprint + " " + timetoprint + "\n" +
                                "Merchant Name: " + subcompany_name.toUpperCase() + "\n" +
                                "Branch       : " + terminal_name.toUpperCase() + "\n" +
                                "-------------------------------" + "\n" +
                                "\n").getBytes("UTF-8");
                        arryBody1 = ("Card No. : " + "  **** **** **** " + print_card_no + "\n" +
                                "Trans Type : " + "    " + type_name.toUpperCase() + "\n" +
                                "Current Balance  : " + print_balance + "\n" +
                                "-------------------------------" + "\n" +
                                "\n").getBytes("UTF-8");
                        arryFooter = ("Customer Service" + "\n"
                                + "Hotline#: TRIPKO(678-1234)" + "\n" +
                                "\n").getBytes("UTF-8");
                        arryspace1 = "\n".getBytes("UTF-8");
                    } catch (Throwable e) {

                        e.printStackTrace();
                    }
                    begin();
                    if (querystatus == 1) {

                        writeLineBreak(20);
                        write(arryspace1);
                        alignment(1);
                        Fontsize(16);
                        boldFont(2);
                        doublewidth();
                        write(arryTitle);
                        backtonormal();
                        nextline();

                        Fontsize(0);
                        write(arryTrx);
                        alignment(0);
                        write(arrySubtitle);
                        write(arryBody1);

                        alignment(1);
                        write(arryFooter);
                        write(arryspace1);
                        write(arryspace1);
                        write(arryspace1);
                        write(arryspace1);

                        insertData(company_id,
                                subcompany_id,
                                terminal_id,
                                setting_control_no,
                                Cardno,
                                Balance,
                                transaction_no,
                                trace_no,
                                device_serial);
                        setting_last_transaction_no += 1;
                        ref_trace_no += 1;
                        updateTicket(String.valueOf(setting_last_transaction_no),
                                String.valueOf(ref_trace_no));
                        DBBackup();
                        end();
                        btnCheckBalance.setEnabled(true);
                        btnCheckBalance.setClickable(true);
                        Intent intent2 = new Intent(getContext(), UpdateSendingServices.class);
                        getActivity().startService(intent2);
                    } else {
                        //OpenNoPaper();
                    }
                }
                PrinterInterface.close();
            }
        });
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                totalBalance.setText("P 0.00");
                btnCheckBalance.setEnabled(true);
                btnCheckBalance.setClickable(true);
            }
        });

        prettyDialog.dismiss();
    }
})
.show();
</code>```

I expect that it will not print twice even I clicked the "YES" pretty dialog button.

答:
i think you can just do a trick like this

create a count variable  count=0;. In button click, validate condition such that if(count==0) show dialog and make count = 1. (with this dialog will not open second time) while dismissing dialog make count = 0 again.

I think this will work

Hope it helps.

```<code>if(count == 0){
count = 1 ;
//showdialog process
}
</code>```

and right before dismiss()

```<code>  ......
  count = 0;
  prettyDialog.dismiss();
</code>```

Body:
I debugging my application then I tried clicking twice and fast on the pretty dialog button and it print twice I expect that even I clicked twice it will not print twice.

I tried error handler codes but it was not working.

prettyDialog.addButton("YES",
R.color.navy_blue,
R.color.gold_yellow,
new PrettyDialogCallback() {
    @Override
    public void onClick() {

        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {

                raw_serial = String.valueOf(Build.SERIAL);
                serial_final = raw_serial.substring(raw_serial.length() - 7);

                nf = new DecimalFormat("000000");

                DateFormat dateFormat = new SimpleDateFormat("MMddyyyy");
                Date date = new Date();
                ticket_date = dateFormat.format(date).toString();

                DateFormat datetimeformat = new SimpleDateFormat("HHmmss");
                Date time = new Date();

                ticket_time = datetimeformat.format(time).toString();
                transaction_no = serial_final + ticket_date + ticket_time + nf.format(setting_last_transaction_no);
                trace_no = merchant_code + serial_final + ticket_date + ticket_time + nf.format(ref_trace_no);
                print_card_no = Cardno.substring(Cardno.length() - 4);
                String print_balance;
                print_balance = "P" + String.valueOf(Balance);
                int balancespace = 0;
                int balancelength = 0;
                balancelength = print_balance.length();
                balancespace = 13 - balancelength;
                for (int j = 0; j < balancespace; j++) {
                    print_balance = " " + print_balance;
                }
                int print = PrinterInterface.open();
                Log.e("print", String.valueOf(print));
                int querystatus = PrinterInterface.queryStatus();
                Log.e("querystatus", String.valueOf(querystatus));
                DateFormat dateformatforprint = new SimpleDateFormat("MMM.dd,yyyy");
                Date dateformatprint = new Date();
                String datetoprint = dateformatforprint.format(dateformatprint).toString();
                DateFormat timeformattoprint = new SimpleDateFormat("HH:mm");
                Date timeformat = new Date();
                String timetoprint = timeformattoprint.format(timeformat).toString();
                String finalStation = "";
                Log.e("asdasd", "asdasd");
                if (print >= 0) {
                    byte[] arryTitle = null;
                    byte[] arryTrx = null;
                    byte[] arrySubtitle = null;
                    byte[] arryBody1 = null;
                    byte[] arryspace1 = null;
                    byte[] arryFooter = null;
                    //test
                    try {
                        arryTitle = ("\n" + "TRIPKO" + "\n" + "\n").getBytes("UTF-8");
                        arryTrx = ("TRX: " + transaction_no + "\n" +
                                trace_no + "\n").getBytes("UTF-8");
                        arrySubtitle = ("Date & Time  : " + datetoprint + " " + timetoprint + "\n" +
                                "Merchant Name: " + subcompany_name.toUpperCase() + "\n" +
                                "Branch       : " + terminal_name.toUpperCase() + "\n" +
                                "-------------------------------" + "\n" +
                                "\n").getBytes("UTF-8");
                        arryBody1 = ("Card No. : " + "  **** **** **** " + print_card_no + "\n" +
                                "Trans Type : " + "    " + type_name.toUpperCase() + "\n" +
                                "Current Balance  : " + print_balance + "\n" +
                                "-------------------------------" + "\n" +
                                "\n").getBytes("UTF-8");
                        arryFooter = ("Customer Service" + "\n"
                                + "Hotline#: TRIPKO(678-1234)" + "\n" +
                                "\n").getBytes("UTF-8");
                        arryspace1 = "\n".getBytes("UTF-8");
                    } catch (Throwable e) {

                        e.printStackTrace();
                    }
                    begin();
                    if (querystatus == 1) {

                        writeLineBreak(20);
                        write(arryspace1);
                        alignment(1);
                        Fontsize(16);
                        boldFont(2);
                        doublewidth();
                        write(arryTitle);
                        backtonormal();
                        nextline();

                        Fontsize(0);
                        write(arryTrx);
                        alignment(0);
                        write(arrySubtitle);
                        write(arryBody1);

                        alignment(1);
                        write(arryFooter);
                        write(arryspace1);
                        write(arryspace1);
                        write(arryspace1);
                        write(arryspace1);

                        insertData(company_id,
                                subcompany_id,
                                terminal_id,
                                setting_control_no,
                                Cardno,
                                Balance,
                                transaction_no,
                                trace_no,
                                device_serial);
                        setting_last_transaction_no += 1;
                        ref_trace_no += 1;
                        updateTicket(String.valueOf(setting_last_transaction_no),
                                String.valueOf(ref_trace_no));
                        DBBackup();
                        end();
                        btnCheckBalance.setEnabled(true);
                        btnCheckBalance.setClickable(true);
                        Intent intent2 = new Intent(getContext(), UpdateSendingServices.class);
                        getActivity().startService(intent2);
                    } else {
                        //OpenNoPaper();
                    }
                }
                PrinterInterface.close();
            }
        });
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                totalBalance.setText("P 0.00");
                btnCheckBalance.setEnabled(true);
                btnCheckBalance.setClickable(true);
            }
        });

        prettyDialog.dismiss();
    }
})
.show();

I expect that it will not print twice even I clicked the "YES" pretty dialog button.

Body:
i think you can just do a trick like this

create a count variable  count=0;. In button click, validate condition such that if(count==0) show dialog and make count = 1. (with this dialog will not open second time) while dismissing dialog make count = 0 again.

I think this will work

Hope it helps.

if(count == 0){
count = 1 ;
//showdialog process
}

and right before dismiss()

  ......
  count = 0;
  prettyDialog.dismiss();


来源: stackexchange

问:
Docker - Postgres and pgAdmin 4 : Connection refused
Newbie with docker, I am trying to connect throught localhost my pgAdmin container to the postgres one.

```<code>CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                         NAMES
0b00555238ba        dpage/pgadmin4      "/entrypoint.sh"         43 minutes ago      Up 43 minutes       0.0.0.0:80->80/tcp, 443/tcp   pedantic_turing
e79fb6440a95        postgres            "docker-entrypoint.s…"   About an hour ago   Up About an hour    0.0.0.0:5432->5432/tcp        pg-docker
</code>```

I succeed connecting with psql command.

```<code>psql -h localhost -U postgres -d postgres
</code>```

But when I create the server on pgAdmin with the same parameters as psql I got the following error.

Unable to connect to server:

could not connect to server: Connection refused Is the server running
  on host "localhost" (127.0.0.1) and accepting TCP/IP connections on
  port 5432? could not connect to server: Address not available Is the
  server running on host "localhost" (::1) and accepting TCP/IP
  connections on port 5432?

I succeed to connect throught the IPAddress given by docker inspect on the container.

By the way, I checked postgresql.conf and assert that listen_addresses = '*' and also that pg_hba.conf contain host all all all md5.

But I don't get it, why shouldn't I be able to use the localhost address ? And why does docker even give me an address that is not local ?

答:
In this case:

Pgadmin fails to connect to localhost, but psql works from outside docker.

both pgadmin & Postgres are running as Containers

Although you haven't indicated if you are doing so, ideally both containers could be part of a custom bridge network for automatic DNS resolution.

If not added explicitly they will be part of the default bridge network.

To find out the networks created in your docker runtime, type:
$ docker network ls

Some networks will be listed in the console, maybe you'll find a [name]_default it should be your network.

Execute
docker network inspect [name]_default
it'll show up a bunch of information, for us the most important is IPv4Address, something like this:
"7c3cd7532ab8aacc70830afb74adad7296d9c8ddd725c498af2d7ee2d2c2aadd": {
                "Name": "intime_postegres_1",
                "EndpointID": "56a9cb574469f22259497b72719f9f4a3e555b09f95058fcf389ef5287381f28",
                "MacAddress": "02:42:ac:12:00:02",
                "IPv4Address": "172.18.0.2/16",
                "IPv6Address": ""
            }

Instead of using localhost for the server name/ip in the pgAdmin new server dialog, connect to the postgres instance's "IPv4Address".

In my case connecting at 172.18.0.2:5432, worked like a charm.

ContentLicense: CC BY-SA 4.0

Body:
Newbie with docker, I am trying to connect throught localhost my pgAdmin container to the postgres one.

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                         NAMES
0b00555238ba        dpage/pgadmin4      "/entrypoint.sh"         43 minutes ago      Up 43 minutes       0.0.0.0:80->80/tcp, 443/tcp   pedantic_turing
e79fb6440a95        postgres            "docker-entrypoint.s…"   About an hour ago   Up About an hour    0.0.0.0:5432->5432/tcp        pg-docker

I succeed connecting with psql command.

psql -h localhost -U postgres -d postgres

But when I create the server on pgAdmin with the same parameters as psql I got the following error.

Unable to connect to server:

could not connect to server: Connection refused Is the server running
  on host "localhost" (127.0.0.1) and accepting TCP/IP connections on
  port 5432? could not connect to server: Address not available Is the
  server running on host "localhost" (::1) and accepting TCP/IP
  connections on port 5432?

I succeed to connect throught the IPAddress given by docker inspect on the container.

By the way, I checked postgresql.conf and assert that listen_addresses = '*' and also that pg_hba.conf contain host all all all md5.

But I don't get it, why shouldn't I be able to use the localhost address ? And why does docker even give me an address that is not local ?


问:
TinyMCE: Copy-Paste from Google Docs
Folks,

My company needs to support the following workflow:
- There's rich content getting created in Google Docs (with simple formatting - bold/italic, as well as hyperlinks)
- That content is then pasted into an internal CMS that uses TinyMCE.

Problem: all formatting gets lost when pasting stuff in.

Already tried the "paste from Word" plugin - it doesn't work.

Please advise. Thank you!

UPDATE:
I narrowed the problem down to Google Chrome. Firefox works just fine. I also used the paste_pre_processing() callbacks - the data gets corrupted before getting in there.

答:
I know this question was asked a long time ago however I am making an application that requires a copy and paste from google drive into tiny mce. This is actually fairly simple with the free paste plugin. Simply remove the filters so that it can copy in all of the data.

```<code> tinymce.init({
    selector: 'textarea',
    plugins: "paste",
    paste_data_images: true,
    paste_enable_default_filters: false,
    paste_remove_styles_if_webkit: false
 });
</code>```

ContentLicense: CC BY-SA 3.0

Title: TinyMCE: Copy-Paste from Google Docs

Body:
I know this question was asked a long time ago however I am making an application that requires a copy and paste from google drive into tiny mce. This is actually fairly simple with the free paste plugin. Simply remove the filters so that it can copy in all of the data.

 tinymce.init({
    selector: 'textarea',
    plugins: "paste",
    paste_data_images: true,
    paste_enable_default_filters: false,
    paste_remove_styles_if_webkit: false
 });


问:
Map doesn't exist on Observable<Object> with angular 6.0.0 and rxjs 6.1.0
Hi I'm trying to follow a tutorial on angular but the tutorial was made in September. I believe the person used angular-cli 1.3.2. I'm not sure which version of rxjs he was using. I'm using angular cli 6.0.0 and angular 6 with rxjs 6.1.0.

I am running into a problem where calling .map on observable is not found.
ERROR in xxx/xxx/dataService.ts(19,14): error TS2339: Property 'map' does not exist on type 'Observable<Object>'.
I looked into the Observable class and I don't see a function called map.

Is there a new way in angular 6 or rxjs to achieve what the tutorial is trying to do?

Here is my .ts file:

```<code>import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { map } from 'rxjs/operators';

@Injectable()
export class DataService {

    constructor(private http: HttpClient) {

    }

    public products = [

    ];

    loadProducts() {
        return this.http.get("/api/products")
            .map((data: any[]) => {
                this.products = data;
                return true;
            });
    }
}
</code>```

This is the output from ng --version

```<code>λ ng --version

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/

Angular CLI: 6.0.0
Node: 8.11.1
OS: win32 x64
Angular: 6.0.0
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.6.0
@angular-devkit/build-angular     0.6.0
@angular-devkit/build-optimizer   0.6.0
@angular-devkit/core              0.6.0
@angular-devkit/schematics        0.6.0 (cli-only)
@ngtools/webpack                  6.0.0
@schematics/angular               0.6.0 (cli-only)
@schematics/update                0.6.0 (cli-only)
rxjs                              6.1.0
typescript                        2.7.2
webpack                           4.6.0
</code>```

I did a little digging and in my node_modules/rxjs/observable folder there is no map.* file

```<code>λ ls -R rxjs\observable
'rxjs\observable':
ArrayLikeObservable.d.ts            IfObservable.d.ts             combineLatest.d.ts       if.js.map
ArrayLikeObservable.js              IfObservable.js               combineLatest.js         interval.d.ts
ArrayLikeObservable.js.map          IfObservable.js.map           combineLatest.js.map     interval.js
ArrayObservable.d.ts                IntervalObservable.d.ts       concat.d.ts              interval.js.map
ArrayObservable.js                  IntervalObservable.js         concat.js                merge.d.ts
ArrayObservable.js.map              IntervalObservable.js.map     concat.js.map            merge.js
BoundCallbackObservable.d.ts        IteratorObservable.d.ts       defer.d.ts               merge.js.map
BoundCallbackObservable.js          IteratorObservable.js         defer.js                 never.d.ts
BoundCallbackObservable.js.map      IteratorObservable.js.map     defer.js.map             never.js
BoundNodeCallbackObservable.d.ts    NeverObservable.d.ts          dom/                     never.js.map
BoundNodeCallbackObservable.js      NeverObservable.js            empty.d.ts               of.d.ts
BoundNodeCallbackObservable.js.map  NeverObservable.js.map        empty.js                 of.js
ConnectableObservable.d.ts          PairsObservable.d.ts          empty.js.map             of.js.map
ConnectableObservable.js            PairsObservable.js            forkJoin.d.ts            onErrorResumeNext.d.ts
ConnectableObservable.js.map        PairsObservable.js.map        forkJoin.js              onErrorResumeNext.js
DeferObservable.d.ts                PromiseObservable.d.ts        forkJoin.js.map          onErrorResumeNext.js.map DeferObservable.js                  PromiseObservable.js          from.d.ts                pairs.d.ts
DeferObservable.js.map              PromiseObservable.js.map      from.js                  pairs.js
EmptyObservable.d.ts                RangeObservable.d.ts          from.js.map              pairs.js.map
EmptyObservable.js                  RangeObservable.js            fromArray.d.ts           race.d.ts
EmptyObservable.js.map              RangeObservable.js.map        fromArray.js             race.js
ErrorObservable.d.ts                ScalarObservable.d.ts         fromArray.js.map         race.js.map
ErrorObservable.js                  ScalarObservable.js           fromEvent.d.ts           range.d.ts
ErrorObservable.js.map              ScalarObservable.js.map       fromEvent.js             range.js
ForkJoinObservable.d.ts             SubscribeOnObservable.d.ts    fromEvent.js.map         range.js.map
ForkJoinObservable.js               SubscribeOnObservable.js      fromEventPattern.d.ts    throw.d.ts
ForkJoinObservable.js.map           SubscribeOnObservable.js.map  fromEventPattern.js      throw.js
FromEventObservable.d.ts            TimerObservable.d.ts          fromEventPattern.js.map  throw.js.map
FromEventObservable.js              TimerObservable.js            fromIterable.d.ts        timer.d.ts
FromEventObservable.js.map          TimerObservable.js.map        fromIterable.js          timer.js
FromEventPatternObservable.d.ts     UsingObservable.d.ts          fromIterable.js.map      timer.js.map
FromEventPatternObservable.js       UsingObservable.js            fromPromise.d.ts         using.d.ts
FromEventPatternObservable.js.map   UsingObservable.js.map        fromPromise.js           using.js
FromObservable.d.ts                 bindCallback.d.ts             fromPromise.js.map       using.js.map
FromObservable.js                   bindCallback.js               generate.d.ts            zip.d.ts
FromObservable.js.map               bindCallback.js.map           generate.js              zip.js
GenerateObservable.d.ts             bindNodeCallback.d.ts         generate.js.map          zip.js.map
GenerateObservable.js               bindNodeCallback.js           if.d.ts
GenerateObservable.js.map           bindNodeCallback.js.map       if.js

'rxjs\observable/dom':
AjaxObservable.d.ts  AjaxObservable.js.map  WebSocketSubject.js      ajax.d.ts  ajax.js.map     webSocket.js
AjaxObservable.js    WebSocketSubject.d.ts  WebSocketSubject.js.map  ajax.js    webSocket.d.ts  webSocket.js.map
</code>```

答:
i was facing the same problem.
lets change the way to import map. use the code which i have written below

import { map } from "rxjs/operators";

then use pipe with map. see the example for better understanding

```<code>import {Http,Headers,Response} from '@angular/http';
import { map } from "rxjs/operators";

@Injectable({
  providedIn: 'root'
})
export class ContactServiceService {

  constructor(private http:Http) { }

  getContactList(){
    return this.http.get('http://localhost:3000/contact')
    .pipe(map(res => res.json()));
  }

}

</code>```

Body:
Hi I'm trying to follow a tutorial on angular but the tutorial was made in September. I believe the person used angular-cli 1.3.2. I'm not sure which version of rxjs he was using. I'm using angular cli 6.0.0 and angular 6 with rxjs 6.1.0.

I am running into a problem where calling .map on observable is not found.
ERROR in xxx/xxx/dataService.ts(19,14): error TS2339: Property 'map' does not exist on type 'Observable<Object>'.
I looked into the Observable class and I don't see a function called map.

Is there a new way in angular 6 or rxjs to achieve what the tutorial is trying to do?

Here is my .ts file:

import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { map } from 'rxjs/operators';

@Injectable()
export class DataService {

    constructor(private http: HttpClient) {

    }

    public products = [

    ];

    loadProducts() {
        return this.http.get("/api/products")
            .map((data: any[]) => {
                this.products = data;
                return true;
            });
    }
}

This is the output from ng --version

λ ng --version

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/

Angular CLI: 6.0.0
Node: 8.11.1
OS: win32 x64
Angular: 6.0.0
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.6.0
@angular-devkit/build-angular     0.6.0
@angular-devkit/build-optimizer   0.6.0
@angular-devkit/core              0.6.0
@angular-devkit/schematics        0.6.0 (cli-only)
@ngtools/webpack                  6.0.0
@schematics/angular               0.6.0 (cli-only)
@schematics/update                0.6.0 (cli-only)
rxjs                              6.1.0
typescript                        2.7.2
webpack                           4.6.0

I did a little digging and in my node_modules/rxjs/observable folder there is no map.* file

λ ls -R rxjs\observable
'rxjs\observable':
ArrayLikeObservable.d.ts            IfObservable.d.ts             combineLatest.d.ts       if.js.map
ArrayLikeObservable.js              IfObservable.js               combineLatest.js         interval.d.ts
ArrayLikeObservable.js.map          IfObservable.js.map           combineLatest.js.map     interval.js
ArrayObservable.d.ts                IntervalObservable.d.ts       concat.d.ts              interval.js.map
ArrayObservable.js                  IntervalObservable.js         concat.js                merge.d.ts
ArrayObservable.js.map              IntervalObservable.js.map     concat.js.map            merge.js
BoundCallbackObservable.d.ts        IteratorObservable.d.ts       defer.d.ts               merge.js.map
BoundCallbackObservable.js          IteratorObservable.js         defer.js                 never.d.ts
BoundCallbackObservable.js.map      IteratorObservable.js.map     defer.js.map             never.js
BoundNodeCallbackObservable.d.ts    NeverObservable.d.ts          dom/                     never.js.map
BoundNodeCallbackObservable.js      NeverObservable.js            empty.d.ts               of.d.ts
BoundNodeCallbackObservable.js.map  NeverObservable.js.map        empty.js                 of.js
ConnectableObservable.d.ts          PairsObservable.d.ts          empty.js.map             of.js.map
ConnectableObservable.js            PairsObservable.js            forkJoin.d.ts            onErrorResumeNext.d.ts
ConnectableObservable.js.map        PairsObservable.js.map        forkJoin.js              onErrorResumeNext.js
DeferObservable.d.ts                PromiseObservable.d.ts        forkJoin.js.map          onErrorResumeNext.js.map DeferObservable.js                  PromiseObservable.js          from.d.ts                pairs.d.ts
DeferObservable.js.map              PromiseObservable.js.map      from.js                  pairs.js
EmptyObservable.d.ts                RangeObservable.d.ts          from.js.map              pairs.js.map
EmptyObservable.js                  RangeObservable.js            fromArray.d.ts           race.d.ts
EmptyObservable.js.map              RangeObservable.js.map        fromArray.js             race.js
ErrorObservable.d.ts                ScalarObservable.d.ts         fromArray.js.map         race.js.map
ErrorObservable.js                  ScalarObservable.js           fromEvent.d.ts           range.d.ts
ErrorObservable.js.map              ScalarObservable.js.map       fromEvent.js             range.js
ForkJoinObservable.d.ts             SubscribeOnObservable.d.ts    fromEvent.js.map         range.js.map
ForkJoinObservable.js               SubscribeOnObservable.js      fromEventPattern.d.ts    throw.d.ts
ForkJoinObservable.js.map           SubscribeOnObservable.js.map  fromEventPattern.js      throw.js
FromEventObservable.d.ts            TimerObservable.d.ts          fromEventPattern.js.map  throw.js.map
FromEventObservable.js              TimerObservable.js            fromIterable.d.ts        timer.d.ts
FromEventObservable.js.map          TimerObservable.js.map        fromIterable.js          timer.js
FromEventPatternObservable.d.ts     UsingObservable.d.ts          fromIterable.js.map      timer.js.map
FromEventPatternObservable.js       UsingObservable.js            fromPromise.d.ts         using.d.ts
FromEventPatternObservable.js.map   UsingObservable.js.map        fromPromise.js           using.js
FromObservable.d.ts                 bindCallback.d.ts             fromPromise.js.map       using.js.map
FromObservable.js                   bindCallback.js               generate.d.ts            zip.d.ts
FromObservable.js.map               bindCallback.js.map           generate.js              zip.js
GenerateObservable.d.ts             bindNodeCallback.d.ts         generate.js.map          zip.js.map
GenerateObservable.js               bindNodeCallback.js           if.d.ts
GenerateObservable.js.map           bindNodeCallback.js.map       if.js

'rxjs\observable/dom':
AjaxObservable.d.ts  AjaxObservable.js.map  WebSocketSubject.js      ajax.d.ts  ajax.js.map     webSocket.js
AjaxObservable.js    WebSocketSubject.d.ts  WebSocketSubject.js.map  ajax.js    webSocket.d.ts  webSocket.js.map

Body:
i was facing the same problem.
lets change the way to import map. use the code which i have written below

import { map } from "rxjs/operators";

then use pipe with map. see the example for better understanding

import {Http,Headers,Response} from '@angular/http';
import { map } from "rxjs/operators";

@Injectable({
  providedIn: 'root'
})
export class ContactServiceService {

  constructor(private http:Http) { }

  getContactList(){
    return this.http.get('http://localhost:3000/contact')
    .pipe(map(res => res.json()));
  }

}


问:
Flex row force child image to shrink height to 100% of other content
Take the following example;

.row {
  background: #F88;
  margin-top: 20px;
}

.cont {
  display: block;
  height: 82px;
  width: 82px;
  background-color: #0AF;
}

.txt {
  background-color: #0C0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div class="row no-gutters">
    <div class="col-auto"><div class="cont">82px</div></div>
    <div class="col-auto"><img src="https://i.imgur.com/WIxmfZb.png" /></div>
    <div class="col"><div class="txt">Text content</div></div>
  </div>
</div></code>```

I would like the 100x100 image to shrink to the height of the next-tallest column (in the example this would be the 82px block element in the 1st column) while maintaining its aspect ratio.

So far I have attempted various different combinations of flex-basis, flex-shrink, and one solution which I managed to kind of get to work is to set the style of the image to height: 0; min-height: 100%; which works in the inspector, however;

It exposed a bug in Chrome, where the width of the image is initially 0 until you resize the window, which will pop it into the correct aspect ratio

It didn't work in IE >_>

I'm pretty sure it violates some kind of international law against torturing the next dev that would have to pick my code up

After a couple of hours of brute-force I've yet to find a solution where

The image correctly fills 100% of the flex height (ignoring its own height)

The image maintains its aspect ratio

The image doesn't overflow

The image isn't absolutely positioned

The size of the image isn't explicitly set

The ideal solution should look like this;

Any help would be much appreciated.

答:
I set the image to the same height as the first column by restricting its width to the same dimension:

```<code>.same-as-column-1 {
  max-width: 82px;
}
</code>```

I wasn't sure if the third column was allowed to be taller, it locks up nicely if restricted to the same height as well but not sure that works for real use case.

Either way the image seems to meet the requirements, fills 100% of the flex height, maintains its aspect ratio, doesn't overflow, and isn't absolutely positioned/

.row {
  background: #F88;
  margin-top: 20px;
}

.cont {
  display: block;
  height: 82px;
  width: 82px;
  background-color: #0AF;
}

.same-as-column-1 {
  max-width: 82px;
}

.txt {
  background-color: #0C0;
  max-height: 82px;
  overflow-y: scroll;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
  <div class="row no-gutters flex-row flex-nowrap">
    <div class="col-auto">
      <div class="cont">
        82px
      </div>
    </div>
    <div class="col-auto">
      <img class="same-as-column-1" src="https://i.imgur.com/WIxmfZb.png" />
    </div>
    <div class="col">
      <div class="txt">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin sit amet massa quis nunc porta rutrum nec ac tellus. Phasellus eget ligula tristique, tristique elit ac, mollis eros. Aenean lobortis volutpat sem, et eleifend metus faucibus sed.
          Vivamus at varius nibh. Suspendisse rhoncus posuere elit sed tincidunt. Curabitur blandit in ipsum ut tempor. Mauris et eleifend justo. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Mauris sollicitudin
          vehicula urna, egestas cursus dolor efficitur id. Aenean tempus vestibulum mauris, a accumsan sem vulputate quis. Maecenas tempor rhoncus molestie. Proin erat metus, cursus lacinia sodales non, malesuada non felis.</p>

        <p>Ut ac luctus elit. Mauris id ipsum id dolor hendrerit rhoncus. Fusce a ligula gravida, porttitor magna a, feugiat est. Maecenas at leo mi. Phasellus volutpat ex vitae nisl euismod, a luctus odio tristique. Maecenas eget tincidunt eros. Etiam auctor
          velit at felis condimentum, sit amet feugiat dolor auctor. Mauris tempus nulla quis ullamcorper porttitor. Etiam nec neque congue, molestie diam vel, suscipit dui. Sed mollis id dolor ut lacinia. Nulla facilisi. Suspendisse ut pellentesque metus.
          In tincidunt ante at pretium mattis. Aliquam egestas neque vel nisi cursus rhoncus.</p>
      </div>
    </div>
  </div>
</div></code>```

Body:
Take the following example;

.row {
  background: #F88;
  margin-top: 20px;
}

.cont {
  display: block;
  height: 82px;
  width: 82px;
  background-color: #0AF;
}

.txt {
  background-color: #0C0;
}

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>

82px

Text content

I would like the 100x100 image to shrink to the height of the next-tallest column (in the example this would be the 82px block element in the 1st column) while maintaining its aspect ratio.

So far I have attempted various different combinations of flex-basis, flex-shrink, and one solution which I managed to kind of get to work is to set the style of the image to height: 0; min-height: 100%; which works in the inspector, however;

It exposed a bug in Chrome, where the width of the image is initially 0 until you resize the window, which will pop it into the correct aspect ratio

It didn't work in IE >_>

I'm pretty sure it violates some kind of international law against torturing the next dev that would have to pick my code up

After a couple of hours of brute-force I've yet to find a solution where

The image correctly fills 100% of the flex height (ignoring its own height)

The image maintains its aspect ratio

The image doesn't overflow

The image isn't absolutely positioned

The size of the image isn't explicitly set

The ideal solution should look like this;

Any help would be much appreciated.

Body:
I set the image to the same height as the first column by restricting its width to the same dimension:

.same-as-column-1 {
  max-width: 82px;
}

I wasn't sure if the third column was allowed to be taller, it locks up nicely if restricted to the same height as well but not sure that works for real use case.

Either way the image seems to meet the requirements, fills 100% of the flex height, maintains its aspect ratio, doesn't overflow, and isn't absolutely positioned/

.row {
  background: #F88;
  margin-top: 20px;
}

.cont {
  display: block;
  height: 82px;
  width: 82px;
  background-color: #0AF;
}

.same-as-column-1 {
  max-width: 82px;
}

.txt {
  background-color: #0C0;
  max-height: 82px;
  overflow-y: scroll;
}

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
  <div class="row no-gutters flex-row flex-nowrap">
    <div class="col-auto">
      <div class="cont">
        82px
      </div>
    </div>
    <div class="col-auto">
      <img class="same-as-column-1" src="https://i.imgur.com/WIxmfZb.png" />
    </div>
    <div class="col">
      <div class="txt">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin sit amet massa quis nunc porta rutrum nec ac tellus. Phasellus eget ligula tristique, tristique elit ac, mollis eros. Aenean lobortis volutpat sem, et eleifend metus faucibus sed.
          Vivamus at varius nibh. Suspendisse rhoncus posuere elit sed tincidunt. Curabitur blandit in ipsum ut tempor. Mauris et eleifend justo. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Mauris sollicitudin
          vehicula urna, egestas cursus dolor efficitur id. Aenean tempus vestibulum mauris, a accumsan sem vulputate quis. Maecenas tempor rhoncus molestie. Proin erat metus, cursus lacinia sodales non, malesuada non felis.</p>

        <p>Ut ac luctus elit. Mauris id ipsum id dolor hendrerit rhoncus. Fusce a ligula gravida, porttitor magna a, feugiat est. Maecenas at leo mi. Phasellus volutpat ex vitae nisl euismod, a luctus odio tristique. Maecenas eget tincidunt eros. Etiam auctor
          velit at felis condimentum, sit amet feugiat dolor auctor. Mauris tempus nulla quis ullamcorper porttitor. Etiam nec neque congue, molestie diam vel, suscipit dui. Sed mollis id dolor ut lacinia. Nulla facilisi. Suspendisse ut pellentesque metus.
          In tincidunt ante at pretium mattis. Aliquam egestas neque vel nisi cursus rhoncus.</p>
      </div>
    </div>
  </div>
</div>


问:
python pandas.Series.isin with case insensitive
I want to filter out some rows with one of DataFrame's column which data is in a list.

```<code>df[df['column'].isin(mylist)]
</code>```

But I found that it's case sensitive.
Is there any method using ".isin()" with case insensitive?

答:
I would put my list into a CSV and load it as a dataframe.  Afterwards I would run the command:

```<code>df_done = df[df["Server Name"].str.lower().isin(df_compare["Computer Name"].str.lower())]
</code>```

This avoids using for loop and can handle large amounts of data easily.

```<code>df = 5000 rows
df_compare = 1000 rows
</code>```

Body:
I want to filter out some rows with one of DataFrame's column which data is in a list.

df[df['column'].isin(mylist)]

But I found that it's case sensitive.
Is there any method using ".isin()" with case insensitive?

Body:
I would put my list into a CSV and load it as a dataframe.  Afterwards I would run the command:

df_done = df[df["Server Name"].str.lower().isin(df_compare["Computer Name"].str.lower())]

This avoids using for loop and can handle large amounts of data easily.

df = 5000 rows
df_compare = 1000 rows


问:
How would I remove words from dictionary key lists that contain 6 or more letters?
I can't figure out how to create a function that is able to remove words with less than 6 characters from each list that is a value of a key of a dictionary.

I'm trying to pop each word that is less than 6 out of the list but I'm getting "TypeError: cannot unpack non-iterable int object". I don't know if the method I am using is correct.

```<code>def remove_word(words_dict):
    items_list = list(words_dict.items())

    for key, value in range(len(items_list) -1, -1, -1):
        if len(value) < 6:
            items_list.pop()
    words_dict = items_list.sort()
    return words_dict
</code>```

```<code>words_dict = {'colours' : ['red', 'blue', 'green'],
    'places' : ['america', 'china', 'malaysia', 'argentina', 'india'],
    'animals' : ['lion', 'cat', 'dog', 'wolf', 'monkey',
                'zebra'],
    }
</code>```

Should print:

```<code>1.
colours : []
places : ['america', 'malaysia', 'argentina']
animals : ['monkey']
</code>```

答:
You can do this with nested loops:

```<code>for key in words_dict:
    words_dict[key] = [i for i in dict[key] if len(i) >= 6]
</code>```

A loop comprehension (building a new list based on criteria from the previous list) is actually the easiest way to accomplish this task, because of how python handles list iterators. You can actually put that inside a dict comprehension as well:

```<code>new_words_dict = {key: [i for i in value if len(i) >= 6] for key, value in words_dict.items()}
</code>```

Body:
I can't figure out how to create a function that is able to remove words with less than 6 characters from each list that is a value of a key of a dictionary.

I'm trying to pop each word that is less than 6 out of the list but I'm getting "TypeError: cannot unpack non-iterable int object". I don't know if the method I am using is correct.

def remove_word(words_dict):
    items_list = list(words_dict.items())

    for key, value in range(len(items_list) -1, -1, -1):
        if len(value) < 6:
            items_list.pop()
    words_dict = items_list.sort()
    return words_dict

words_dict = {'colours' : ['red', 'blue', 'green'],
    'places' : ['america', 'china', 'malaysia', 'argentina', 'india'],
    'animals' : ['lion', 'cat', 'dog', 'wolf', 'monkey',
                'zebra'],
    }

Should print:

1.
colours : []
places : ['america', 'malaysia', 'argentina']
animals : ['monkey']

Body:
You can do this with nested loops:

for key in words_dict:
    words_dict[key] = [i for i in dict[key] if len(i) >= 6]

A loop comprehension (building a new list based on criteria from the previous list) is actually the easiest way to accomplish this task, because of how python handles list iterators. You can actually put that inside a dict comprehension as well:

new_words_dict = {key: [i for i in value if len(i) >= 6] for key, value in words_dict.items()}


问:
Error "NU3034 This package is signed but not by a trusted signer"
Today I found myself unable to restore NuGet packages on my machine. Doing so produces errors resembling:

Myproject.csproj : error NU3034: Package 'SomePackage 1.2.3' from source 'https://api.nuget.org/v3/index.json': This package is signed but not by a trusted signer.

How can I fix package restore?

答:
Running nuget trusted-signers list showed I had one trusted signer by the name of "NuGet Test Developer".

This was present in %appdata%\NuGet\NuGet.Config under the <trustedSigners> node.

Commenting out the entire <trustedSigners> node allowed restore to complete successfully.

It may also be possible to use nuget trusted-signers Add -Name nuget.org to explicitly trust packages from nuget.org, but in my case I don't believe I need the "NuGet Test Developer" signator.

It may also be possible to use nuget config -set signatureValidationMode=accept to disable signature validation altogether.

I found this article useful for learning more about NuGet package signing.


问:
Autocompletetextview return Parameter specified as non-null is null
I implemented this custom autocompletetextview in my application. Just when user tried to type some text, the application stopped. I checked my web api is working fine. I'm new to kotlin so I don't really know how to solve the problem.

This is my custom adapter looks like

```<code>class AutoCompleteAdapter(context: Context, resource: Int) : ArrayAdapter<String>(context, resource), Filterable {
    private val mlistData: ArrayList<String>

    init {
        mlistData = ArrayList()
    }

    fun setData(list: ArrayList<String>) {
        mlistData.clear()
        mlistData.addAll(list)
    }

    override fun getCount(): Int {
        return mlistData.size
    }

    override fun getItem(position: Int): String? {
        return mlistData[position]
    }

    /**
     * Used to Return the full object directly from adapter.
     *
     * @param position
     * @return
     */
    fun getObject(position: Int): String {
        return mlistData[position]
    }

    override fun getFilter(): Filter {
        return object : Filter() {
            override fun performFiltering(constraint: CharSequence?): FilterResults {
                val filterResults = FilterResults()
                if (constraint != null) {
                    filterResults.values = mlistData
                    filterResults.count = mlistData.size
                }
                return filterResults
            }

            override fun publishResults(constraint: CharSequence, results: FilterResults?) {
                if (results != null && results.count > 0) {
                    notifyDataSetChanged()
                } else {
                    notifyDataSetInvalidated()
                }
            }
        }
    }
}
</code>```

This is the code where I use the autocompleteTextView

```<code>class RegistrationInformationActivity : AppCompatActivity(), AdapterView.OnItemSelectedListener {

    private lateinit var autoCompleteAdapter: AutoCompleteAdapter
    lateinit var handler: Handler
    private val TRIGGER_AUTO_COMPLETE = 100
    private val AUTO_COMPLETE_DELAY: Long = 300

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_registration_information)

        autoCompleteAdapter = AutoCompleteAdapter(this, android.R.layout.simple_dropdown_item_1line)
        register_provinsi.threshold = 2
        register_provinsi.setAdapter(autoCompleteAdapter)
        register_provinsi.setOnItemClickListener{ parent, view, position, id ->
                val result = autoCompleteAdapter.getObject(position)
                register_provinsi.setText(result)
            }
        register_provinsi.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                handler.removeMessages(TRIGGER_AUTO_COMPLETE)
                handler.sendEmptyMessageDelayed(
                    TRIGGER_AUTO_COMPLETE,
                    AUTO_COMPLETE_DELAY
                )
            }
            override fun afterTextChanged(s: Editable) {}
        })

        handler = Handler(Handler.Callback { msg ->
            if (msg.what == TRIGGER_AUTO_COMPLETE) {
                if (!TextUtils.isEmpty(register_provinsi.text))
                    val string = register_provinsi.text.toString()
                    loadProvinsi(string)
                }
            }
            false
        })

    }
</code>```

This where I make call to web api using volley

```<code>private fun loadProvinsi(provinsi: String) {
        val stringRequest = StringRequest(
            Request.Method.GET, EndPoints.URL_GET_PROVINSI + "&keyword=" + provinsi,
            Response.Listener<String> { s ->
                try {
                    val obj = JSONObject(s)
                    val list = ArrayList<String>()
                    if (!obj.equals("")) {
                        val array = obj.getJSONArray("list")
                        for (i in 0 until array.length() - 1) {
                            val objectProvinsi = array.getJSONObject(i)
                            objectProvinsi.getString("value")
                            list.add(objectProvinsi.getString("value"))
                        }
                    } else {
                        Toast.makeText(applicationContext, obj.getString("message"), Toast.LENGTH_LONG).show()
                    }
                    autoCompleteAdapter.setData(list)
                    autoCompleteAdapter.notifyDataSetChanged()
                } catch (e: JSONException) {
                    e.printStackTrace()
                }
            },
            Response.ErrorListener { volleyError ->
                Toast.makeText(applicationContext, volleyError.message, Toast.LENGTH_LONG).show()
            })
        val requestQueue = Volley.newRequestQueue(this)
        requestQueue.add<String>(stringRequest)
    }
</code>```

I already implemented methods from AdapterView.OnItemSelectedListener. The logged from the app is always

```<code>E/UncaughtException: java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter constraint
        at com.example.bookingonline.model.AutoCompleteAdapter$getFilter$1.publishResults(AutoCompleteAdapter.kt)
        at android.widget.Filter$ResultsHandler.handleMessage(Filter.java:282)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:145)
        at android.app.ActivityThread.main(ActivityThread.java:5942)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.bookingonline, PID: 16925
    java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter constraint
        at com.example.bookingonline.model.AutoCompleteAdapter$getFilter$1.publishResults(AutoCompleteAdapter.kt)
        at android.widget.Filter$ResultsHandler.handleMessage(Filter.java:282)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:145)
        at android.app.ActivityThread.main(ActivityThread.java:5942)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
</code>```

答:
Change to this

```<code>override fun publishResults(constraint: CharSequence?, results: FilterResults?) {
                if (results != null && results.count > 0) {
                    notifyDataSetChanged()
                } else {
                    notifyDataSetInvalidated()
                }
            }
</code>```

In the error message, it says constraint: CharSequence? is null, but you declare it as non-null (without the question mark), so just add the question mark for it

Body:
I implemented this custom autocompletetextview in my application. Just when user tried to type some text, the application stopped. I checked my web api is working fine. I'm new to kotlin so I don't really know how to solve the problem.

This is my custom adapter looks like

class AutoCompleteAdapter(context: Context, resource: Int) : ArrayAdapter<String>(context, resource), Filterable {
    private val mlistData: ArrayList<String>

    init {
        mlistData = ArrayList()
    }

    fun setData(list: ArrayList<String>) {
        mlistData.clear()
        mlistData.addAll(list)
    }

    override fun getCount(): Int {
        return mlistData.size
    }

    override fun getItem(position: Int): String? {
        return mlistData[position]
    }

    /**
     * Used to Return the full object directly from adapter.
     *
     * @param position
     * @return
     */
    fun getObject(position: Int): String {
        return mlistData[position]
    }

    override fun getFilter(): Filter {
        return object : Filter() {
            override fun performFiltering(constraint: CharSequence?): FilterResults {
                val filterResults = FilterResults()
                if (constraint != null) {
                    filterResults.values = mlistData
                    filterResults.count = mlistData.size
                }
                return filterResults
            }

            override fun publishResults(constraint: CharSequence, results: FilterResults?) {
                if (results != null && results.count > 0) {
                    notifyDataSetChanged()
                } else {
                    notifyDataSetInvalidated()
                }
            }
        }
    }
}

This is the code where I use the autocompleteTextView

class RegistrationInformationActivity : AppCompatActivity(), AdapterView.OnItemSelectedListener {

    private lateinit var autoCompleteAdapter: AutoCompleteAdapter
    lateinit var handler: Handler
    private val TRIGGER_AUTO_COMPLETE = 100
    private val AUTO_COMPLETE_DELAY: Long = 300

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_registration_information)

        autoCompleteAdapter = AutoCompleteAdapter(this, android.R.layout.simple_dropdown_item_1line)
        register_provinsi.threshold = 2
        register_provinsi.setAdapter(autoCompleteAdapter)
        register_provinsi.setOnItemClickListener{ parent, view, position, id ->
                val result = autoCompleteAdapter.getObject(position)
                register_provinsi.setText(result)
            }
        register_provinsi.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                handler.removeMessages(TRIGGER_AUTO_COMPLETE)
                handler.sendEmptyMessageDelayed(
                    TRIGGER_AUTO_COMPLETE,
                    AUTO_COMPLETE_DELAY
                )
            }
            override fun afterTextChanged(s: Editable) {}
        })

        handler = Handler(Handler.Callback { msg ->
            if (msg.what == TRIGGER_AUTO_COMPLETE) {
                if (!TextUtils.isEmpty(register_provinsi.text))
                    val string = register_provinsi.text.toString()
                    loadProvinsi(string)
                }
            }
            false
        })

    }

This where I make call to web api using volley

private fun loadProvinsi(provinsi: String) {
        val stringRequest = StringRequest(
            Request.Method.GET, EndPoints.URL_GET_PROVINSI + "&keyword=" + provinsi,
            Response.Listener<String> { s ->
                try {
                    val obj = JSONObject(s)
                    val list = ArrayList<String>()
                    if (!obj.equals("")) {
                        val array = obj.getJSONArray("list")
                        for (i in 0 until array.length() - 1) {
                            val objectProvinsi = array.getJSONObject(i)
                            objectProvinsi.getString("value")
                            list.add(objectProvinsi.getString("value"))
                        }
                    } else {
                        Toast.makeText(applicationContext, obj.getString("message"), Toast.LENGTH_LONG).show()
                    }
                    autoCompleteAdapter.setData(list)
                    autoCompleteAdapter.notifyDataSetChanged()
                } catch (e: JSONException) {
                    e.printStackTrace()
                }
            },
            Response.ErrorListener { volleyError ->
                Toast.makeText(applicationContext, volleyError.message, Toast.LENGTH_LONG).show()
            })
        val requestQueue = Volley.newRequestQueue(this)
        requestQueue.add<String>(stringRequest)
    }

I already implemented methods from AdapterView.OnItemSelectedListener. The logged from the app is always

E/UncaughtException: java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter constraint
        at com.example.bookingonline.model.AutoCompleteAdapter$getFilter$1.publishResults(AutoCompleteAdapter.kt)
        at android.widget.Filter$ResultsHandler.handleMessage(Filter.java:282)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:145)
        at android.app.ActivityThread.main(ActivityThread.java:5942)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.bookingonline, PID: 16925
    java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter constraint
        at com.example.bookingonline.model.AutoCompleteAdapter$getFilter$1.publishResults(AutoCompleteAdapter.kt)
        at android.widget.Filter$ResultsHandler.handleMessage(Filter.java:282)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:145)
        at android.app.ActivityThread.main(ActivityThread.java:5942)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)

Body:
Change to this

override fun publishResults(constraint: CharSequence?, results: FilterResults?) {
                if (results != null && results.count > 0) {
                    notifyDataSetChanged()
                } else {
                    notifyDataSetInvalidated()
                }
            }

In the error message, it says constraint: CharSequence? is null, but you declare it as non-null (without the question mark), so just add the question mark for it


问:
Textarea remaining characters not working properly
I have a textarea with pre-filled value in it. Now, I have also installed a "character remaining" line underneath the text area.

I'm not been able to achieve the default count value, if you notice on load the word count stays at "250 characters remaining", also note that the value is pre-filled with some text already so the function should count the pre-filled text by default.

The text color changes to yellow once "100 characters are remaining" and to red once "0 characters are remaining". It seems like the color doesn't change back to default when I reach the yellow color and starts removing the text to more than 100 characters.

Can someone help?

document.addEventListener('keyup', function(event) {
  if (event.target.matches('textarea.minchar')) {
    let element = event.target;
    let value = element.value;
    let maxLength = element.maxLength;
    let rechar = element.nextElementSibling;

    rechar.innerText = `${maxLength - Number(value.length)} characters remaining`;

    if (maxLength - Number(value.length) == 0) {
      rechar.style.color = "#E01424";
    } else if (maxLength - Number(value.length) <= 100) {
      rechar.style.color = "#CF7721";
    }
  }
}, false);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-md-10 pl-0">
  <textarea cols="15" rows="4" placeholder="Describe this Extra in brief for your guest" class="minchar" maxlength="250">Save time and return the vehicle at any fuel level. The price includes up to a full tank of petrol/diesel/charge.</textarea>
  <p class="rechar" id="test">250 characters remaining</p>
</div></code>```

答:
I analyzed your question content and found more than one issue there, solving them will give you an open perspective of what is happening. Let me explain.

Define first what you will use in your code.

This will help you to understand your code better, defining useful variables first. So you don't have to call them over and over again. So, I'd suggest you to define your DOM elements references at the very beginning like this:

```<code>var textarea = document.querySelector(".minchar"),
    output = document.querySelector(".rechar");
var maxLength = +textarea.getAttribute("maxlength");
</code>```

Now we have the textarea in a variable, the output div in another and the max length we shoud use.

Handle your remaining characters in a function.

Why is this you may ask? Well, see for yourself how cleaner, readable and simpler does the code change. So, having a simple function that its only job is to update the remaining characters output, will let you run the function whenever you want to update it. It could be when a key is pressed, when the textarea changes, or even when the website is loaded:

The function:

```<code>function outputRemainingCharacters(){
    let used = textarea.value.length;
    output.innerText = `${maxLength - +used} characters remaining`;
}
</code>```

Adding the function to the event listener just when the website is done loading:

```<code>window.onload = outputRemainingCharacters;
</code>```

As easy as that, it will then update your value from the very beginning.

Add a default condition to your if statement.

This is due to, if you don't add a default value, you will never be able to return to the default value as you mention:

```<code>textarea.addEventListener('keydown', function(event) {

    outputRemainingCharacters();
    let used = textarea.value.length;
    if (maxLength - used == 0) {
        output.style.color = "#E01424";
    } else if (maxLength - used <= 100) {
        output.style.color = "#CF7721";
    } else {
        output.style.color = "#000"; //Default color
    }

});
</code>```

As you can see, the event listener is now a lot cleaner. I also would recommend:

Use event listeners for the specific event on the specific element you need.

This will help you not adding extra if statements to match if the event triggered on the element you want. Since we defined the text area at the very beginning, we can now just assign the event listener directly to it.

Note: You should use the event listener keydown instead of keyup. This due to the fact that holding down a key will not trigger the event until the key is up. keydown will be more accurate here. Try holding the space key down while writing to the textbox in the following snippet and see what happens.

Check this example:

var textarea = document.querySelector(".minchar"),
    output = document.querySelector(".rechar");
var maxLength = +textarea.getAttribute("maxlength");

function outputRemainingCharacters(){
    let used = textarea.value.length;
    output.innerText = `${maxLength - +used} characters remaining`;
}

textarea.addEventListener('keydown', function(event) {

    outputRemainingCharacters();
    let used = textarea.value.length;
    if (maxLength - used == 0) {
        output.style.color = "#E01424";
    } else if (maxLength - used <= 100) {
        output.style.color = "#CF7721";
    } else {
        output.style.color = "#000"; //Default color
    }

});

window.onload = outputRemainingCharacters;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-md-10 pl-0">
  <textarea cols="15" rows="4" placeholder="Describe this Extra in brief for your guest" class="minchar" maxlength="250">Save time and return the vehicle at any fuel level. The price includes up to a full tank of petrol/diesel/charge.</textarea>
  <p class="rechar" id="test">250 characters remaining</p>
</div></code>```

Body:
I have a textarea with pre-filled value in it. Now, I have also installed a "character remaining" line underneath the text area.

I'm not been able to achieve the default count value, if you notice on load the word count stays at "250 characters remaining", also note that the value is pre-filled with some text already so the function should count the pre-filled text by default.

The text color changes to yellow once "100 characters are remaining" and to red once "0 characters are remaining". It seems like the color doesn't change back to default when I reach the yellow color and starts removing the text to more than 100 characters.

Can someone help?

document.addEventListener('keyup', function(event) {
  if (event.target.matches('textarea.minchar')) {
    let element = event.target;
    let value = element.value;
    let maxLength = element.maxLength;
    let rechar = element.nextElementSibling;

    rechar.innerText = `${maxLength - Number(value.length)} characters remaining`;

    if (maxLength - Number(value.length) == 0) {
      rechar.style.color = "#E01424";
    } else if (maxLength - Number(value.length) <= 100) {
      rechar.style.color = "#CF7721";
    }
  }
}, false);

  <textarea cols="15" rows="4" placeholder="Describe this Extra in brief for your guest" class="minchar" maxlength="250">Save time and return the vehicle at any fuel level. The price includes up to a full tank of petrol/diesel/charge.</textarea>

250 characters remaining

Body:
I analyzed your question content and found more than one issue there, solving them will give you an open perspective of what is happening. Let me explain.

Define first what you will use in your code.

This will help you to understand your code better, defining useful variables first. So you don't have to call them over and over again. So, I'd suggest you to define your DOM elements references at the very beginning like this:

var textarea = document.querySelector(".minchar"),
    output = document.querySelector(".rechar");
var maxLength = +textarea.getAttribute("maxlength");

Now we have the textarea in a variable, the output div in another and the max length we shoud use.

Handle your remaining characters in a function.

Why is this you may ask? Well, see for yourself how cleaner, readable and simpler does the code change. So, having a simple function that its only job is to update the remaining characters output, will let you run the function whenever you want to update it. It could be when a key is pressed, when the textarea changes, or even when the website is loaded:

The function:

function outputRemainingCharacters(){
    let used = textarea.value.length;
    output.innerText = `${maxLength - +used} characters remaining`;
}

Adding the function to the event listener just when the website is done loading:

window.onload = outputRemainingCharacters;

As easy as that, it will then update your value from the very beginning.

Add a default condition to your if statement.

This is due to, if you don't add a default value, you will never be able to return to the default value as you mention:

textarea.addEventListener('keydown', function(event) {

    outputRemainingCharacters();
    let used = textarea.value.length;
    if (maxLength - used == 0) {
        output.style.color = "#E01424";
    } else if (maxLength - used <= 100) {
        output.style.color = "#CF7721";
    } else {
        output.style.color = "#000"; //Default color
    }

});

As you can see, the event listener is now a lot cleaner. I also would recommend:

Use event listeners for the specific event on the specific element you need.

This will help you not adding extra if statements to match if the event triggered on the element you want. Since we defined the text area at the very beginning, we can now just assign the event listener directly to it.

Note: You should use the event listener keydown instead of keyup. This due to the fact that holding down a key will not trigger the event until the key is up. keydown will be more accurate here. Try holding the space key down while writing to the textbox in the following snippet and see what happens.

Check this example:

var textarea = document.querySelector(".minchar"),
    output = document.querySelector(".rechar");
var maxLength = +textarea.getAttribute("maxlength");

function outputRemainingCharacters(){
    let used = textarea.value.length;
    output.innerText = `${maxLength - +used} characters remaining`;
}

textarea.addEventListener('keydown', function(event) {

    outputRemainingCharacters();
    let used = textarea.value.length;
    if (maxLength - used == 0) {
        output.style.color = "#E01424";
    } else if (maxLength - used <= 100) {
        output.style.color = "#CF7721";
    } else {
        output.style.color = "#000"; //Default color
    }

});

window.onload = outputRemainingCharacters;

<div class="col-md-10 pl-0">
  <textarea cols="15" rows="4" placeholder="Describe this Extra in brief for your guest" class="minchar" maxlength="250">Save time and return the vehicle at any fuel level. The price includes up to a full tank of petrol/diesel/charge.</textarea>
  <p class="rechar" id="test">250 characters remaining</p>
</div>


问:
Looking for javascript event equivalent to 'onRender'
I'd like to add to my  element JS event listener that will be triggered when the page is rendered (or loaded) to the DOM and the TD contains its innerHTML value.
something like:

```<code><script>
function manipulate(field){
field.value = field.value+'_done';
}
</script>
<td onRender=manipulate(this)>Hello World</td>
</code>```

I can't use onLoad because it can be used in  only to my understanding
Is there any way to do it?

答:
You don't have to attach the onLoad event to the body. You can use the global event handler like this:</p>

```<code>function init() {
 //Your function call
}
window.onload = init;
</code>```

Body:
I'd like to add to my  element JS event listener that will be triggered when the page is rendered (or loaded) to the DOM and the TD contains its innerHTML value.
something like:

Hello World

I can't use onLoad because it can be used in  only to my understanding
Is there any way to do it?

Body:
You don't have to attach the onLoad event to the body. You can use the global event handler like this:

function init() {
 //Your function call
}
window.onload = init;


问:
Default set of kryo registrations for spark/scala
I am running into a whack-a-mole with many classes requiring kryo registration. Is there a default registration for common spark classes that can help?

Here is a list of classes that I have had to add so far - and there is no end in sight:

```<code>  conf.registerKryoClasses(Array(classOf[Row]))
  conf.registerKryoClasses(Array(classOf[InternalRow]))
  conf.registerKryoClasses(Array(classOf[Array[InternalRow]]))
  conf.registerKryoClasses(Array(classOf[scala.reflect.ClassTag$$anon$1]))
  conf.registerKryoClasses(Array(classOf[org.apache.spark.sql.catalyst.expressions.UnsafeRow]))
  conf.registerKryoClasses(Array(classOf[Array[org.apache.spark.sql.types.StructType]]))
  conf.registerKryoClasses(Array(classOf[org.apache.spark.sql.types.StructType]))
</code>```

答:
This is not really an answer but is a partial explanation of the behavior. There was some older code that was forcing kryo to be particular:

```<code> val conf: SparkConf = new SparkConf()
  .set("spark.kryo.registrationRequired", "true")
</code>```

I removed that line and then the "registration missing" complaints magically disappeared.

Body:
I am running into a whack-a-mole with many classes requiring kryo registration. Is there a default registration for common spark classes that can help?

Here is a list of classes that I have had to add so far - and there is no end in sight:

  conf.registerKryoClasses(Array(classOf[Row]))
  conf.registerKryoClasses(Array(classOf[InternalRow]))
  conf.registerKryoClasses(Array(classOf[Array[InternalRow]]))
  conf.registerKryoClasses(Array(classOf[scala.reflect.ClassTag$$anon$1]))
  conf.registerKryoClasses(Array(classOf[org.apache.spark.sql.catalyst.expressions.UnsafeRow]))
  conf.registerKryoClasses(Array(classOf[Array[org.apache.spark.sql.types.StructType]]))
  conf.registerKryoClasses(Array(classOf[org.apache.spark.sql.types.StructType]))

Body:
This is not really an answer but is a partial explanation of the behavior. There was some older code that was forcing kryo to be particular:

 val conf: SparkConf = new SparkConf()
  .set("spark.kryo.registrationRequired", "true")

I removed that line and then the "registration missing" complaints magically disappeared.


问:
Iterate through Nested JavaScript Objects
I'm trying to iterate through a nested object to retrieve a specific object identified by a string. In the sample object below, the identifier string is the "label" property. I can't wrap my head around how to iterate down through the tree to return the appropriate object. Any help or suggestions would be greatly appreciated.</p>

```<code>var cars = {
  label: 'Autos',
  subs: [
    {
      label: 'SUVs',
      subs: []
    },
    {
      label: 'Trucks',
      subs: [
        {
          label: '2 Wheel Drive',
          subs: []
        },
        {
          label: '4 Wheel Drive',
          subs: [
            {
              label: 'Ford',
              subs: []
            },
            {
              label: 'Chevrolet',
              subs: []
            }
          ]
        }
      ]
    },
    {
      label: 'Sedan',
      subs: []
    }
  ]
}
</code>```

答:
```<code>var findObjectByLabel = function(objs, label) {
  if(objs.label === label) {
    return objs;
    }
  else{
    if(objs.subs){
      for(var i in objs.subs){
        let found = findObjectByLabel(objs.subs[i],label)
        if(found) return found
      }
    }
  }
};

findObjectByLabel(cars, "Ford");
</code>```

Body:
I'm trying to iterate through a nested object to retrieve a specific object identified by a string. In the sample object below, the identifier string is the "label" property. I can't wrap my head around how to iterate down through the tree to return the appropriate object. Any help or suggestions would be greatly appreciated.

var cars = {
  label: 'Autos',
  subs: [
    {
      label: 'SUVs',
      subs: []
    },
    {
      label: 'Trucks',
      subs: [
        {
          label: '2 Wheel Drive',
          subs: []
        },
        {
          label: '4 Wheel Drive',
          subs: [
            {
              label: 'Ford',
              subs: []
            },
            {
              label: 'Chevrolet',
              subs: []
            }
          ]
        }
      ]
    },
    {
      label: 'Sedan',
      subs: []
    }
  ]
}


答:
You can do this using a loop over the dict and a nested comprehension.

```<code>words_dict = {
    'colours' : ['red', 'blue', 'green'],
    'places' : ['america', 'china', 'malaysia', 'argentina', 'india'],
    'animals' : ['lion', 'cat', 'dog', 'wolf', 'monkey','zebra'],
}

for key, lst in words_dict.items():
    filtered_lst = [word for word in lst if len(word) >= 6]
    print(f"{key} : {filtered_lst}")
</code>```

Output for this is:

```<code>colours : []
places : ['america', 'malaysia', 'argentina']
animals : ['monkey']
</code>```

Or to actually make a function that essentially removes the elements and returns the corrected dict as your code originally did then use something as follows:

```<code>def remove_words(words_dict):
    return {key: [word for word in lst if len(word) >= 6]
            for key, lst in words_dict.items()}
</code>```

But then you'd still need to loop over them to print it correctly.

```<code>words_dict = remove_words(words_dict)
for key, lst in words_dict.items():
    print(f"{key} : {lst}")
</code>```

Title: How would I remove words from dictionary key lists that contain 6 or more letters?

Body:
You can do this using a loop over the dict and a nested comprehension.

words_dict = {
    'colours' : ['red', 'blue', 'green'],
    'places' : ['america', 'china', 'malaysia', 'argentina', 'india'],
    'animals' : ['lion', 'cat', 'dog', 'wolf', 'monkey','zebra'],
}

for key, lst in words_dict.items():
    filtered_lst = [word for word in lst if len(word) >= 6]
    print(f"{key} : {filtered_lst}")

Output for this is:

colours : []
places : ['america', 'malaysia', 'argentina']
animals : ['monkey']

Or to actually make a function that essentially removes the elements and returns the corrected dict as your code originally did then use something as follows:

def remove_words(words_dict):
    return {key: [word for word in lst if len(word) >= 6]
            for key, lst in words_dict.items()}

But then you'd still need to loop over them to print it correctly.

words_dict = remove_words(words_dict)
for key, lst in words_dict.items():
    print(f"{key} : {lst}")


问:
Any way that we can prevent the breakdown between reference and object when resize a vector?
I was debugging an issue and realized that when a vector is resizing, the reference will not work anymore. To illustrate this point, below is the minimal code. The output is 0 instead of 1. Is there anyway that we can prevent this happen except reserving a large space for x?

```<code>#include <iostream>
#include <vector>
using namespace std;

vector<int> x{};

int main(){
  x.reserve(1);
  x.push_back(0);
  int & y = x[0];
  x.resize(10);
  y=1;
  cout << x[0] << endl;
  return 0;
}
</code>```

答:
This is called invalidation and the only way you can prevent it is if you make sure that the vector capacity does not change.

```<code>x.reserve(10);
x.push_back(0);
int &y = x[0];
x.resize(10);
</code>```

Body:
I was debugging an issue and realized that when a vector is resizing, the reference will not work anymore. To illustrate this point, below is the minimal code. The output is 0 instead of 1. Is there anyway that we can prevent this happen except reserving a large space for x?

#include <iostream>
#include <vector>
using namespace std;

vector<int> x{};

int main(){
  x.reserve(1);
  x.push_back(0);
  int & y = x[0];
  x.resize(10);
  y=1;
  cout << x[0] << endl;
  return 0;
}

Body:
This is called invalidation and the only way you can prevent it is if you make sure that the vector capacity does not change.

x.reserve(10);
x.push_back(0);
int &y = x[0];
x.resize(10);


问:
How can I efficiently send objects in my game with client-server architecture
I have made a networked 2d top-down shooter game. It's fairly standard, the user moves their player using WASD, and can cast spells using 12345 and the mouse. The user must kill enemies and stay alive.

I've networked it for multiple users to play in the same arena, but it's too inefficient to run.

Sprites are stored in a Dictionary<string, sprite>, which is stored in the clients and server machines.

It's implemented as so:

The users keyboard and mouse input is sent to the server each frame (KeyboardState, MouseState).

The server takes the input and updates the game state.

The server sends each client their viewport(rectangle), and the position(float,float), sprite key(string), rotation(float), colour(int,int,int,int), of all sprites in that user's viewport.

The server stores this information as instances of a class that holds these values.

To send it, the server uses a BinaryFormatter to serialise the class, and sends it using TcpClient and Sockets.

The client deserialises the incoming data back into the classes and draws them to the screen

Unfortunately this makes the game incredibly slow. I tested this on only one machine, so there isn't latency, so I assume there is too much data being sent.

To fix this I think I would either need to store and send this data efficiently, or implement this differently.

To send it efficiently, I think I'd need to pack the data as bytes and send it, but I don't know how to do this.

How would I send the data efficiently, or implement it differently so that it is efficient?

答:
Minimize the amount of data traversing the network. Only send the needed amount of data and provide your own verification through timestamps and validation.

Each actionId and AnimationId in the following should exhibit the minimal (power of 2) amount of bytes to uniquely describe all of the possible values.

Server -> Client:

Servers known client position and rotation. Acknowledgement of last actionId.
A list of all other clients positions, orientations(rotations), animationIds... within the field of view of the client +- maxRotationRate within a distance of MaxViewDistance +- maxMovementRate.

The client must average its current position with the servers position every step.

Process all inputs locally(mouse and keyboard), and only send the relevant data to the server:

Every update, the client will send the relevant data and update its own internal state and process the server state given, and increasing int value(call this a timestamp). Include parity or CRC here.

Client -> Server
Current position, rotation, actionId, animationId, and a monotonically increasing int value(call this a timestamp). Include parity or CRC here.

All rendering decisions, the Viewport, current animation/sprite/colour should be established on the client(the colour and initial position needs to be given to the client at logon).

Location data will be shared(local updates and server adjustments).

Location and rotation and velocity data(both linear and rotational) need to be sent to the server every update. Upon receipt at the server a validation process must occur to prevent cheating. On missed, out of order, or malformed updates, the server will assume the last position + velocity * (time difference from last timestamp + current server time).

You must use UDP for the communication(note that you are using your own timestamps and CRC to validate the data received, no more crashes on invalid data).

Only process packets where the parity/CRC checks pass and reject the packets that are received too short or fail the checks. These checks will eliminate the crash that is associated with bad packets.

TCP's retry mechanism and ordered delivery is detrimental to game performance.  Each time a single packet is lost or delivered out of order, the time delta error(time the data is sent versus the time the server processes it) is increased by the RTT(Round Trip Time, i.e. Ping Time) due do the server retries and packet re-ordering. This will lead to multi-second delays that will only increase as the game goes on.

Network delays and dropped/malformed packets are normal occurrences for games. In the case of out of order packets based on timestamp values, drop all but the last, since this indicates the players latest wishes (for movement). With firing(spell casting in your case), keep sending the spell bits until acknowledged(ActionId). Ignore all but the first received spell on the server(send the Acknowledgement to the client), until the recharge period has expired.

While this answer excludes all points not brought up in the original question, mainly damage, a structure should be created that when an incidence of a damage inducing element is produced the on the server that distributes the damage according to the defined rules of damage distribution, that needs to be applied to each afflicted client.


问:
Print the access logs before UrlRewriteFilter
I have an application in which currently I am using two filters.

First one is UrlRewriteFilter which is for re-writing the url.

```<code><filter>
    <filter-name>UrlRewriteFilter</filter-name>
    <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
    <init-param>
        <param-name>logLevel</param-name>
        <param-value>DEBUG</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>UrlRewriteFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
</code>```

Second is a filter which is printing the performance of each page, along with the url.

```<code><filter>
    <filter-name>PerfLoggingFilter</filter-name>
    <filter-class>
        com.sia.saa.common.filter.PerfLoggingFilter
        </filter-class>
</filter>
<filter-mapping>
    <filter-name>PerfLoggingFilter</filter-name>
    <url-pattern>*.form</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
</filter-mapping>
</code>```

But in the logs only the re-written URL is being printed and not the original url.

Please suggest a way so that URL re-writing can continue but in the logs only the original url is printed.

Note: Post questions in case you need other details.

答: Is it not possible to have the second filter before the first one? If the second filter is executed first, you will have the original url...</p>

ContentLicense: CC BY-SA 2.5

Body:
I have an application in which currently I am using two filters.

First one is UrlRewriteFilter which is for re-writing the url.

<filter>
    <filter-name>UrlRewriteFilter</filter-name>
    <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
    <init-param>
        <param-name>logLevel</param-name>
        <param-value>DEBUG</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>UrlRewriteFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Second is a filter which is printing the performance of each page, along with the url.

<filter>
    <filter-name>PerfLoggingFilter</filter-name>
    <filter-class>
        com.sia.saa.common.filter.PerfLoggingFilter
        </filter-class>
</filter>
<filter-mapping>
    <filter-name>PerfLoggingFilter</filter-name>
    <url-pattern>*.form</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
</filter-mapping>

But in the logs only the re-written URL is being printed and not the original url.

Please suggest a way so that URL re-writing can continue but in the logs only the original url is printed.

Note: Post questions in case you need other details.


答: {k: [i for i in v if len(i) > 5] for k, v in words_dict.items()}


问:
DynamoDB and ElasticSearch - table design approaches
I'am currently thinking about my DynamoDB database. The goal is to get the best speed with a really large amount of data possible. For me, DynamoDB seems as a good option. Furthermore, it is necessary for me to connect the table to ElasticSearch because I need geopoint-querys (like show me all posts that are within a specific area).
Would the following approach make sense to you regarding the best practices of DynamoDB? It is possible, that the sort key for example 'posts' is a hot spot, but if I query only with ElasticSearch, there should be no problem - right? What would be the best solution?

My tables look like this:

So my thoughts are:

To query all users just select every row with the sort_key 'user'

To get a post with the creator, query the post_id and the sort_key 'post'

In a relational database, the two tables would look like this:

答:
You can do something like using overloaded attributes (using same columns for different things)

Then, query with user_id and post_id=0 for user info and post_id=others for posts


问:
Javascript - Image dimensions form multiple file input
Can't get the dimensions - height and width: the result is always "undefined". I clearly don't understand how JavaScript works here. I am however, able to display the file.

The PHP file contains the following input tag, which selects multiple pictures:

```<code>$output = "<input class=\"wpisNazwyWkladow\"
id=\"wpis_tabela_zdjecie_wybieracz\" type=\"file\" multiple
name=\"ads_photofile\">";
</code>```

This is the JavaScript script in question:

```<code>var input = $(this); // works
var ilosc = input[0].files.length;
var pliki = input[0].files;

for (var i = 0; i < ilosc; i++)
{
   var tmppath = URL.createObjectURL(pliki[i]); // works - displays
   var nazwa = pliki[i].name; // works
   var tempRozmiar = pliki[i].size; // works
   var typ = pliki[i].type; // typ fotki // works

   // The part that does not work:
   tempWysokosc = tmppath.height;
   tempSzerokosc = tmppath.width;

}
</code>```

I'm expecting an integer value for "tempWysokosc" and "tempSzerokosc".

Need help please.

答:
Chances are that the image hasnt fully rendered by the time you ask it for the height, so set the width and height after the onload event:

```<code>tmppath.onload=function() {
    tempWysokosc = tmppath.height;
    tempSzerokosc = tmppath.width;
}
</code>```

Similar answer: Can't get height and width of image in javascript

Body:
Can't get the dimensions - height and width: the result is always "undefined". I clearly don't understand how JavaScript works here. I am however, able to display the file.

The PHP file contains the following input tag, which selects multiple pictures:

$output = "<input class=\"wpisNazwyWkladow\"
id=\"wpis_tabela_zdjecie_wybieracz\" type=\"file\" multiple
name=\"ads_photofile\">";

This is the JavaScript script in question:

var input = $(this); // works
var ilosc = input[0].files.length;
var pliki = input[0].files;

for (var i = 0; i < ilosc; i++)
{
   var tmppath = URL.createObjectURL(pliki[i]); // works - displays
   var nazwa = pliki[i].name; // works
   var tempRozmiar = pliki[i].size; // works
   var typ = pliki[i].type; // typ fotki // works

   // The part that does not work:
   tempWysokosc = tmppath.height;
   tempSzerokosc = tmppath.width;

}

I'm expecting an integer value for "tempWysokosc" and "tempSzerokosc".

Need help please.

Body:
Chances are that the image hasnt fully rendered by the time you ask it for the height, so set the width and height after the onload event:

tmppath.onload=function() {
    tempWysokosc = tmppath.height;
    tempSzerokosc = tmppath.width;
}

Similar answer: Can't get height and width of image in javascript


问:
Swift: when should I use "var" instead of "let"?
As Apple Documentation says:

Use let to make a constant and var to make a variable. The value of a constant doesn’t need to be known at compile time, but you must assign it a value exactly once. This means you can use constants to name a value that you determine once but use in many places.

Let's consider some class:

```<code>class A {
    var a = [String]()
}
</code>```

Since array a is mutable, it's defined via var. But what if we consider class B, where instance of A is property?

```<code>class B {
    let b = A()
}
</code>```

Even if b is mutable, let keyword will be ok, because reference won't be changed. On the other hand, var will be ok too, because content of b can be changed. What should I pick in this example - let or var?

答:
When you declare a variable with var, it means it can be updated, it is variable, it’s value can be modified.

When you declare a variable with let, it means it cannot be updated, it is non variable, it’s value cannot be modified.

```<code>var a = 1
print (a) // output 1
a = 2
print (a) // output 2

let b = 4
print (b) // output 4
b = 5 // error "Cannot assign to value: 'b' is a 'let' constant"
</code>```

Let us understand above example: We have created a new variable “a” with “var keyword” and assigned the value “1”. When I print “a” I get output as 1. Then I assign 2 to “var a” i.e I’m modifying value of variable “a”. I can do it without getting compiler error because I declared it as var.

In the second scenario I created a new variable “b” with “let keyword” and assigned the value “4”. When I print “b” I got 4 as output. Then I try to assign 5 to “let b” i.e. I’m trying to modify the “let” variable and I get compile time error “Cannot assign to value: ‘b’ is a ‘let’ constant”.

Source: https://thenucleargeeks.com/2019/04/10/swift-let-vs-var/

Body:
As Apple Documentation says:

Use let to make a constant and var to make a variable. The value of a constant doesn’t need to be known at compile time, but you must assign it a value exactly once. This means you can use constants to name a value that you determine once but use in many places.

Let's consider some class:

class A {
    var a = [String]()
}

Since array a is mutable, it's defined via var. But what if we consider class B, where instance of A is property?

class B {
    let b = A()
}

Even if b is mutable, let keyword will be ok, because reference won't be changed. On the other hand, var will be ok too, because content of b can be changed. What should I pick in this example - let or var?

Body:
When you declare a variable with var, it means it can be updated, it is variable, it’s value can be modified.

When you declare a variable with let, it means it cannot be updated, it is non variable, it’s value cannot be modified.

var a = 1
print (a) // output 1
a = 2
print (a) // output 2

let b = 4
print (b) // output 4
b = 5 // error "Cannot assign to value: 'b' is a 'let' constant"

Let us understand above example: We have created a new variable “a” with “var keyword” and assigned the value “1”. When I print “a” I get output as 1. Then I assign 2 to “var a” i.e I’m modifying value of variable “a”. I can do it without getting compiler error because I declared it as var.

In the second scenario I created a new variable “b” with “let keyword” and assigned the value “4”. When I print “b” I got 4 as output. Then I try to assign 5 to “let b” i.e. I’m trying to modify the “let” variable and I get compile time error “Cannot assign to value: ‘b’ is a ‘let’ constant”.

Source: https://thenucleargeeks.com/2019/04/10/swift-let-vs-var/


问:
Does the secure cookie work on http request with 443 port?
Does a Cookie with the secure flag work on Http request with 443 port?

For example) http:443//www.example.com

And how about ssl on Http request with 443 port?

答:
"Does a Cookie with the secure flag work on Http request with 443 port?"

-- No. A cookie with secure flag only works under HTTPS environment. HTTP request to port 443 (the default port of HTTPS) is still an HTTP, not HTTPS. Protocol is protocol, it won't be decided by which port is used.

According to RFC6265:

The Secure attribute limits the scope of the cookie to "secure"
channels (where "secure" is defined by the user agent).  When a
cookie has the Secure attribute, the user agent will include the
cookie in an HTTP request only if the request is transmitted over a
secure channel (typically HTTP over Transport Layer Security (TLS)

HTTP request to port 443 is not transmitted over a secure channel.

I made a simple experiment, and the result is listed as below:

Make a web server, listen to port 443, with HTTP protocol. It works well.

On above server, return cookie without secure flag. The browser received the cookie and store it successfully.

On above server, return cookie with secure flag. The browser received the cookie, but ignore it automatically, as the current protocol is HTTP, not HTTPS.

"How about ssl on Http request with 443 port?"

-- There is no SSL on HTTP request with 443 port. 443 is a plain, normal number, there is nothing special for it. It's just being choosed as the default port of HTTPS, nothing more.