问:
Pandoc filter tikz.py returns "not a valid json value"
I'm using the tikz.py pandocfilter to turn latex tikz code in a markdown file into images in the output html file. I'm running pandoc version 1.17.0.2, python 2.7.10 and ImageMagick 6.9.6-4. My pandoc command is:

```<code>pandoc -s -c --mathjax -i- t slidy tik.md --filter tikz.py -o tik.html
</code>```

(but I've tried simpler commands without slidy or mathjax and they give the same issue)

Where tik.md contains a simple tikz environment:

```<code>\begin{tikzpicture}
\draw (0,0) -- (4,0) -- (4,4) -- (0,4) -- (0,0);
\end{tikzpicture}
</code>```

tikz.py runs well and it seems to successfully generate the image:

$ pandoc -s -c --mathjax -i -t slidy tik.md --filter tikz.py -o tik.html

This is pdfTeX, Version 3.14159265-2.6-1.40.16 (TeX Live 2015)
  (preloaded format=pdflatex) restricted \write18 enabled.

entering extended mode

(./tikz.tex

LaTeX2e <2015/01/01>

Babel ...

.....

[1] (./tikz.aux) )

Output written on tikz.pdf (1 page, 1077 bytes).

Transcript written on tikz.log.

Created image tikz-images/53200b26dfa2c05d2b92647ef74211f7a2ce0c0e.png

pandoc: Error in $: Failed reading: not a valid json value

I am using an unaltered tikz.py so it is not clear to me where the source of the problem could be. Any thoughts?

答:
I just ran into the same thing in a Ruby filter, and finally figured out that it was because I was trying to write debugging output to standard output. Since a filter has to read standard input and write to standard output, any debugging output on standard output will blow things up.

In my Ruby filter I had to change puts 'debug stuff' to STDERR.puts 'debug stuff'.

Body:
I'm using the tikz.py pandocfilter to turn latex tikz code in a markdown file into images in the output html file. I'm running pandoc version 1.17.0.2, python 2.7.10 and ImageMagick 6.9.6-4. My pandoc command is:

pandoc -s -c --mathjax -i- t slidy tik.md --filter tikz.py -o tik.html

(but I've tried simpler commands without slidy or mathjax and they give the same issue)

Where tik.md contains a simple tikz environment:

\begin{tikzpicture}
\draw (0,0) -- (4,0) -- (4,4) -- (0,4) -- (0,0);
\end{tikzpicture}

tikz.py runs well and it seems to successfully generate the image:

$ pandoc -s -c --mathjax -i -t slidy tik.md --filter tikz.py -o tik.html

This is pdfTeX, Version 3.14159265-2.6-1.40.16 (TeX Live 2015)
  (preloaded format=pdflatex) restricted \write18 enabled.

entering extended mode

(./tikz.tex

LaTeX2e <2015/01/01>

Babel ...

.....

[1] (./tikz.aux) )

Output written on tikz.pdf (1 page, 1077 bytes).

Transcript written on tikz.log.

Created image tikz-images/53200b26dfa2c05d2b92647ef74211f7a2ce0c0e.png

pandoc: Error in $: Failed reading: not a valid json value

I am using an unaltered tikz.py so it is not clear to me where the source of the problem could be. Any thoughts?


来源: stackexchange

问:
Onclick image to move another page is not working

I'm new to nativescript. I'm navigation from Alert page to
Naviagation page. I have posted all relevant codes.please check it.

I'm not getting any issue.When performing image onClick I'm able to call this method onNotification().

I'm able to see this console log in command prompt

console.log("SteveCheck", "Test");

But I don't know, Why it is not moving to notification page when
click on the button in alert page.Below I have added all the relevant codes.

app.module.ts:

```<code>import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core";
import { NativeScriptModule } from "nativescript-angular/nativescript.module";
import { AlertComponent } from "./AlertFolder/alert.component";

import { NativeScriptRouterModule } from "nativescript-angular/router"
import {AppRoutes, AppComponents } from "./app.routing";

@NgModule({
  declarations: [AlertComponent, ...AppComponents],
  bootstrap: [AlertComponent],
  imports: [
    NativeScriptModule,
    NativeScriptRouterModule,
    NativeScriptRouterModule.forRoot(AppRoutes)
    ],

  schemas: [NO_ERRORS_SCHEMA],
})

export class AppModule {}
</code>```

app.routing.ts:

```<code>import { AlertComponent } from "./AlertFolder/alert.component";
import { NotificationComponent } from "./Noficiation/notification";

export const AppRoutes:any = [

    { path: "", component: AlertComponent },
    { path: "NotificationPage", component: NotificationComponent}
];

export const AppComponents: any = [

 AlertComponent,
 NotificationComponent

];
</code>```

alert.component.ts:

```<code> @Component({
 selector: "sdk-child-component",
 moduleId: module.id,
 ....
 })

export class AlertComponent   {

.....
.....
 public constructor(private router: Router, private routerExtensions: RouterExtensions){

this.alertList = [];
}

onNotification() {

     console.log("SteveCheck", "Test");
     this.router.navigate(["NotificationPage"]);

}

 }
</code>```

alert.component.html:

```<code> <StackLayout class="borders" orientation="horizontal" >
    <Label class="notification-label" text="Notification Center" ></Label>
    <Image src="res://right_arrow" stretch="none" class="right-arrow" (tap)="onNotification()"></Image>

  </StackLayout>
</code>```

答:
I have to use Path folder name Notification. I have that second page NotificationComponent placed inside that Notification folder only.That's why I'm unable to navigate between pages.

By changing this :

```<code>  this.router.navigate(["NotificationPage"]);
</code>```

to this:

```<code>this.router.navigate(["Notification"]);
</code>```

fixed my issue

ContentLicense: CC BY-SA 3.0

Body:
I'm new to nativescript. I'm navigation from Alert page to
Naviagation page. I have posted all relevant codes.please check it.

I'm not getting any issue.When performing image onClick I'm able to call this method onNotification().

I'm able to see this console log in command prompt

console.log("SteveCheck", "Test");

But I don't know, Why it is not moving to notification page when
click on the button in alert page.Below I have added all the relevant codes.

app.module.ts:

import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core";
import { NativeScriptModule } from "nativescript-angular/nativescript.module";
import { AlertComponent } from "./AlertFolder/alert.component";

import { NativeScriptRouterModule } from "nativescript-angular/router"
import {AppRoutes, AppComponents } from "./app.routing";

@NgModule({
  declarations: [AlertComponent, ...AppComponents],
  bootstrap: [AlertComponent],
  imports: [
    NativeScriptModule,
    NativeScriptRouterModule,
    NativeScriptRouterModule.forRoot(AppRoutes)
    ],

  schemas: [NO_ERRORS_SCHEMA],
})

export class AppModule {}

app.routing.ts:

import { AlertComponent } from "./AlertFolder/alert.component";
import { NotificationComponent } from "./Noficiation/notification";

export const AppRoutes:any = [

    { path: "", component: AlertComponent },
    { path: "NotificationPage", component: NotificationComponent}
];

export const AppComponents: any = [

 AlertComponent,
 NotificationComponent

];

alert.component.ts:

 @Component({
 selector: "sdk-child-component",
 moduleId: module.id,
 ....
 })

export class AlertComponent   {

.....
.....
 public constructor(private router: Router, private routerExtensions: RouterExtensions){

this.alertList = [];
}

onNotification() {

     console.log("SteveCheck", "Test");
     this.router.navigate(["NotificationPage"]);

}

 }

alert.component.html:

 <StackLayout class="borders" orientation="horizontal" >

    <Image src="res://right_arrow" stretch="none" class="right-arrow" (tap)="onNotification()"></Image>

  </StackLayout>

Body:
I have to use Path folder name Notification. I have that second page NotificationComponent placed inside that Notification folder only.That's why I'm unable to navigate between pages.

By changing this :

  this.router.navigate(["NotificationPage"]);

to this:

this.router.navigate(["Notification"]);

fixed my issue


问:
Go back 2 pages - React-Router - ReactJS -
I have an component that it goBack to the previous page. I use that: this.props.history.goBack(); but I wanna that go back two levels. I have tried a lot of thing as this.props.history.goBack(-2); but I do not achieve that. I am using ReactRouter v4.

How could I do that? Thank you.

答:
use this.props.history.go(-2)

as it's described in
https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/history.md


问:
Android bluetooth: dropped packets
We have built a wearable device that takes measurements and sends the results over BLE to an Android device every 20msec.  We are getting strange results where the first 270 packets are received on time and without loss, but at 271 things get strange.  We will give five packets (on time) and then drop 32 packets, and then repeat.

The mobile phone is a Nexus 5X with Android 7.1.1. The device is running an nRF51 with BLE 4.2. And we are using the Android nRF toolbox v2.4.0 based on the Template app.
One hypothesis we had was that the ConnectionPriority was wrong and that we need to set to a higher priority.  We have tried adding the following in the BleManager:

mBluetoothGatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH);

But is makes no difference.  The odd thing is that the system seems to work find for the first 270 packets.
Any ideas how to debug this?

Sample logcat below.  Note that the packet numbers are the received packet numbers on the Android side, not the packet numbers from the device side:

```<code>Packet #258; SensorTime = 256.175sec; Delta = 018.8msec
Packet #259; SensorTime = 256.200sec; Delta = 025.0msec
Packet #260; SensorTime = 256.213sec; Delta = 012.5msec
Packet #261; SensorTime = 256.238sec; Delta = 025.0msec
Packet #262; SensorTime = 256.256sec; Delta = 018.8msec
Packet #263; SensorTime = 256.275sec; Delta = 018.8msec
Packet #264; SensorTime = 256.300sec; Delta = 025.0msec
Packet #265; SensorTime = 256.319sec; Delta = 018.8msec
Packet #266; SensorTime = 256.338sec; Delta = 018.8msec
Packet #267; SensorTime = 256.356sec; Delta = 018.7msec
Packet #268; SensorTime = 256.375sec; Delta = 018.8msec
Packet #269; SensorTime = 256.394sec; Delta = 018.8msec
Packet #270; SensorTime = 256.419sec; Delta = 025.0msec
Packet #271; SensorTime = 256.438sec; Delta = 018.8msec
=== Time Fault :: Time   256.656sec : Time delta = 218.8 msec; mTime since last fault = 0.000 sec
Packet #272; SensorTime = 256.656sec; Delta = 218.8msec
=== Time Fault :: Time   257.294sec : Time delta = 637.5 msec; mTime since last fault = 0.001 sec
Packet #273; SensorTime = 257.294sec; Delta = 637.5msec
Packet #274; SensorTime = 257.313sec; Delta = 018.8msec
=== Time Fault :: Time   257.938sec : Time delta = 625.0 msec; mTime since last fault = 0.639 sec
Packet #275; SensorTime = 257.938sec; Delta = 625.0msec
=== Time Fault :: Time   258.594sec : Time delta = 656.3 msec; mTime since last fault = 0.003 sec
Packet #276; SensorTime = 258.594sec; Delta = 656.3msec
Packet #277; SensorTime = 258.613sec; Delta = 018.8msec
Packet #278; SensorTime = 258.638sec; Delta = 025.0msec
Packet #279; SensorTime = 258.650sec; Delta = 012.5msec
Packet #280; SensorTime = 258.675sec; Delta = 025.0msec
=== Time Fault :: Time   259.231sec : Time delta = 556.2 msec; mTime since last fault = 0.639 sec
Packet #281; SensorTime = 259.231sec; Delta = 556.2msec
Packet #282; SensorTime = 259.256sec; Delta = 025.0msec
Packet #283; SensorTime = 259.275sec; Delta = 018.8msec
Packet #284; SensorTime = 259.294sec; Delta = 018.7msec
Packet #285; SensorTime = 259.313sec; Delta = 018.8msec
=== Time Fault :: Time   259.875sec : Time delta = 562.5 msec; mTime since last fault = 0.657 sec
Packet #286; SensorTime = 259.875sec; Delta = 562.5msec
Packet #287; SensorTime = 259.894sec; Delta = 018.8msec
Packet #288; SensorTime = 259.913sec; Delta = 018.8msec
Packet #289; SensorTime = 259.931sec; Delta = 018.8msec
Packet #290; SensorTime = 259.956sec; Delta = 025.0msec
=== Time Fault :: Time   260.513sec : Time delta = 556.2 msec; mTime since last fault = 0.636 sec
Packet #291; SensorTime = 260.513sec; Delta = 556.2msec
Packet #292; SensorTime = 260.531sec; Delta = 018.8msec
Packet #293; SensorTime = 260.550sec; Delta = 018.8msec
Packet #294; SensorTime = 260.569sec; Delta = 018.8msec
Packet #295; SensorTime = 260.594sec; Delta = 025.0msec
=== Time Fault :: Time   261.169sec : Time delta = 575.0 msec; mTime since last fault = 0.645 sec
Packet #296; SensorTime = 261.169sec; Delta = 575.0msec
Packet #297; SensorTime = 261.188sec; Delta = 018.8msec
Packet #298; SensorTime = 261.213sec; Delta = 025.0msec
Packet #299; SensorTime = 261.231sec; Delta = 018.7msec
Packet #300; SensorTime = 261.250sec; Delta = 018.8msec
=== Time Fault :: Time   261.806sec : Time delta = 556.3 msec; mTime since last fault = 0.645 sec
Packet #301; SensorTime = 261.806sec; Delta = 556.3msec
Packet #302; SensorTime = 261.831sec; Delta = 025.0msec
Packet #303; SensorTime = 261.850sec; Delta = 018.8msec
Packet #304; SensorTime = 261.869sec; Delta = 018.8msec
Packet #305; SensorTime = 261.894sec; Delta = 025.0msec
=== Time Fault :: Time   262.456sec : Time delta = 562.5 msec; mTime since last fault = 1.283 sec
Packet #306; SensorTime = 262.456sec; Delta = 562.5msec
Packet #307; SensorTime = 262.469sec; Delta = 012.5msec
Packet #308; SensorTime = 262.488sec; Delta = 018.8msec
Packet #309; SensorTime = 262.506sec; Delta = 018.8msec
Packet #310; SensorTime = 262.525sec; Delta = 018.8msec
=== Time Fault :: Time   263.106sec : Time delta = 581.2 msec; mTime since last fault = 0.658 sec
Packet #311; SensorTime = 263.106sec; Delta = 581.2msec
=== Time Fault :: Time   263.750sec : Time delta = 643.8 msec; mTime since last fault = 0.631 sec
Packet #312; SensorTime = 263.750sec; Delta = 643.8msec
=== Time Fault :: Time   264.388sec : Time delta = 637.5 msec; mTime since last fault = 0.003 sec
Packet #313; SensorTime = 264.388sec; Delta = 637.5msec
</code>```

答:
After tracking packet with a BLE sniffer, we discovered that, on the device side, there was a pair of bad constants:

```<code>#define MIN_CONN_INTERVAL  MSEC_TO_UNITS(400, UNIT_1_25_MS)
#define MAX_CONN_INTERVAL  MSEC_TO_UNITS(650, UNIT_1_25_MS)
</code>```

These were corrected as follows:

```<code>#define MIN_CONN_INTERVAL  MSEC_TO_UNITS(10, UNIT_1_25_MS)
#define MAX_CONN_INTERVAL  MSEC_TO_UNITS(20, UNIT_1_25_MS)
</code>```

Once corrected the connection rate settled our fine.  The most bizarre part was that some devices and some phones worked at full speed, but others would drop into the above incorrect Connection Priority.
THanks for the help.  The sniffer was the key here!

Title: Android bluetooth: dropped packets

Body:
We have built a wearable device that takes measurements and sends the results over BLE to an Android device every 20msec.  We are getting strange results where the first 270 packets are received on time and without loss, but at 271 things get strange.  We will give five packets (on time) and then drop 32 packets, and then repeat.

The mobile phone is a Nexus 5X with Android 7.1.1. The device is running an nRF51 with BLE 4.2. And we are using the Android nRF toolbox v2.4.0 based on the Template app.
One hypothesis we had was that the ConnectionPriority was wrong and that we need to set to a higher priority.  We have tried adding the following in the BleManager:

mBluetoothGatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH);

But is makes no difference.  The odd thing is that the system seems to work find for the first 270 packets.
Any ideas how to debug this?

Sample logcat below.  Note that the packet numbers are the received packet numbers on the Android side, not the packet numbers from the device side:

Packet #258; SensorTime = 256.175sec; Delta = 018.8msec
Packet #259; SensorTime = 256.200sec; Delta = 025.0msec
Packet #260; SensorTime = 256.213sec; Delta = 012.5msec
Packet #261; SensorTime = 256.238sec; Delta = 025.0msec
Packet #262; SensorTime = 256.256sec; Delta = 018.8msec
Packet #263; SensorTime = 256.275sec; Delta = 018.8msec
Packet #264; SensorTime = 256.300sec; Delta = 025.0msec
Packet #265; SensorTime = 256.319sec; Delta = 018.8msec
Packet #266; SensorTime = 256.338sec; Delta = 018.8msec
Packet #267; SensorTime = 256.356sec; Delta = 018.7msec
Packet #268; SensorTime = 256.375sec; Delta = 018.8msec
Packet #269; SensorTime = 256.394sec; Delta = 018.8msec
Packet #270; SensorTime = 256.419sec; Delta = 025.0msec
Packet #271; SensorTime = 256.438sec; Delta = 018.8msec
=== Time Fault :: Time   256.656sec : Time delta = 218.8 msec; mTime since last fault = 0.000 sec
Packet #272; SensorTime = 256.656sec; Delta = 218.8msec
=== Time Fault :: Time   257.294sec : Time delta = 637.5 msec; mTime since last fault = 0.001 sec
Packet #273; SensorTime = 257.294sec; Delta = 637.5msec
Packet #274; SensorTime = 257.313sec; Delta = 018.8msec
=== Time Fault :: Time   257.938sec : Time delta = 625.0 msec; mTime since last fault = 0.639 sec
Packet #275; SensorTime = 257.938sec; Delta = 625.0msec
=== Time Fault :: Time   258.594sec : Time delta = 656.3 msec; mTime since last fault = 0.003 sec
Packet #276; SensorTime = 258.594sec; Delta = 656.3msec
Packet #277; SensorTime = 258.613sec; Delta = 018.8msec
Packet #278; SensorTime = 258.638sec; Delta = 025.0msec
Packet #279; SensorTime = 258.650sec; Delta = 012.5msec
Packet #280; SensorTime = 258.675sec; Delta = 025.0msec
=== Time Fault :: Time   259.231sec : Time delta = 556.2 msec; mTime since last fault = 0.639 sec
Packet #281; SensorTime = 259.231sec; Delta = 556.2msec
Packet #282; SensorTime = 259.256sec; Delta = 025.0msec
Packet #283; SensorTime = 259.275sec; Delta = 018.8msec
Packet #284; SensorTime = 259.294sec; Delta = 018.7msec
Packet #285; SensorTime = 259.313sec; Delta = 018.8msec
=== Time Fault :: Time   259.875sec : Time delta = 562.5 msec; mTime since last fault = 0.657 sec
Packet #286; SensorTime = 259.875sec; Delta = 562.5msec
Packet #287; SensorTime = 259.894sec; Delta = 018.8msec
Packet #288; SensorTime = 259.913sec; Delta = 018.8msec
Packet #289; SensorTime = 259.931sec; Delta = 018.8msec
Packet #290; SensorTime = 259.956sec; Delta = 025.0msec
=== Time Fault :: Time   260.513sec : Time delta = 556.2 msec; mTime since last fault = 0.636 sec
Packet #291; SensorTime = 260.513sec; Delta = 556.2msec
Packet #292; SensorTime = 260.531sec; Delta = 018.8msec
Packet #293; SensorTime = 260.550sec; Delta = 018.8msec
Packet #294; SensorTime = 260.569sec; Delta = 018.8msec
Packet #295; SensorTime = 260.594sec; Delta = 025.0msec
=== Time Fault :: Time   261.169sec : Time delta = 575.0 msec; mTime since last fault = 0.645 sec
Packet #296; SensorTime = 261.169sec; Delta = 575.0msec
Packet #297; SensorTime = 261.188sec; Delta = 018.8msec
Packet #298; SensorTime = 261.213sec; Delta = 025.0msec
Packet #299; SensorTime = 261.231sec; Delta = 018.7msec
Packet #300; SensorTime = 261.250sec; Delta = 018.8msec
=== Time Fault :: Time   261.806sec : Time delta = 556.3 msec; mTime since last fault = 0.645 sec
Packet #301; SensorTime = 261.806sec; Delta = 556.3msec
Packet #302; SensorTime = 261.831sec; Delta = 025.0msec
Packet #303; SensorTime = 261.850sec; Delta = 018.8msec
Packet #304; SensorTime = 261.869sec; Delta = 018.8msec
Packet #305; SensorTime = 261.894sec; Delta = 025.0msec
=== Time Fault :: Time   262.456sec : Time delta = 562.5 msec; mTime since last fault = 1.283 sec
Packet #306; SensorTime = 262.456sec; Delta = 562.5msec
Packet #307; SensorTime = 262.469sec; Delta = 012.5msec
Packet #308; SensorTime = 262.488sec; Delta = 018.8msec
Packet #309; SensorTime = 262.506sec; Delta = 018.8msec
Packet #310; SensorTime = 262.525sec; Delta = 018.8msec
=== Time Fault :: Time   263.106sec : Time delta = 581.2 msec; mTime since last fault = 0.658 sec
Packet #311; SensorTime = 263.106sec; Delta = 581.2msec
=== Time Fault :: Time   263.750sec : Time delta = 643.8 msec; mTime since last fault = 0.631 sec
Packet #312; SensorTime = 263.750sec; Delta = 643.8msec
=== Time Fault :: Time   264.388sec : Time delta = 637.5 msec; mTime since last fault = 0.003 sec
Packet #313; SensorTime = 264.388sec; Delta = 637.5msec

Body:
After tracking packet with a BLE sniffer, we discovered that, on the device side, there was a pair of bad constants:

#define MIN_CONN_INTERVAL  MSEC_TO_UNITS(400, UNIT_1_25_MS)
#define MAX_CONN_INTERVAL  MSEC_TO_UNITS(650, UNIT_1_25_MS)

These were corrected as follows:

#define MIN_CONN_INTERVAL  MSEC_TO_UNITS(10, UNIT_1_25_MS)
#define MAX_CONN_INTERVAL  MSEC_TO_UNITS(20, UNIT_1_25_MS)

Once corrected the connection rate settled our fine.  The most bizarre part was that some devices and some phones worked at full speed, but others would drop into the above incorrect Connection Priority.
THanks for the help.  The sniffer was the key here!


问:
Layout fields with no margin between them on BlackBerry
How do I prevent extra space between two fields: </p>

```<code>VerticalFieldManager _fieldManagerMiddle =
    new VerticalFieldManager(Manager.VERTICAL_SCROLL);
LabelField field = new LabelField("Title");
CustomFieldList list = new CustomFieldList ();

_fieldManagerMiddle.add(field);
_fieldManagerMiddle.add(list);
</code>```

答:
You can create custom manager .
inside the sublayout method you can position the contents as per your requirement and choice</p>

ContentLicense: CC BY-SA 2.5

Body:
How do I prevent extra space between two fields:

VerticalFieldManager _fieldManagerMiddle =
    new VerticalFieldManager(Manager.VERTICAL_SCROLL);
LabelField field = new LabelField("Title");
CustomFieldList list = new CustomFieldList ();

_fieldManagerMiddle.add(field);
_fieldManagerMiddle.add(list);


问:
how to properly access AWS Api Gateway from Node Web application
I'm experiencing a wired issue, where the same exact code (which accesses AWS Api Gateway) runs just fine if submitted this way:  node app.js, but produces 307 Redirect, when submitted from within Node/Express app.

Here is the "stand-alone" single file node program (app.js) :

```<code>var http = require("https");

var options = {
      "method": "POST",
        "hostname": "ipzjnsvxnd.execute-api.us-west-2.amazonaws.com",
          "port": null,
            "path": "/DEV/execution",
              "headers": {
                      "cache-control": "no-cache",
                          "postman-token": "b929e970-fe22-0f4f-e659-117890fda955"
                                }
};

var req = http.request(options, function (res) {
      var chunks = [];

        res.on("data", function (chunk) {
                chunks.push(chunk);
                  });

          res.on("end", function () {
                  var body = Buffer.concat(chunks);
                      console.log(body.toString());
                        });
});

req.write("{\n  \"input\": \"{ \\\"account_key\\\": \\\"9990\\\", \\\"acc1\\\": \\\"1235813\\\", \\\"acc2\\\": \\\"13711\\\",\\\"amount\\\": \\\"1000.00\\\", \\\"city\\\": \\\"BrandonTown\\\" }\",\n  \"name\": \"RequiredUniqueValueGoesHere19090\",\n  \"stateMachineArn\": \"arn:aws:states:us-west-2:217465658899:stateMachine:FICO_StateMachine3\"\n}");
req.end();
</code>```

And here is the same code, as a part of a Node/Express Web app:

```<code>module.exports = function(app) {

    var querystring = require('querystring');
    var http = require('http');
    http.post = require('http-post');

    app.get('*', function(req, res) {
        res.sendfile('./public/index.html');
    });

    app.post("/customerinfo", function(req, res) {

        var options = {
            "method": "POST",
            "hostname": "ipzjnsvxnd.execute-api.us-west-2.amazonaws.com",
            "path": "/DEV/execution",
            "headers": {
                "cache-control": "no-cache",
                "postman-token": "b929e970-fe22-0f4f-e659-117890fda955"
            }
        };

          var req1 = http.request(options, function (res1) {
            var chunks = [];

            res1.on("data", function (chunk) {
                chunks.push(chunk);
            });

            res1.on("end", function () {
                var body = Buffer.concat(chunks);
                console.log(body.toString());
            });
        });

        req1.write("{\n  \"input\": \"{ \\\"account_key\\\": \\\"9990\\\", \\\"acc1\\\": \\\"1235813\\\", \\\"acc2\\\": \\\"13711\\\",\\\"amount\\\": \\\"1000.00\\\", \\\"city\\\": \\\"BrandonTown\\\" }\",\n  \"name\": \"RequiredUniqueValueGoesHere1239091\",\n  \"stateMachineArn\": \"arn:aws:states:us-west-2:217465658899:stateMachine:FICO_StateMachine3\"\n}");
        req1.end();
    });

};
</code>```

The first one works fine when submitted:  node app.js
The second one returns:

```<code><html>
<head><title>307 Temporary Redirect</title></head>
<body bgcolor="white">
<center><h1>307 Temporary Redirect</h1></center>
<hr><center>CloudFront</center>
</body>
</html>

<html>
<head><title>307 Temporary Redirect</title></head>
<body bgcolor="white">
<center><h1>307 Temporary Redirect</h1></center>
<hr><center>CloudFront</center>
</body>
</html>

<html>
<head><title>307 Temporary Redirect</title></head>
</code>```

答:
You need to change the code http = require('http') to http = require('https') inside your express app.

Also, take a look at request, it is an HTTP client with support for HTTPS and also has lots of other features built in.

Body:
I'm experiencing a wired issue, where the same exact code (which accesses AWS Api Gateway) runs just fine if submitted this way:  node app.js, but produces 307 Redirect, when submitted from within Node/Express app.

Here is the "stand-alone" single file node program (app.js) :

var http = require("https");

var options = {
      "method": "POST",
        "hostname": "ipzjnsvxnd.execute-api.us-west-2.amazonaws.com",
          "port": null,
            "path": "/DEV/execution",
              "headers": {
                      "cache-control": "no-cache",
                          "postman-token": "b929e970-fe22-0f4f-e659-117890fda955"
                                }
};

var req = http.request(options, function (res) {
      var chunks = [];

        res.on("data", function (chunk) {
                chunks.push(chunk);
                  });

          res.on("end", function () {
                  var body = Buffer.concat(chunks);
                      console.log(body.toString());
                        });
});

req.write("{\n  \"input\": \"{ \\\"account_key\\\": \\\"9990\\\", \\\"acc1\\\": \\\"1235813\\\", \\\"acc2\\\": \\\"13711\\\",\\\"amount\\\": \\\"1000.00\\\", \\\"city\\\": \\\"BrandonTown\\\" }\",\n  \"name\": \"RequiredUniqueValueGoesHere19090\",\n  \"stateMachineArn\": \"arn:aws:states:us-west-2:217465658899:stateMachine:FICO_StateMachine3\"\n}");
req.end();

And here is the same code, as a part of a Node/Express Web app:

module.exports = function(app) {

    var querystring = require('querystring');
    var http = require('http');
    http.post = require('http-post');

    app.get('*', function(req, res) {
        res.sendfile('./public/index.html');
    });

    app.post("/customerinfo", function(req, res) {

        var options = {
            "method": "POST",
            "hostname": "ipzjnsvxnd.execute-api.us-west-2.amazonaws.com",
            "path": "/DEV/execution",
            "headers": {
                "cache-control": "no-cache",
                "postman-token": "b929e970-fe22-0f4f-e659-117890fda955"
            }
        };

          var req1 = http.request(options, function (res1) {
            var chunks = [];

            res1.on("data", function (chunk) {
                chunks.push(chunk);
            });

            res1.on("end", function () {
                var body = Buffer.concat(chunks);
                console.log(body.toString());
            });
        });

        req1.write("{\n  \"input\": \"{ \\\"account_key\\\": \\\"9990\\\", \\\"acc1\\\": \\\"1235813\\\", \\\"acc2\\\": \\\"13711\\\",\\\"amount\\\": \\\"1000.00\\\", \\\"city\\\": \\\"BrandonTown\\\" }\",\n  \"name\": \"RequiredUniqueValueGoesHere1239091\",\n  \"stateMachineArn\": \"arn:aws:states:us-west-2:217465658899:stateMachine:FICO_StateMachine3\"\n}");
        req1.end();
    });

};

The first one works fine when submitted:  node app.js
The second one returns:

<title>307 Temporary Redirect</title>

307 Temporary Redirect

CloudFront

<title>307 Temporary Redirect</title>

307 Temporary Redirect

CloudFront

<title>307 Temporary Redirect</title>


问:
C++11 Boost, how to base64 decode back to integer presentation
Based on this code here, I was able to write some code that converts a vector of integers into a base64 encoded version. And I can confirm it is the right output by comparing with a separate Java implementation. </p>

```<code>#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <cstdint>
#include <typeinfo>

#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <boost/archive/iterators/ostream_iterator.hpp>
#include <boost/archive/iterators/remove_whitespace.hpp>

///....

using namespace std;
namespace po = boost::program_options;
namespace fs = boost::filesystem;
namespace bi = boost::archive::iterators;

    std::stringstream os;
    typedef
        bi::base64_from_binary<    // convert binary values to base64 characters
            bi::transform_width<   // retrieve 6 bit integers from a sequence of 32 bit ints
                vector<int32_t>::const_iterator,
                6,
                32
            >
        >
        base64_text;

    copy(
         base64_text(di.cbegin()),
         base64_text(di.cend()),
         ostream_iterator<char>(os)
         );

    cout << os.str() << "\n";
</code>```

<p>Now I'm trying to write the code to decode this back into a vector of integers, but this is proving much more difficult. I tried to convert the given examples to my use case (see below), but I just get an unhelpful segfault on the copy call. Frustratingly, everything I find is assuming string input/output to encode/decode. Any help is appreciated. </p>

```<code>typedef
  bi::transform_width<
    bi::binary_from_base64<bi::remove_whitespace<string::const_iterator>>,
      32, 6
  >
  base64_dec;

  vector<int32_t> decoded_ints;
  copy(
       base64_dec(base64ints.cbegin()),
       base64_dec(base64ints.cend()),
       decoded_ints.begin()
       );
</code>```

答:
You are trying to copy into empty vector, copy does not take care of inserting elements, but only copying. You have to preallocate the destination vector using resize() or just use back_inserter like this

```<code>vector<int32_t> decoded_ints;
  copy(
       base64_dec(base64ints.cbegin()),
       base64_dec(base64ints.cend()),
       std::back_inserter(decoded_ints)
       );
</code>```

EDIT001: Since there is no better answer is given and despite minimal working example wasnt introduced and I have no idea why it gets segfault I will expand my answer.

Above code should work, as well as initializing your int vector when declaring it - something like vector<int32_t> decoded_ints(base64_dec(base64ints.cbegin()),base64_dec(base64ints.cend()))
However, your whole code doesnt work, didnt check if it encodes the data correctly, but it definitely doesnt produce the right result when decoding. Looks like transform_width doesnt do the trick with something wider than 8 bits or there is a padding added to the encoded data which should be taken into account when decoding. In any case you could work around all these by pushing your int vector into string (or vector of int8_t's). Something like this.

```<code>#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <vector>
#include <iostream>
#include <memory.h>

int main()
{
    using namespace std;
    namespace bi = boost::archive::iterators;

    using IntVec = vector<int32_t>;
    IntVec di(1024, 0);

    int32_t n = 0;
    std::generate(di.begin(), di.end(), [&n]() { return n++; });

    string input(reinterpret_cast<string::pointer>(di.data()),
                 reinterpret_cast<string::pointer>(di.data()) + (di.size() * sizeof(IntVec::value_type)));
    typedef bi::base64_from_binary<bi::transform_width<string::const_iterator, 6, 8>> base64_text;
    typedef bi::transform_width<bi::binary_from_base64<string::const_iterator>, 8, 6> base64_dec;

    std::string base64ints(base64_text(input.cbegin()), base64_text(input.cend()));
    string decoded(base64_dec(base64ints.begin()), base64_dec(base64ints.end()));
    IntVec decoded_ints(reinterpret_cast<IntVec::const_pointer>(decoded.data()),
                        reinterpret_cast<IntVec::const_pointer>(decoded.data()) +
                            (decoded.size() / sizeof(IntVec::value_type)));

    if (decoded_ints.size() == di.size())
        cout << "Size matches" << std::endl;
    else
        cout << "Size does not match" << std::endl;

    if (memcmp(decoded_ints.data(), di.data(), di.size() * sizeof(int32_t)) == 0)
        cout << "Data matches" << std::endl;
    else
        cout << "Data does not match" << std::endl;
}
</code>```

Live on CoLiRu

In addition I think it is a good idea to contact Robert Ramey (boost serialization maintainer) on Boost Mailing List

Body:
Based on this code here, I was able to write some code that converts a vector of integers into a base64 encoded version. And I can confirm it is the right output by comparing with a separate Java implementation.

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <cstdint>
#include <typeinfo>

#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <boost/archive/iterators/ostream_iterator.hpp>
#include <boost/archive/iterators/remove_whitespace.hpp>

///....

using namespace std;
namespace po = boost::program_options;
namespace fs = boost::filesystem;
namespace bi = boost::archive::iterators;

    std::stringstream os;
    typedef
        bi::base64_from_binary<    // convert binary values to base64 characters
            bi::transform_width<   // retrieve 6 bit integers from a sequence of 32 bit ints
                vector<int32_t>::const_iterator,
                6,
                32
            >
        >
        base64_text;

    copy(
         base64_text(di.cbegin()),
         base64_text(di.cend()),
         ostream_iterator<char>(os)
         );

    cout << os.str() << "\n";

Now I'm trying to write the code to decode this back into a vector of integers, but this is proving much more difficult. I tried to convert the given examples to my use case (see below), but I just get an unhelpful segfault on the copy call. Frustratingly, everything I find is assuming string input/output to encode/decode. Any help is appreciated.

typedef
  bi::transform_width<
    bi::binary_from_base64<bi::remove_whitespace<string::const_iterator>>,
      32, 6
  >
  base64_dec;

  vector<int32_t> decoded_ints;
  copy(
       base64_dec(base64ints.cbegin()),
       base64_dec(base64ints.cend()),
       decoded_ints.begin()
       );

Body:
You are trying to copy into empty vector, copy does not take care of inserting elements, but only copying. You have to preallocate the destination vector using resize() or just use back_inserter like this

vector<int32_t> decoded_ints;
  copy(
       base64_dec(base64ints.cbegin()),
       base64_dec(base64ints.cend()),
       std::back_inserter(decoded_ints)
       );

EDIT001: Since there is no better answer is given and despite minimal working example wasnt introduced and I have no idea why it gets segfault I will expand my answer.

Above code should work, as well as initializing your int vector when declaring it - something like vector<int32_t> decoded_ints(base64_dec(base64ints.cbegin()),base64_dec(base64ints.cend()))
However, your whole code doesnt work, didnt check if it encodes the data correctly, but it definitely doesnt produce the right result when decoding. Looks like transform_width doesnt do the trick with something wider than 8 bits or there is a padding added to the encoded data which should be taken into account when decoding. In any case you could work around all these by pushing your int vector into string (or vector of int8_t's). Something like this.

#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <vector>
#include <iostream>
#include <memory.h>

int main()
{
    using namespace std;
    namespace bi = boost::archive::iterators;

    using IntVec = vector<int32_t>;
    IntVec di(1024, 0);

    int32_t n = 0;
    std::generate(di.begin(), di.end(), [&n]() { return n++; });

    string input(reinterpret_cast<string::pointer>(di.data()),
                 reinterpret_cast<string::pointer>(di.data()) + (di.size() * sizeof(IntVec::value_type)));
    typedef bi::base64_from_binary<bi::transform_width<string::const_iterator, 6, 8>> base64_text;
    typedef bi::transform_width<bi::binary_from_base64<string::const_iterator>, 8, 6> base64_dec;

    std::string base64ints(base64_text(input.cbegin()), base64_text(input.cend()));
    string decoded(base64_dec(base64ints.begin()), base64_dec(base64ints.end()));
    IntVec decoded_ints(reinterpret_cast<IntVec::const_pointer>(decoded.data()),
                        reinterpret_cast<IntVec::const_pointer>(decoded.data()) +
                            (decoded.size() / sizeof(IntVec::value_type)));

    if (decoded_ints.size() == di.size())
        cout << "Size matches" << std::endl;
    else
        cout << "Size does not match" << std::endl;

    if (memcmp(decoded_ints.data(), di.data(), di.size() * sizeof(int32_t)) == 0)
        cout << "Data matches" << std::endl;
    else
        cout << "Data does not match" << std::endl;
}

Live on CoLiRu

In addition I think it is a good idea to contact Robert Ramey (boost serialization maintainer) on Boost Mailing List


问:
Is exposing class and method names in the URL unsecure?
I don't use any famous framework and I've created my own one. It is actually kind of a advanced MVC. Anyway, Its routing is totally different than other frameworks. I mean, there isn't any file named route containing all routes. It will call the needed class and function automatically based on the URL. For example:

```<code>http://example.com/classname/methodname/arg1/arg2
</code>```

URL above calls this script by using autoloader:

```<code>class classname{

    public function methodname() {

        // do stuff
    }
}
</code>```

See? Everyone will know the name of class or method in my script. My question is, is that secure enough? Or is there something particular that I should know?

答:
It depends. If your framework allows arbitrary classes and function to be invoked, this means you effectively build a remote shell with a web interface. In other words: maximum insecure.

Likewise, if your application also allows file uploads, a malicious user might be able to upload their own PHP classes and then invoke it from your URLs. Without further details about your framework, it's hard to say. But you probably want to whitelist what can be called this way.

Even if the framework has some protection measures to control what code can be called, I am not a friend of leaking implementation details like this to the public. You tied your public API to a specific implementation with this. That will make it harder to change the code while maintaining the same API for clients to call.

Body:
I don't use any famous framework and I've created my own one. It is actually kind of a advanced MVC. Anyway, Its routing is totally different than other frameworks. I mean, there isn't any file named route containing all routes. It will call the needed class and function automatically based on the URL. For example:

http://example.com/classname/methodname/arg1/arg2

URL above calls this script by using autoloader:

class classname{

    public function methodname() {

        // do stuff
    }
}

See? Everyone will know the name of class or method in my script. My question is, is that secure enough? Or is there something particular that I should know?


问:
T-SQL Updating Query
I'm new to SQL and I'm trying to figure out how to SUM several columns and update an existing column with 1 or 0 if the SUM of the columns is more than 0.
Also, making sure null values get assigned a 0 value.

How to do something like the following in T-SQL?

```<code>if (select (coalesce(COL1, 0) +
coalesce(COL2 0) +
coalesce(COL3, 0) +
coalesce(COL4, 0) +
coalesce(COL5, 0) from SOMETABLE where X_CONDITION = 10)  >  0)
update SOMETABLE set ABC_COLUMN = 1
    else
    set ABC_COLUMN = 0;
</code>```

EDIT:

Currently the table looks somewhat like this:

```<code>x_condition | col1 | col2 |col3| col4| col5| abc_column
------------| -----| -----| ---| ----|-----|-----------
     7      | 1    |      |    |     |     |    0  (this in incorrect)
     7      | 0    |   0  |    |  0  |     |    0  (this is correct)
     5      | 1    |   1  |    |     |     |    0  (this is incorrect)
</code>```

I want the abc_column fixed - almost like a flag:

```<code> x_condition | col1 | col2 |col3| col4| col5| abc_column
------------| -----| -----| ---| ----|-----|-----------
     7      | 1    |      |    |     |     |    1
     7      | 0    |   0  |    |  0  |     |    0
     5      | 1    |   1  |    |     |     |    1
</code>```

Thank you!

答:
Use UPDATE statement as below format :</p>

```<code>  UPDATE SOMETABLE
  SET ABC_COLUMN = CASE WHEN ISNULL(COL1,0) > 0 THEN 1
                        WHEN ISNULL(COL2,0) > 0 THEN 1
                        WHEN ISNULL(COL3,0) > 0 THEN 1
                        WHEN ISNULL(COL4,0) > 0 THEN 1
                        WHEN ISNULL(COL5,0) > 0 THEN 1 ELSE 0 END
</code>```

Title: T-SQL Updating Query

Body:
I'm new to SQL and I'm trying to figure out how to SUM several columns and update an existing column with 1 or 0 if the SUM of the columns is more than 0.
Also, making sure null values get assigned a 0 value.

How to do something like the following in T-SQL?

if (select (coalesce(COL1, 0) +
coalesce(COL2 0) +
coalesce(COL3, 0) +
coalesce(COL4, 0) +
coalesce(COL5, 0) from SOMETABLE where X_CONDITION = 10)  >  0)
update SOMETABLE set ABC_COLUMN = 1
    else
    set ABC_COLUMN = 0;

EDIT:

Currently the table looks somewhat like this:

x_condition | col1 | col2 |col3| col4| col5| abc_column
------------| -----| -----| ---| ----|-----|-----------
     7      | 1    |      |    |     |     |    0  (this in incorrect)
     7      | 0    |   0  |    |  0  |     |    0  (this is correct)
     5      | 1    |   1  |    |     |     |    0  (this is incorrect)

I want the abc_column fixed - almost like a flag:

 x_condition | col1 | col2 |col3| col4| col5| abc_column
------------| -----| -----| ---| ----|-----|-----------
     7      | 1    |      |    |     |     |    1
     7      | 0    |   0  |    |  0  |     |    0
     5      | 1    |   1  |    |     |     |    1

Thank you!

Body:
Use UPDATE statement as below format :

  UPDATE SOMETABLE
  SET ABC_COLUMN = CASE WHEN ISNULL(COL1,0) > 0 THEN 1
                        WHEN ISNULL(COL2,0) > 0 THEN 1
                        WHEN ISNULL(COL3,0) > 0 THEN 1
                        WHEN ISNULL(COL4,0) > 0 THEN 1
                        WHEN ISNULL(COL5,0) > 0 THEN 1 ELSE 0 END


问:
ORA-39171 ORA-01659 impdp
I'm trying to restore my Oracle backup version 11.2.0.1 to another server version 11.2.0.4.

When I run the impdp, the ORA-39171 and ORA-01659 erros are shown.

impdp hosp/xxxx file=HOSP3001.DMP logfile=loghosp3001.dmp version=latest schemas=HOSP

In the .dmp file I have the following TABLESPACES and DATAFILES:

```<code>DATAFILE                                          | TABLESPACE
</code>```

```<code>/u01/app/oracle/product/11.2.0/db_1/dbs/HOSP      | HOSP
/u01/app/oracle/product/11.2.0/db_1/dbs/HOSPDATA  | HOSPDATA
/u01/app/oracle/product/11.2.0/db_1/dbs/HOSPDATA2 | HOSPDATA
/u01/app/oracle/product/11.2.0/db_1/dbs/HOSPDATA3 | HOSPDATA
</code>```

I have created in the new server the follwing TABLESPACES and DATAFILES.

```<code>CREATE TABLESPACE HOSP DATAFILE 'HOSP' SIZE 1024M ;
ALTER DATABASE DATAFILE 'HOSP' RESIZE 1024M ;
ALTER DATABASE DATAFILE 'HOSP' AUTOEXTEND ON MAXSIZE UNLIMITED ;

CREATE TABLESPACE HOSPDATA DATAFILE 'HOSPDATA' SIZE 1024M ;
ALTER DATABASE DATAFILE 'HOSPDATA' RESIZE 1024M ;
ALTER DATABASE DATAFILE 'HOSPDATA' AUTOEXTEND ON MAXSIZE UNLIMITED ;
</code>```

In this new scenario I intend to keep just one DATAFILE for the TABLESPACE "HOSPDATA".

答: you can use impdp with option "transform=segment_attributes:n"

Title: ORA-39171 ORA-01659 impdp

Body:
I'm trying to restore my Oracle backup version 11.2.0.1 to another server version 11.2.0.4.

When I run the impdp, the ORA-39171 and ORA-01659 erros are shown.

impdp hosp/xxxx file=HOSP3001.DMP logfile=loghosp3001.dmp version=latest schemas=HOSP

In the .dmp file I have the following TABLESPACES and DATAFILES:

DATAFILE                                          | TABLESPACE

/u01/app/oracle/product/11.2.0/db_1/dbs/HOSP      | HOSP
/u01/app/oracle/product/11.2.0/db_1/dbs/HOSPDATA  | HOSPDATA
/u01/app/oracle/product/11.2.0/db_1/dbs/HOSPDATA2 | HOSPDATA
/u01/app/oracle/product/11.2.0/db_1/dbs/HOSPDATA3 | HOSPDATA

I have created in the new server the follwing TABLESPACES and DATAFILES.

CREATE TABLESPACE HOSP DATAFILE 'HOSP' SIZE 1024M ;
ALTER DATABASE DATAFILE 'HOSP' RESIZE 1024M ;
ALTER DATABASE DATAFILE 'HOSP' AUTOEXTEND ON MAXSIZE UNLIMITED ;

CREATE TABLESPACE HOSPDATA DATAFILE 'HOSPDATA' SIZE 1024M ;
ALTER DATABASE DATAFILE 'HOSPDATA' RESIZE 1024M ;
ALTER DATABASE DATAFILE 'HOSPDATA' AUTOEXTEND ON MAXSIZE UNLIMITED ;

In this new scenario I intend to keep just one DATAFILE for the TABLESPACE "HOSPDATA".


问:
Get the last word that is being typed
I want to get the word that is currently being typed in a UITextField.

Case 1:

hello there

If the cursor is after the second e (meaning e has just been typed, then the word there should be returned

Case 2:

User deletes o from hello (cursor is after the second l), then the word hell should be returned

I have some code for this but it is returning all text in the UITextField.

postView.textView.delegate = self

```<code>func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    let text = (textView.text as NSString?)?.replacingCharacters(in: range, with: text)

    return true
}
</code>```

Update 1:
I have gone through these similar questions but these didn't work for me.

Get currently typed word in UITextView

Get word that is being typed

答:
Try with below code, its working at my end.</p>

```<code>func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    let nsString = textView.text as NSString?
    let newString = nsString?.replacingCharacters(in: range, with: text)
    let arr = newString?.components(separatedBy: " ")
    self.lblWord.text = arr?.last
    return true
}
</code>```

Title: Get the last word that is being typed

Body:
I want to get the word that is currently being typed in a UITextField.

Case 1:

hello there

If the cursor is after the second e (meaning e has just been typed, then the word there should be returned

Case 2:

User deletes o from hello (cursor is after the second l), then the word hell should be returned

I have some code for this but it is returning all text in the UITextField.

postView.textView.delegate = self

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    let text = (textView.text as NSString?)?.replacingCharacters(in: range, with: text)

    return true
}

Update 1:
I have gone through these similar questions but these didn't work for me.

Get currently typed word in UITextView

Get word that is being typed

Body:
Try with below code, its working at my end.

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    let nsString = textView.text as NSString?
    let newString = nsString?.replacingCharacters(in: range, with: text)
    let arr = newString?.components(separatedBy: " ")
    self.lblWord.text = arr?.last
    return true
}


问:
How to align specific layout to bottom and fix size of imageview to cover remaining space?
I have a imageview & relative layout, where the layout containing two buttons should align to bottom and circular image should stretch to take remaining space. I tried from other answers but could not do it. I have code and image below.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/cardview_light_background"
android:clickable="true">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <include layout="@layout/toolbar_child_with_progress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/toolbar_child"/>
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/toolbar_child">
        <RelativeLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            >
                <ImageView
                    android:id="@+id/iv_SavedInvoice"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:src="@drawable/service_app_logo"
                    android:scaleType="fitStart"
                    android:adjustViewBounds="true"
                    android:layout_centerHorizontal="true"
                    />

                <LinearLayout
                    android:id="@+id/ll_inner"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:layout_below="@+id/iv_SavedInvoice"
                    android:layout_alignParentBottom="true"
                    >
                    <Button
                        style="@style/PrimaryButton"
                        android:layout_marginTop="20dp"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/form_proof_replace_invoice"
                        android:id="@+id/button_ReplaceInvoice" />
                    <Button
                        style="@style/NoBorderButton"
                        android:layout_marginTop="20dp"
                        android:layout_marginBottom="20dp"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/form_proof_next"
                        android:id="@+id/button_SavedProofNext" />
                </LinearLayout>
            </RelativeLayout>
    </ScrollView>
</RelativeLayout>
</code>```

答:
I don't know why you used ScrollView and other Nested Layout. The UI that you want can be simply achieved by using layout weight attribute. You check this code and make changes according to your need.`</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/cardview_light_background"
android:clickable="true"
android:orientation="vertical">

<include
    android:id="@+id/toolbar_child"
    layout="@layout/toolbar_child_with_progress"
    android:layout_width="match_parent"
    android:layout_height="50dp" />

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1">

    <ImageView
        android:id="@+id/iv_SavedInvoice"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:adjustViewBounds="true"
        android:scaleType="fitStart"
        android:src="@mipmap/ic_launcher" />

</RelativeLayout>

<LinearLayout
    android:id="@+id/ll_inner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_below="@+id/iv_SavedInvoice"
    android:orientation="vertical">

    <Button
        android:id="@+id/button_ReplaceInvoice"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="form_proof_replace_invoice" />

    <Button
        android:id="@+id/button_SavedProofNext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="form_proof_next" />
</LinearLayout>

</LinearLayout>
</code>```

Body:
I have a imageview & relative layout, where the layout containing two buttons should align to bottom and circular image should stretch to take remaining space. I tried from other answers but could not do it. I have code and image below.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/cardview_light_background"
android:clickable="true">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <include layout="@layout/toolbar_child_with_progress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/toolbar_child"/>
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/toolbar_child">
        <RelativeLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            >
                <ImageView
                    android:id="@+id/iv_SavedInvoice"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:src="@drawable/service_app_logo"
                    android:scaleType="fitStart"
                    android:adjustViewBounds="true"
                    android:layout_centerHorizontal="true"
                    />

                <LinearLayout
                    android:id="@+id/ll_inner"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:layout_below="@+id/iv_SavedInvoice"
                    android:layout_alignParentBottom="true"
                    >
                    <Button
                        style="@style/PrimaryButton"
                        android:layout_marginTop="20dp"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/form_proof_replace_invoice"
                        android:id="@+id/button_ReplaceInvoice" />
                    <Button
                        style="@style/NoBorderButton"
                        android:layout_marginTop="20dp"
                        android:layout_marginBottom="20dp"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/form_proof_next"
                        android:id="@+id/button_SavedProofNext" />
                </LinearLayout>
            </RelativeLayout>
    </ScrollView>
</RelativeLayout>

Body:
I don't know why you used ScrollView and other Nested Layout. The UI that you want can be simply achieved by using layout weight attribute. You check this code and make changes according to your need.`

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/cardview_light_background"
android:clickable="true"
android:orientation="vertical">

<include
    android:id="@+id/toolbar_child"
    layout="@layout/toolbar_child_with_progress"
    android:layout_width="match_parent"
    android:layout_height="50dp" />

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1">

    <ImageView
        android:id="@+id/iv_SavedInvoice"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:adjustViewBounds="true"
        android:scaleType="fitStart"
        android:src="@mipmap/ic_launcher" />

</RelativeLayout>

<LinearLayout
    android:id="@+id/ll_inner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_below="@+id/iv_SavedInvoice"
    android:orientation="vertical">

    <Button
        android:id="@+id/button_ReplaceInvoice"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="form_proof_replace_invoice" />

    <Button
        android:id="@+id/button_SavedProofNext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="form_proof_next" />
</LinearLayout>

</LinearLayout>


问:
How can I initialize a C# List in the same line I declare it. (IEnumerable string Collection Example)
I am writing my testcode and I do not want wo write:

```<code>List<string> nameslist = new List<string>();
nameslist.Add("one");
nameslist.Add("two");
nameslist.Add("three");
</code>```

I would love to write

```<code>List<string> nameslist = new List<string>({"one", "two", "three"});
</code>```

However {"one", "two", "three"} is not an "IEnumerable string Collection". How can I initialise this in one line using the IEnumerable string Collection"?

答:
Change the code to

```<code>List<string> nameslist = new List<string> {"one", "two", "three"};
</code>```

or

```<code>List<string> nameslist = new List<string>(new[] {"one", "two", "three"});
</code>```

Body:
I am writing my testcode and I do not want wo write:

List<string> nameslist = new List<string>();
nameslist.Add("one");
nameslist.Add("two");
nameslist.Add("three");

I would love to write

List<string> nameslist = new List<string>({"one", "two", "three"});

However {"one", "two", "three"} is not an "IEnumerable string Collection". How can I initialise this in one line using the IEnumerable string Collection"?

Body:
Change the code to

List<string> nameslist = new List<string> {"one", "two", "three"};

or

List<string> nameslist = new List<string>(new[] {"one", "two", "three"});


问:
how to make virtual scroll work with ngFor Directive in ionic 2
I have a card that I want repeated, for that I use ngFor, but since I won't know for certain just how many cards I will be repeating, it will vary from load to load, I want to implement virtual scroll to contain a potentially large overflow. The few things I have tried don't work. This is my latest attempt.</p>

```<code><ion-content id="content">

   <ion-card id="card" *ngFor="let event of listOfEvents
     [virtualScroll]="listOfEvents" >

          <ion-item *virtualItem="let event">

       <ion-row>

                <ion-col><span class="showDetails">Guests Needed:</span> {{event.guests}} </ion-col><ion-col><span class="showDetails">Cover:</span> {{event.coverCharge}}</ion-col><ion-col><span class="showDetails">Drink Min:</span>{{event.drinkMin}} </ion-col>

        </ion-row>

            </ion-item>

         </ion-card>

    </ion-content >
</code>```

答:
You dont have to use ngFor along with [virtualScroll]. The latter does the looping.

I would try using ng-template to set virtual scroll.

```<code><ion-content id="content">

 <ng-template [virtualScroll]="listOfEvents">
   <ion-card id="card" *virtualItem="let event" >
       <ion-row>
          <ion-col><span class="showDetails">Guests Needed:</span> {{event.guests}} </ion-col>
          <ion-col><span class="showDetails">Cover:</span> {{event.coverCharge}}</ion-col>
          <ion-col><span class="showDetails">Drink Min:</span>{{event.drinkMin}} </ion-col>
        </ion-row>
    </ion-card>
 </ng-template>
</ion-content>
</code>```

Body:
I have a card that I want repeated, for that I use ngFor, but since I won't know for certain just how many cards I will be repeating, it will vary from load to load, I want to implement virtual scroll to contain a potentially large overflow. The few things I have tried don't work. This is my latest attempt.

<ion-content id="content">

   <ion-card id="card" *ngFor="let event of listOfEvents
     [virtualScroll]="listOfEvents" >

          <ion-item *virtualItem="let event">

       <ion-row>

                <ion-col>Guests Needed: {{event.guests}} </ion-col><ion-col>Cover: {{event.coverCharge}}</ion-col><ion-col>Drink Min:{{event.drinkMin}} </ion-col>

        </ion-row>

            </ion-item>

         </ion-card>

    </ion-content >

Body:
You dont have to use ngFor along with [virtualScroll]. The latter does the looping.

I would try using ng-template to set virtual scroll.

<ion-content id="content">

 <ng-template [virtualScroll]="listOfEvents">
   <ion-card id="card" *virtualItem="let event" >
       <ion-row>
          <ion-col><span class="showDetails">Guests Needed:</span> {{event.guests}} </ion-col>
          <ion-col><span class="showDetails">Cover:</span> {{event.coverCharge}}</ion-col>
          <ion-col><span class="showDetails">Drink Min:</span>{{event.drinkMin}} </ion-col>
        </ion-row>
    </ion-card>
 </ng-template>
</ion-content>


问:
Add & Delete Row for JTable of Custom Components
I'm doing step by step...

Changing LookAndFeel of JTable of Custom Component

Note: I have more custom Columns, this code it's for demonstration porpoise.

Now, I want to implement add Row and Delete Row using a class extended from DefaultTableModel, for JTable populated with custom Objects.

Here my code:

```<code>import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;

public class LAF_TableCustom_AddDelRow {

  static JFrame frame = new JFrame();

  public JComponent makeUI() {

    String[] hdrsObjects = {"PanelSpinnerRadioButton Class Column"};
    Object[][] objectMatrix = new Object[3][1];
    objectMatrix[0][0] = new PanelSpinnerRadioButtonData(false, 10, 40);
    objectMatrix[1][0] = new PanelSpinnerRadioButtonData(true,  20, 40);
    objectMatrix[2][0] = new PanelSpinnerRadioButtonData(false, 30, 40);

//    JTable table = new JTable(new DefaultTableModel(objectMatrix, hdrsObjects)) {
    JTable table = new JTable(new PSRBTableModel(objectMatrix, hdrsObjects)) {
      @Override public void updateUI() {
        super.updateUI();
        setRowHeight(30);
        TableColumn tc = getColumn("PanelSpinnerRadioButton Class Column");
        tc.setCellRenderer(new PSRBTableCellRenderer());
        tc.setCellEditor(new PSRBTableCellEditor());
      }
    };

    JScrollPane scrollPane = new JScrollPane(table);
    scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
    scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

    JPanel pV = new JPanel();
    pV.setLayout(new BoxLayout(pV, BoxLayout.PAGE_AXIS));

    JButton bAddRow = new JButton("Add Row");
    bAddRow.addActionListener(new ActionListener() {
      @Override public void actionPerformed(ActionEvent evt) {
        ((PSRBTableModel)table.getModel()).addRow(
            new Object[] { new PanelSpinnerRadioButtonData(false, 10, 40) }
        );
//        ((DefaultTableModel)table.getModel()).addRow(
//            new Object[] { new PanelSpinnerRadioButtonData(false, 10, 40) }
//        );
      }
    });

    pV.add(bAddRow);
    pV.add(scrollPane);
    return pV;
  }

  public static void main(String... args) {
    EventQueue.invokeLater(() -> {
    frame.getContentPane().add(new LAF_TableCustom_AddDelRow().makeUI());
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setSize(320, 240);
    frame.setVisible(true);
    });
  }

}

class PanelSpinnerRadioButtonData {
  private boolean opt02 = false;
  private Integer from = 0;
  private Integer size = 1;

  PanelSpinnerRadioButtonData() {
    this(false, 5, 10);
  }
  PanelSpinnerRadioButtonData(boolean opt02, Integer from, Integer size) {
    this.opt02 = opt02;
    this.from = from;
    this.size = size;
  }
  public boolean getOption() {
    return opt02;
  }
  public Integer getFrom() {
    return from;
  }
  public Integer getSize() {
    return size;
  }
}

class PanelSpinnerRadioButton extends JPanel {
  public final JRadioButton jrbOption01 = new JRadioButton("01");
  public final JRadioButton jrbOption02 = new JRadioButton("12");
  public final JSpinner jspnValues = new JSpinner(new SpinnerNumberModel(5, 0, 10, 1));
  public final JButton jbRemoveRow = new JButton("Del Row");

  private final JPanel panel = new JPanel();

  PanelSpinnerRadioButton() {
    this(new PanelSpinnerRadioButtonData(false, 20, 40));
  }
  PanelSpinnerRadioButton(PanelSpinnerRadioButtonData data) {
    super();

    panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
    panel.add(jrbOption01);
    panel.add(jrbOption02);
    panel.add(jspnValues);
    panel.add(jbRemoveRow);

    jbRemoveRow.addActionListener(new ActionListener() {
      @Override public void actionPerformed(ActionEvent e) {
        JTable table = (JTable)SwingUtilities.getAncestorOfClass(
            JTable.class, (Component) e.getSource());
        int row = table.getEditingRow();
        table.getCellEditor().stopCellEditing();
//        ((DefaultTableModel) table.getModel()).removeRow(row);
        ((PSRBTableModel) table.getModel()).removeRow(row);

      }
    });

    ButtonGroup bg = new ButtonGroup();
    bg.add(jrbOption01);
    bg.add(jrbOption02);
    ((SpinnerNumberModel) jspnValues.getModel()).setMaximum(data.getSize());
    setData(data);

    init();
  }
  private void init() {
    setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
    setBackground(new Color(0, 0, 0, 0));
    add(panel);
  }
  public void setData(PanelSpinnerRadioButtonData data) {
    if (data.getOption()) {
      jrbOption02.setSelected(true);
    } else {
      jrbOption01.setSelected(true);
    }
    ((SpinnerNumberModel) jspnValues.getModel()).setValue(data.getFrom());
  }
  public PanelSpinnerRadioButtonData getData() {
    return new PanelSpinnerRadioButtonData(
        jrbOption02.isSelected(),
        (Integer) ((SpinnerNumberModel) jspnValues.getModel()).getValue(),
        (Integer) ((SpinnerNumberModel) jspnValues.getModel()).getMaximum());
  }

}

class PSRBTableCellRenderer implements TableCellRenderer {
  private final PanelSpinnerRadioButton renderer = new PanelSpinnerRadioButton();
  @Override public Component getTableCellRendererComponent(
      JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    if (value instanceof PanelSpinnerRadioButtonData) {
      renderer.setData((PanelSpinnerRadioButtonData) value);
    }
    return renderer;
  }
}

class PSRBTableCellEditor extends AbstractCellEditor implements TableCellEditor {
  private final PanelSpinnerRadioButton editor = new PanelSpinnerRadioButton();
  @Override public Object getCellEditorValue() {
    return editor.getData();
  }
  @Override public Component getTableCellEditorComponent(
      JTable table, Object value, boolean isSelected, int row, int column) {
    if (value instanceof PanelSpinnerRadioButtonData) {
      editor.setData((PanelSpinnerRadioButtonData) value);
    }
    return editor;
  }

}

//class PSRBTableModel extends AbstractTableModel {
class PSRBTableModel extends DefaultTableModel {

  private final Object[][] data;
  private final Object[] columns;

  public PSRBTableModel(Object[][] data, Object[] columns) {
    this.data = data;
    this.columns = columns;
  }

  @Override public Object getValueAt(int rowIndex, int columnIndex) {
    if (data != null) {
      if (data.length > 0) {
        return data[rowIndex][columnIndex];
      }
    }
    return null;
  }

  @Override public int getColumnCount() {
    return ((columns == null) ? 0: columns.length);
  }

  @Override public int getRowCount() {
    return ((data == null) ? 0: data.length);
  }

  @Override public Class getColumnClass(int columnIndex) {
    if (data != null) {
      if (data.length > 0) {
        if (data[0][columnIndex] instanceof PanelSpinnerRadioButton) {
          return PanelSpinnerRadioButton.class;
        }
        return data[0][columnIndex].getClass();
      }
    }
    return Object.class;
  }

  @Override public boolean isCellEditable(int rowIndex, int columnIndex) {
    if (data != null) {
      if (data.length > 0) {
        if (data[0][columnIndex] instanceof PanelSpinnerRadioButton) {
          return true;
        }
      }
    }
    return true;
  }

  @Override public void setValueAt(Object value, int row, int col) {
    data[row][col] = value;
    fireTableCellUpdated(row, col);
  }

  @Override public String getColumnName(int columnIndex) {
    return (String)columns[columnIndex];
  }

  @Override public void removeRow(int row) {
    fireTableRowsDeleted(row, row);
    System.out.println("fireTableRowsDeleted(" + row + ", " + row + ");");
  }

  @Override public void addRow(Object[] rowData) {
    super.addRow(rowData);
  }
}
</code>```

The problem!!!

When I pressed the Del Row Button, the row wasn't deleted!
I got the print message related with the Row: fireTableRowsDeleted(ROW, ROW);I

When I pressed the Add Row I got this Exception...

```<code>Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 3 > 0
    at java.util.Vector.insertElementAt(Vector.java:598)
    at javax.swing.table.DefaultTableModel.insertRow(DefaultTableModel.java:374)
    at javax.swing.table.DefaultTableModel.addRow(DefaultTableModel.java:350)
    at javax.swing.table.DefaultTableModel.addRow(DefaultTableModel.java:361)
    at PSRBTableModel.addRow(LAF_TableCustom_AddDelRow.java:248)
    at LAF_TableCustom_AddDelRow$2.actionPerformed(LAF_TableCustom_AddDelRow.java:45)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
</code>```

How Can I to do these operations (removeRow, addRow), overriding respective methods with my Custom DefaultTableModel?

This answer, is not working

EDIT

```<code>  //Doesn't Work
  @Override public void removeRow(int row) {
    super.removeRow(row);
  }

  //Doesn't Work
  @Override public void removeRow(int row) {
    getDataVector().removeElementAt(row);
    fireTableRowsDeleted(row, row);
  }

  //Doesn't Work (Not overriding the Method)
  //  @Override public void removeRow(int row) {
  //    getDataVector().removeElementAt(row);
  //  }
</code>```

答:
The basic problem is, DefaultTableModel is already backed by a Vector, which manages the row/column data.  But your extension of it, implements it's own data structure making the Vector redundant.

If you take the time to look at the source code for DefaultTabelModel you'll find that addRow(Object[]) calls addRow(Vector) which makes use of getRowCount, which call your implementation of it...

```<code>/**
 *  Adds a row to the end of the model.  The new row will contain
 *  <code>null</code> values unless <code>rowData</code> is specified.
 *  Notification of the row being added will be generated.
 *
 * @param   rowData          optional data of the row being added
 */
public void addRow(Vector rowData) {
    insertRow(getRowCount(), rowData);
}

/**
 *  Adds a row to the end of the model.  The new row will contain
 *  <code>null</code> values unless <code>rowData</code> is specified.
 *  Notification of the row being added will be generated.
 *
 * @param   rowData          optional data of the row being added
 */
public void addRow(Object[] rowData) {
    addRow(convertToVector(rowData));
}
</code>```

This means that Vector has nothing in it, but your code says that there are 3 rows, which basically triggers all the core issues.

You have a choice to make.  Either use DefaultTableModel and throw away you own data structures (data and columns) or use something like AbstractTableModel which will force you to implement your own data structures.

May basic recommendation would be to go for the first, as the DefaultTableModel should be capable of providing the basic underlying requirements you seem to need.

For a, really, basic example:

```<code>class PSRBTableModel extends DefaultTableModel {

    public PSRBTableModel(Object[][] data, Object[] columns) {
        super(data, columns);
    }

    @Override
    public Class getColumnClass(int columnIndex) {
        if (getRowCount() > 0) {
            Object value = getValueAt(0, columnIndex);
            if (value instanceof PanelSpinnerRadioButton) {
                return PanelSpinnerRadioButton.class;
            }
        }
        return Object.class;
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return getColumnClass(columnIndex) == PanelSpinnerRadioButton.class;
    }
}
</code>```

Body:
I'm doing step by step...

Changing LookAndFeel of JTable of Custom Component

Note: I have more custom Columns, this code it's for demonstration porpoise.

Now, I want to implement add Row and Delete Row using a class extended from DefaultTableModel, for JTable populated with custom Objects.

Here my code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;

public class LAF_TableCustom_AddDelRow {

  static JFrame frame = new JFrame();

  public JComponent makeUI() {

    String[] hdrsObjects = {"PanelSpinnerRadioButton Class Column"};
    Object[][] objectMatrix = new Object[3][1];
    objectMatrix[0][0] = new PanelSpinnerRadioButtonData(false, 10, 40);
    objectMatrix[1][0] = new PanelSpinnerRadioButtonData(true,  20, 40);
    objectMatrix[2][0] = new PanelSpinnerRadioButtonData(false, 30, 40);

//    JTable table = new JTable(new DefaultTableModel(objectMatrix, hdrsObjects)) {
    JTable table = new JTable(new PSRBTableModel(objectMatrix, hdrsObjects)) {
      @Override public void updateUI() {
        super.updateUI();
        setRowHeight(30);
        TableColumn tc = getColumn("PanelSpinnerRadioButton Class Column");
        tc.setCellRenderer(new PSRBTableCellRenderer());
        tc.setCellEditor(new PSRBTableCellEditor());
      }
    };

    JScrollPane scrollPane = new JScrollPane(table);
    scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
    scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

    JPanel pV = new JPanel();
    pV.setLayout(new BoxLayout(pV, BoxLayout.PAGE_AXIS));

    JButton bAddRow = new JButton("Add Row");
    bAddRow.addActionListener(new ActionListener() {
      @Override public void actionPerformed(ActionEvent evt) {
        ((PSRBTableModel)table.getModel()).addRow(
            new Object[] { new PanelSpinnerRadioButtonData(false, 10, 40) }
        );
//        ((DefaultTableModel)table.getModel()).addRow(
//            new Object[] { new PanelSpinnerRadioButtonData(false, 10, 40) }
//        );
      }
    });

    pV.add(bAddRow);
    pV.add(scrollPane);
    return pV;
  }

  public static void main(String... args) {
    EventQueue.invokeLater(() -> {
    frame.getContentPane().add(new LAF_TableCustom_AddDelRow().makeUI());
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setSize(320, 240);
    frame.setVisible(true);
    });
  }

}

class PanelSpinnerRadioButtonData {
  private boolean opt02 = false;
  private Integer from = 0;
  private Integer size = 1;

  PanelSpinnerRadioButtonData() {
    this(false, 5, 10);
  }
  PanelSpinnerRadioButtonData(boolean opt02, Integer from, Integer size) {
    this.opt02 = opt02;
    this.from = from;
    this.size = size;
  }
  public boolean getOption() {
    return opt02;
  }
  public Integer getFrom() {
    return from;
  }
  public Integer getSize() {
    return size;
  }
}

class PanelSpinnerRadioButton extends JPanel {
  public final JRadioButton jrbOption01 = new JRadioButton("01");
  public final JRadioButton jrbOption02 = new JRadioButton("12");
  public final JSpinner jspnValues = new JSpinner(new SpinnerNumberModel(5, 0, 10, 1));
  public final JButton jbRemoveRow = new JButton("Del Row");

  private final JPanel panel = new JPanel();

  PanelSpinnerRadioButton() {
    this(new PanelSpinnerRadioButtonData(false, 20, 40));
  }
  PanelSpinnerRadioButton(PanelSpinnerRadioButtonData data) {
    super();

    panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
    panel.add(jrbOption01);
    panel.add(jrbOption02);
    panel.add(jspnValues);
    panel.add(jbRemoveRow);

    jbRemoveRow.addActionListener(new ActionListener() {
      @Override public void actionPerformed(ActionEvent e) {
        JTable table = (JTable)SwingUtilities.getAncestorOfClass(
            JTable.class, (Component) e.getSource());
        int row = table.getEditingRow();
        table.getCellEditor().stopCellEditing();
//        ((DefaultTableModel) table.getModel()).removeRow(row);
        ((PSRBTableModel) table.getModel()).removeRow(row);

      }
    });

    ButtonGroup bg = new ButtonGroup();
    bg.add(jrbOption01);
    bg.add(jrbOption02);
    ((SpinnerNumberModel) jspnValues.getModel()).setMaximum(data.getSize());
    setData(data);

    init();
  }
  private void init() {
    setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
    setBackground(new Color(0, 0, 0, 0));
    add(panel);
  }
  public void setData(PanelSpinnerRadioButtonData data) {
    if (data.getOption()) {
      jrbOption02.setSelected(true);
    } else {
      jrbOption01.setSelected(true);
    }
    ((SpinnerNumberModel) jspnValues.getModel()).setValue(data.getFrom());
  }
  public PanelSpinnerRadioButtonData getData() {
    return new PanelSpinnerRadioButtonData(
        jrbOption02.isSelected(),
        (Integer) ((SpinnerNumberModel) jspnValues.getModel()).getValue(),
        (Integer) ((SpinnerNumberModel) jspnValues.getModel()).getMaximum());
  }

}

class PSRBTableCellRenderer implements TableCellRenderer {
  private final PanelSpinnerRadioButton renderer = new PanelSpinnerRadioButton();
  @Override public Component getTableCellRendererComponent(
      JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    if (value instanceof PanelSpinnerRadioButtonData) {
      renderer.setData((PanelSpinnerRadioButtonData) value);
    }
    return renderer;
  }
}

class PSRBTableCellEditor extends AbstractCellEditor implements TableCellEditor {
  private final PanelSpinnerRadioButton editor = new PanelSpinnerRadioButton();
  @Override public Object getCellEditorValue() {
    return editor.getData();
  }
  @Override public Component getTableCellEditorComponent(
      JTable table, Object value, boolean isSelected, int row, int column) {
    if (value instanceof PanelSpinnerRadioButtonData) {
      editor.setData((PanelSpinnerRadioButtonData) value);
    }
    return editor;
  }

}

//class PSRBTableModel extends AbstractTableModel {
class PSRBTableModel extends DefaultTableModel {

  private final Object[][] data;
  private final Object[] columns;

  public PSRBTableModel(Object[][] data, Object[] columns) {
    this.data = data;
    this.columns = columns;
  }

  @Override public Object getValueAt(int rowIndex, int columnIndex) {
    if (data != null) {
      if (data.length > 0) {
        return data[rowIndex][columnIndex];
      }
    }
    return null;
  }

  @Override public int getColumnCount() {
    return ((columns == null) ? 0: columns.length);
  }

  @Override public int getRowCount() {
    return ((data == null) ? 0: data.length);
  }

  @Override public Class getColumnClass(int columnIndex) {
    if (data != null) {
      if (data.length > 0) {
        if (data[0][columnIndex] instanceof PanelSpinnerRadioButton) {
          return PanelSpinnerRadioButton.class;
        }
        return data[0][columnIndex].getClass();
      }
    }
    return Object.class;
  }

  @Override public boolean isCellEditable(int rowIndex, int columnIndex) {
    if (data != null) {
      if (data.length > 0) {
        if (data[0][columnIndex] instanceof PanelSpinnerRadioButton) {
          return true;
        }
      }
    }
    return true;
  }

  @Override public void setValueAt(Object value, int row, int col) {
    data[row][col] = value;
    fireTableCellUpdated(row, col);
  }

  @Override public String getColumnName(int columnIndex) {
    return (String)columns[columnIndex];
  }

  @Override public void removeRow(int row) {
    fireTableRowsDeleted(row, row);
    System.out.println("fireTableRowsDeleted(" + row + ", " + row + ");");
  }

  @Override public void addRow(Object[] rowData) {
    super.addRow(rowData);
  }
}

The problem!!!

When I pressed the Del Row Button, the row wasn't deleted!
I got the print message related with the Row: fireTableRowsDeleted(ROW, ROW);I

When I pressed the Add Row I got this Exception...

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 3 > 0
    at java.util.Vector.insertElementAt(Vector.java:598)
    at javax.swing.table.DefaultTableModel.insertRow(DefaultTableModel.java:374)
    at javax.swing.table.DefaultTableModel.addRow(DefaultTableModel.java:350)
    at javax.swing.table.DefaultTableModel.addRow(DefaultTableModel.java:361)
    at PSRBTableModel.addRow(LAF_TableCustom_AddDelRow.java:248)
    at LAF_TableCustom_AddDelRow$2.actionPerformed(LAF_TableCustom_AddDelRow.java:45)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)

How Can I to do these operations (removeRow, addRow), overriding respective methods with my Custom DefaultTableModel?

This answer, is not working

EDIT

  //Doesn't Work
  @Override public void removeRow(int row) {
    super.removeRow(row);
  }

  //Doesn't Work
  @Override public void removeRow(int row) {
    getDataVector().removeElementAt(row);
    fireTableRowsDeleted(row, row);
  }

  //Doesn't Work (Not overriding the Method)
  //  @Override public void removeRow(int row) {
  //    getDataVector().removeElementAt(row);
  //  }

Body:
The basic problem is, DefaultTableModel is already backed by a Vector, which manages the row/column data.  But your extension of it, implements it's own data structure making the Vector redundant.

If you take the time to look at the source code for DefaultTabelModel you'll find that addRow(Object[]) calls addRow(Vector) which makes use of getRowCount, which call your implementation of it...

/**
 *  Adds a row to the end of the model.  The new row will contain
 *  <code>null</code> values unless <code>rowData</code> is specified.
 *  Notification of the row being added will be generated.
 *
 * @param   rowData          optional data of the row being added
 */
public void addRow(Vector rowData) {
    insertRow(getRowCount(), rowData);
}

/**
 *  Adds a row to the end of the model.  The new row will contain
 *  <code>null</code> values unless <code>rowData</code> is specified.
 *  Notification of the row being added will be generated.
 *
 * @param   rowData          optional data of the row being added
 */
public void addRow(Object[] rowData) {
    addRow(convertToVector(rowData));
}

This means that Vector has nothing in it, but your code says that there are 3 rows, which basically triggers all the core issues.

You have a choice to make.  Either use DefaultTableModel and throw away you own data structures (data and columns) or use something like AbstractTableModel which will force you to implement your own data structures.

May basic recommendation would be to go for the first, as the DefaultTableModel should be capable of providing the basic underlying requirements you seem to need.

For a, really, basic example:

class PSRBTableModel extends DefaultTableModel {

    public PSRBTableModel(Object[][] data, Object[] columns) {
        super(data, columns);
    }

    @Override
    public Class getColumnClass(int columnIndex) {
        if (getRowCount() > 0) {
            Object value = getValueAt(0, columnIndex);
            if (value instanceof PanelSpinnerRadioButton) {
                return PanelSpinnerRadioButton.class;
            }
        }
        return Object.class;
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return getColumnClass(columnIndex) == PanelSpinnerRadioButton.class;
    }
}


问:
how to get MONTHS, DAYS and weeks (android datepicker)
UPDATE

I am creating a pregnancy due date countdown, so I use android.widget.DatePicker as a tool to set the due date.

For example:

the set due date is Jan. 9 2015

the date now is Nov. 9 2014

so the left months, days and weeks is 2 months, 62 days and 8weeks

So far i can only display the set due date.

Question:
How to get the exact months weeks and days left when the user set the due date.

UPDATE CODE

Here's the code:

```<code>private TextView txtResultDueDate ;
       private DatePicker datePicker;
       private Calendar calendar;
       private int year;
       private int month;
       private int day;

       static final int DATE_DIALOG_ID = 999;

       @Override
       protected void onCreate(Bundle savedInstanceState) {

          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_profile);

           txtResultDueDate = (TextView) findViewById(R.id.txtDue);
           btnChangeDate = (Button)findViewById(R.id.button1);

            calendar = Calendar.getInstance();
            year = calendar.get(Calendar.YEAR);
            month = calendar.get(Calendar.MONTH);
            day = calendar.get(Calendar.DAY_OF_MONTH);
            showDate(year, month+1, day);

       @SuppressWarnings("deprecation")
       public void setDate(View view) {
          showDialog(999);
          Toast.makeText(getApplicationContext(), "ca", Toast.LENGTH_SHORT)
          .show();
       }

       @Override
       protected Dialog onCreateDialog(int id) {
       // TODO Auto-generated method stub
          if (id == 999) {
             return new DatePickerDialog(this, myDateListener, year, month, day);
           }
          return null;
       }

       private DatePickerDialog.OnDateSetListener myDateListener
       = new DatePickerDialog.OnDateSetListener() {

       @Override
       public void onDateSet(DatePicker arg0, int year, int month, int day) {
     Chronology chrono = GregorianChronology.getInstance();
       DateTime end = new DateTime(arg0.getYear(), arg0.getMonth(), arg0.getDayOfMonth(), 0, 0, chrono);

       DateTime current = new DateTime();
       Interval interval = new Interval(current.toInstant(), end.toInstant());
       Period duePeriod = interval.toPeriod();
       showDate(duePeriod.getYears(), duePeriod.getMonths(), duePeriod.getDays());

       }
       };

       private void showDate(int year, int month, int day) {
          txtResultDueDate.setText(new StringBuilder().append(day).append("/")
          .append(month).append("/").append(year));
       }
</code>```

This is the error that I encounter when I set the due date using DatePicker:

FATAL EXCEPTION: main

java.lang.IllegalArgumentException: The end instant must be greater orequal to the start

at org.joda.time.base.Abstraction.checkInterval(AbstractInterval.java.63)

at org.joda.time.base.BaseInterval(BaseInterval.java:94)

at org.joda.time.Interval.(Interval.java.122)

at com.date.androin.Profile$1.onDataset(Profile.java:168)

at android.app.DatePickerDialog.tryNotifyDataSet(DatePickerDialog.java.148)

at android.app.DatePickerDialog.onClick(DatePickerDialog.java.116)

at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)

at android.os.Handler.dispatchMessage(Handler.java:99)

at android.os.Looper.loop(Looper.java:137)

at android.app.ActivityThread.main(ActivityThread.java:5103)

at java.lang.reflect.Method.invokeNative(Native Method)

at java.lang.reflect.Method.invoke(Method.java:511)

at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)

at dalvik.system.NativeStrat.main(Native Method)

答:
```<code>this code is to find week from selected date,it's proper work.
Calendar date1 = Calendar.getInstance();
        Calendar date2 = Calendar.getInstance();

        date1.clear();
        date1.set(Integer.parseInt(selected_year), Integer.parseInt(selected_month), Integer.parseInt(selected_date)); // set date 1 (yyyy,mm,dd)
        System.out.println("Selected Date==>>" + date1);

        date2.clear();
        date2.set(Integer.parseInt(current_year), Integer.parseInt(current_month), Integer.parseInt(current_date));
        System.out.println("Current Date==>>" + date2);

        long diff = date2.getTimeInMillis() - date1.getTimeInMillis();
        float dayCount = (float) diff / (24 * 60 * 60 * 1000);
        week = (int) (dayCount / 7);

        if (week <= 0) {
            Toast.makeText(this, "Sry System Error", Toast.LENGTH_SHORT).show();
            System.out.println("Week==>>" + week);
            test = false;
        } else {
            Toast.makeText(this, "Done", Toast.LENGTH_SHORT).show();
            System.out.println("Week==>>" + week);
            test = true;
        }
</code>```

Body:
UPDATE

I am creating a pregnancy due date countdown, so I use android.widget.DatePicker as a tool to set the due date.

For example:

the set due date is Jan. 9 2015

the date now is Nov. 9 2014

so the left months, days and weeks is 2 months, 62 days and 8weeks

So far i can only display the set due date.

Question:
How to get the exact months weeks and days left when the user set the due date.

UPDATE CODE

Here's the code:

private TextView txtResultDueDate ;
       private DatePicker datePicker;
       private Calendar calendar;
       private int year;
       private int month;
       private int day;

       static final int DATE_DIALOG_ID = 999;

       @Override
       protected void onCreate(Bundle savedInstanceState) {

          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_profile);

           txtResultDueDate = (TextView) findViewById(R.id.txtDue);
           btnChangeDate = (Button)findViewById(R.id.button1);

            calendar = Calendar.getInstance();
            year = calendar.get(Calendar.YEAR);
            month = calendar.get(Calendar.MONTH);
            day = calendar.get(Calendar.DAY_OF_MONTH);
            showDate(year, month+1, day);

       @SuppressWarnings("deprecation")
       public void setDate(View view) {
          showDialog(999);
          Toast.makeText(getApplicationContext(), "ca", Toast.LENGTH_SHORT)
          .show();
       }

       @Override
       protected Dialog onCreateDialog(int id) {
       // TODO Auto-generated method stub
          if (id == 999) {
             return new DatePickerDialog(this, myDateListener, year, month, day);
           }
          return null;
       }

       private DatePickerDialog.OnDateSetListener myDateListener
       = new DatePickerDialog.OnDateSetListener() {

       @Override
       public void onDateSet(DatePicker arg0, int year, int month, int day) {
     Chronology chrono = GregorianChronology.getInstance();
       DateTime end = new DateTime(arg0.getYear(), arg0.getMonth(), arg0.getDayOfMonth(), 0, 0, chrono);

       DateTime current = new DateTime();
       Interval interval = new Interval(current.toInstant(), end.toInstant());
       Period duePeriod = interval.toPeriod();
       showDate(duePeriod.getYears(), duePeriod.getMonths(), duePeriod.getDays());

       }
       };

       private void showDate(int year, int month, int day) {
          txtResultDueDate.setText(new StringBuilder().append(day).append("/")
          .append(month).append("/").append(year));
       }

This is the error that I encounter when I set the due date using DatePicker:

FATAL EXCEPTION: main

java.lang.IllegalArgumentException: The end instant must be greater orequal to the start

at org.joda.time.base.Abstraction.checkInterval(AbstractInterval.java.63)

at org.joda.time.base.BaseInterval(BaseInterval.java:94)

at org.joda.time.Interval.(Interval.java.122)

at com.date.androin.Profile$1.onDataset(Profile.java:168)

at android.app.DatePickerDialog.tryNotifyDataSet(DatePickerDialog.java.148)

at android.app.DatePickerDialog.onClick(DatePickerDialog.java.116)

at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)

at android.os.Handler.dispatchMessage(Handler.java:99)

at android.os.Looper.loop(Looper.java:137)

at android.app.ActivityThread.main(ActivityThread.java:5103)

at java.lang.reflect.Method.invokeNative(Native Method)

at java.lang.reflect.Method.invoke(Method.java:511)

at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)

at dalvik.system.NativeStrat.main(Native Method)


问:
Opening New Window for Every Iteration, Selenium
I am trying to loop through a list of string coordinates to navigate to a specific google earth page. I want a new window opened and the previous closed for each iteration and also need to switch to the new window. I am not sure how to make Selenium open a new window with each iteration, can someone explain how to do this?

Right now if I loop through these coordinates the second iteration is directed to a different page and puts me in a kind of infinite loop, but seems to work fine when the window is initially opened, hence why I want to open multiple windows.

Thanks for your help.

```</p>

```width, height = get_screen_res()
driver = webdriver.Chrome()
driver.set_window_size(width, height)
driver.maximize_window()
driver.switch_to_window(driver.window_handles[0])

for i, c in enumerate(coordinates):
    filepath = '../images/Jafay/' + str(i) + '.png'
    lat, lon = c.split(',')
    url = 'http://earth.google.com/web/@{},{},1615.83371101a,196.41606213d,35y,0h,0t,0r'.format(lat, lon)
    driver.get(url)
    time.sleep(30)
    driver.save_screenshot(filepath)
    driver.close()
```

答:
The problem is in the last line. Don't use driver.close() inside the loop, use it when you finish the script. You also don't need to set the screen size when using maximize_window() and don't need to use switch_to_window() as you have only one window in this point

```<code>driver = webdriver.Chrome()
driver.maximize_window()

for i, c in enumerate(coordinates):
    filepath = '../images/Jafay/' + str(i) + '.png'
    lat, lon = c.split(',')
    url = 'http://earth.google.com/web/@{},{},1615.83371101a,196.41606213d,35y,0h,0t,0r'.format(lat, lon)
    driver.get(url)
    time.sleep(30)
    driver.save_screenshot(filepath)

driver.close()
</code>```

Body:
I am trying to loop through a list of string coordinates to navigate to a specific google earth page. I want a new window opened and the previous closed for each iteration and also need to switch to the new window. I am not sure how to make Selenium open a new window with each iteration, can someone explain how to do this?

Right now if I loop through these coordinates the second iteration is directed to a different page and puts me in a kind of infinite loop, but seems to work fine when the window is initially opened, hence why I want to open multiple windows.

Thanks for your help.

```

width, height = get_screen_res()
driver = webdriver.Chrome()
driver.set_window_size(width, height)
driver.maximize_window()
driver.switch_to_window(driver.window_handles[0])

for i, c in enumerate(coordinates):
    filepath = '../images/Jafay/' + str(i) + '.png'
    lat, lon = c.split(',')
    url = 'http://earth.google.com/web/@{},{},1615.83371101a,196.41606213d,35y,0h,0t,0r'.format(lat, lon)
    driver.get(url)
    time.sleep(30)
    driver.save_screenshot(filepath)
    driver.close()

Body:
The problem is in the last line. Don't use driver.close() inside the loop, use it when you finish the script. You also don't need to set the screen size when using maximize_window() and don't need to use switch_to_window() as you have only one window in this point

driver = webdriver.Chrome()
driver.maximize_window()

for i, c in enumerate(coordinates):
    filepath = '../images/Jafay/' + str(i) + '.png'
    lat, lon = c.split(',')
    url = 'http://earth.google.com/web/@{},{},1615.83371101a,196.41606213d,35y,0h,0t,0r'.format(lat, lon)
    driver.get(url)
    time.sleep(30)
    driver.save_screenshot(filepath)

driver.close()