问:
Apache spark - how to monitor Kafka message delivery?
Would like to monitor Kafka message delivery metrics - mostly how many messages were consumed or lost, latency, eventually consumer offsets and so on...

Found Apache Spark, but I don't really understand, if it can "plugged easily into Kafka" without writing any (java) code.

What I would appreciate is just to change configuration for Kafka connection in some configuration file, where to store message delivery metrics and display and query it in some UI.

Is there "more automated" way to use Spark-Kafka message delivery monitoring, than writing (java) applications from scratch ?

Are there some already finished applications, which can be used freely ?

How to set the chain Kafka - Spark - (database ?) - UI in the most easy and automated way ?

Can Spark monitor other metrics also - clusters, brokers, topics, insync replicas, number of partitions, ... and so on ?

答:
After experiments with different software, kafka-monitor showed to fit best for my case.

It creates topic with partitions over whole cluster and provides metrics about production and consumption like message loss, duplication and end-to-end lag.

Start kafka-monitor like so:

```<code>cd <path_to_kafka_monitor>
export JMX_PORT=<some_port>
./bin/kafka-monitor-start.sh config/kafka-monitor.properties
</code>```

Metrics are collected with jmxTrans. Query used:

```<code>{
    "servers": [{
        "port": "9999",
        "host": "127.0.0.1",
        "queries": [{
                "obj": "kafka.consumer:type=consumer-coordinator-metrics,client-id=*",
                "attr": ["assigned-partitions","commit-latency-avg","commit-rate","heartbeat-rate","heartbeat-response-time-max",
                        "join-rate","join-time-avg","join-time-max","last-heartbeat-seconds-ago","sync-rate","sync-time-avg","sync-time-max"],
                "resultAlias": "monitor-consumer.consumer-coordinator-metrics;client-id",
                "outputWriters": [{
                    "@class": "com.googlecode.jmxtrans.model.output.InfluxDbWriterFactory",
                    "url": "http://127.0.0.1:8086/",
                    "username": "root",
                    "password": "root",
                    "database": "monitor",
                    "typeNames": ["client-id"]
                }]
            },
            {
                "obj": "kafka.consumer:type=consumer-fetch-manager-metrics,client-id=*",
                "attr": ["bytes-consumed-rate","fetch-latency-avg","fetch-latency-max","records-consumed-rate","records-lag-max",
                        "records-per-request-avg"],
                "resultAlias": "monitor-consumer.consumer-fetch-manager-metrics,client-id",
                "outputWriters": [{
                    "@class": "com.googlecode.jmxtrans.model.output.InfluxDbWriterFactory",
                    "url": "http://127.0.0.1:8086/",
                    "username": "root",
                    "password": "root",
                    "database": "monitor",
                    "typeNames": ["client-id"]
                }]
            },
            {
                "obj": "kafka.consumer:type=consumer-fetch-manager-metrics,client-id=*,topic=*",
                "attr": ["bytes-consumed-rate","fetch-size-avg","fetch-size-max","records-consumed-rate","records-per-request-avg"],
                "resultAlias": "monitor-consumer-fetch-manager-metrics;client-id,topic",
                "outputWriters": [{
                    "@class": "com.googlecode.jmxtrans.model.output.InfluxDbWriterFactory",
                    "url": "http://127.0.0.1:8086/",
                    "username": "root",
                    "password": "root",
                    "database": "monitor",
                    "typeNames": ["client-id","topic"]
                }]
            },
            {
                "obj": "kafka.consumer:type=consumer-metrics,client-id=*",
                "attr": [],
                "resultAlias": "monitor-consumer-metrics;client-id",
                "outputWriters": [{
                    "@class": "com.googlecode.jmxtrans.model.output.InfluxDbWriterFactory",
                    "url": "http://127.0.0.1:8086/",
                    "username": "root",
                    "password": "root",
                    "database": "monitor",
                    "typeNames": ["client-id"]
                }]
            },
            {
                "obj": "kafka.consumer:type=consumer-node-metrics,client-id=*,node-id=*",
                "attr": ["incoming-byte-rate","outgoing-byte-rate","request-latency-avg","request-rate","request-size-avg","response-rate"],
                "resultAlias": "monitor-consumer-node-metrics;client-id,node-id",
                "outputWriters": [{
                    "@class": "com.googlecode.jmxtrans.model.output.InfluxDbWriterFactory",
                    "url": "http://127.0.0.1:8086/",
                    "username": "root",
                    "password": "root",
                    "database": "monitor",
                    "typeNames": ["client-id","node-id"]
                }]
            },
            {
                "obj": "kafka.producer:type=producer-metrics,client-id=*",
                "attr": [],
                "resultAlias": "monitor-producer-metrics;client-id",
                "outputWriters": [{
                    "@class": "com.googlecode.jmxtrans.model.output.InfluxDbWriterFactory",
                    "url": "http://127.0.0.1:8086/",
                    "username": "root",
                    "password": "root",
                    "database": "monitor",
                    "typeNames": ["client-id"]
                }]
            },
            {
                "obj": "kafka.producer:type=producer-node-metrics,client-id=*,node-id=*",
                "attr": ["incoming-byte-rate","outgoing-byte-rate","request-latency-avg","request-rate","request-size-avg","response-rate"],
                "resultAlias": "monitor-producer-node-metrics;client-id,node-id",
                "outputWriters": [{
                    "@class": "com.googlecode.jmxtrans.model.output.InfluxDbWriterFactory",
                    "url": "http://127.0.0.1:8086/",
                    "username": "root",
                    "password": "root",
                    "database": "monitor",
                    "typeNames": ["client-id","node-id"]
                }]
            },
            {
                "obj": "kafka.producer:type=producer-topic-metrics,client-id=*,topic=*",
                "attr": [],
                "resultAlias": "monitor-producer-topic-metrics;client-id,topic",
                "outputWriters": [{
                    "@class": "com.googlecode.jmxtrans.model.output.InfluxDbWriterFactory",
                    "url": "http://127.0.0.1:8086/",
                    "username": "root",
                    "password": "root",
                    "database": "monitor",
                    "typeNames": ["client-id","topic"]
                }]
            },
            {
                "obj": "kmf.services:type=consume-service,name=single-cluster-monitor",
                "attr": [],
                "resultAlias": "monitor-consume-service.single-cluster-monitor",
                "outputWriters": [{
                    "@class": "com.googlecode.jmxtrans.model.output.InfluxDbWriterFactory",
                    "url": "http://127.0.0.1:8086/",
                    "username": "root",
                    "password": "root",
                    "database": "monitor"
                }]
            },
            {
                "obj": "kmf.services:type=produce-service,name=single-cluster-monitor",
                "attr": [],
                "resultAlias": "monitor-produce-service.single-cluster-monitor",
                "outputWriters": [{
                    "@class": "com.googlecode.jmxtrans.model.output.InfluxDbWriterFactory",
                    "url": "http://127.0.0.1:8086/",
                    "username": "root",
                    "password": "root",
                    "database": "monitor"
                }]
            }
        ]
    }]
}
</code>```

Body:
After experiments with different software, kafka-monitor showed to fit best for my case.

It creates topic with partitions over whole cluster and provides metrics about production and consumption like message loss, duplication and end-to-end lag.

Start kafka-monitor like so:

cd <path_to_kafka_monitor>
export JMX_PORT=<some_port>
./bin/kafka-monitor-start.sh config/kafka-monitor.properties

Metrics are collected with jmxTrans. Query used:

{
    "servers": [{
        "port": "9999",
        "host": "127.0.0.1",
        "queries": [{
                "obj": "kafka.consumer:type=consumer-coordinator-metrics,client-id=*",
                "attr": ["assigned-partitions","commit-latency-avg","commit-rate","heartbeat-rate","heartbeat-response-time-max",
                        "join-rate","join-time-avg","join-time-max","last-heartbeat-seconds-ago","sync-rate","sync-time-avg","sync-time-max"],
                "resultAlias": "monitor-consumer.consumer-coordinator-metrics;client-id",
                "outputWriters": [{
                    "@class": "com.googlecode.jmxtrans.model.output.InfluxDbWriterFactory",
                    "url": "http://127.0.0.1:8086/",
                    "username": "root",
                    "password": "root",
                    "database": "monitor",
                    "typeNames": ["client-id"]
                }]
            },
            {
                "obj": "kafka.consumer:type=consumer-fetch-manager-metrics,client-id=*",
                "attr": ["bytes-consumed-rate","fetch-latency-avg","fetch-latency-max","records-consumed-rate","records-lag-max",
                        "records-per-request-avg"],
                "resultAlias": "monitor-consumer.consumer-fetch-manager-metrics,client-id",
                "outputWriters": [{
                    "@class": "com.googlecode.jmxtrans.model.output.InfluxDbWriterFactory",
                    "url": "http://127.0.0.1:8086/",
                    "username": "root",
                    "password": "root",
                    "database": "monitor",
                    "typeNames": ["client-id"]
                }]
            },
            {
                "obj": "kafka.consumer:type=consumer-fetch-manager-metrics,client-id=*,topic=*",
                "attr": ["bytes-consumed-rate","fetch-size-avg","fetch-size-max","records-consumed-rate","records-per-request-avg"],
                "resultAlias": "monitor-consumer-fetch-manager-metrics;client-id,topic",
                "outputWriters": [{
                    "@class": "com.googlecode.jmxtrans.model.output.InfluxDbWriterFactory",
                    "url": "http://127.0.0.1:8086/",
                    "username": "root",
                    "password": "root",
                    "database": "monitor",
                    "typeNames": ["client-id","topic"]
                }]
            },
            {
                "obj": "kafka.consumer:type=consumer-metrics,client-id=*",
                "attr": [],
                "resultAlias": "monitor-consumer-metrics;client-id",
                "outputWriters": [{
                    "@class": "com.googlecode.jmxtrans.model.output.InfluxDbWriterFactory",
                    "url": "http://127.0.0.1:8086/",
                    "username": "root",
                    "password": "root",
                    "database": "monitor",
                    "typeNames": ["client-id"]
                }]
            },
            {
                "obj": "kafka.consumer:type=consumer-node-metrics,client-id=*,node-id=*",
                "attr": ["incoming-byte-rate","outgoing-byte-rate","request-latency-avg","request-rate","request-size-avg","response-rate"],
                "resultAlias": "monitor-consumer-node-metrics;client-id,node-id",
                "outputWriters": [{
                    "@class": "com.googlecode.jmxtrans.model.output.InfluxDbWriterFactory",
                    "url": "http://127.0.0.1:8086/",
                    "username": "root",
                    "password": "root",
                    "database": "monitor",
                    "typeNames": ["client-id","node-id"]
                }]
            },
            {
                "obj": "kafka.producer:type=producer-metrics,client-id=*",
                "attr": [],
                "resultAlias": "monitor-producer-metrics;client-id",
                "outputWriters": [{
                    "@class": "com.googlecode.jmxtrans.model.output.InfluxDbWriterFactory",
                    "url": "http://127.0.0.1:8086/",
                    "username": "root",
                    "password": "root",
                    "database": "monitor",
                    "typeNames": ["client-id"]
                }]
            },
            {
                "obj": "kafka.producer:type=producer-node-metrics,client-id=*,node-id=*",
                "attr": ["incoming-byte-rate","outgoing-byte-rate","request-latency-avg","request-rate","request-size-avg","response-rate"],
                "resultAlias": "monitor-producer-node-metrics;client-id,node-id",
                "outputWriters": [{
                    "@class": "com.googlecode.jmxtrans.model.output.InfluxDbWriterFactory",
                    "url": "http://127.0.0.1:8086/",
                    "username": "root",
                    "password": "root",
                    "database": "monitor",
                    "typeNames": ["client-id","node-id"]
                }]
            },
            {
                "obj": "kafka.producer:type=producer-topic-metrics,client-id=*,topic=*",
                "attr": [],
                "resultAlias": "monitor-producer-topic-metrics;client-id,topic",
                "outputWriters": [{
                    "@class": "com.googlecode.jmxtrans.model.output.InfluxDbWriterFactory",
                    "url": "http://127.0.0.1:8086/",
                    "username": "root",
                    "password": "root",
                    "database": "monitor",
                    "typeNames": ["client-id","topic"]
                }]
            },
            {
                "obj": "kmf.services:type=consume-service,name=single-cluster-monitor",
                "attr": [],
                "resultAlias": "monitor-consume-service.single-cluster-monitor",
                "outputWriters": [{
                    "@class": "com.googlecode.jmxtrans.model.output.InfluxDbWriterFactory",
                    "url": "http://127.0.0.1:8086/",
                    "username": "root",
                    "password": "root",
                    "database": "monitor"
                }]
            },
            {
                "obj": "kmf.services:type=produce-service,name=single-cluster-monitor",
                "attr": [],
                "resultAlias": "monitor-produce-service.single-cluster-monitor",
                "outputWriters": [{
                    "@class": "com.googlecode.jmxtrans.model.output.InfluxDbWriterFactory",
                    "url": "http://127.0.0.1:8086/",
                    "username": "root",
                    "password": "root",
                    "database": "monitor"
                }]
            }
        ]
    }]
}


来源: stackexchange

问:
How to sort dates of string?
I have an array of date as 2017-07-06,2017-06-07,2017-07-07. I want to sort these dates in ascending order. So 2017-06-07 will come first. But it is not happening at all. I am using below code for this:

```<code>func sortDates(array:NSMutableArray)->[String]  {

        var strArray:[String] = []
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"// yyyy-MM-dd"
        var convertedArray: [Date] = []
        for dat in array {
            let date = dateFormatter.date(from: dat as! String)
            convertedArray.append(date!)
        }
        let arrDates = convertedArray.sorted(by: { $0.compare($1) == .orderedAscending })
        for value in arrDates {
            let formatter = DateFormatter()
            // initially set the format based on your datepicker date
            formatter.dateFormat = "yyyy-MM-dd"
            let myString = formatter.string(from: value)
            // convert your string to date
            let yourDate = formatter.date(from: myString)
            if yourDate != nil {
                //then again set the date format whhich type of output you need
                formatter.dateFormat = "yyyy-MM-dd"
                // again convert your date to string
                let myStringafd = formatter.string(from: yourDate!)
                strArray.append(myStringafd)
            }
        }
        return strArray
    }
</code>```

Please guide me where I am doing wrong ?

答:
Here is mine code:

```<code>   let arrCurrentDate = [“2017-07-06”, “2017-06-07", “2017-07-07”]
   var arrConverted: [Date] = []

   let dateFrmt = DateFormatter()
   dateFrmt.dateFormat = “yyyy-MM-dd”

   for dateCurrent in arrCurrentDate {
     let date = dateFrmt.date(from: dateCurrent)
     arrConverted.append(date!)
   }
   arrConverted.sort(by: {$0.compare($1) == .orderedAscending})
   arrConverted.sorted(by: {$0.timeIntervalSince1970 < $1.timeIntervalSince1970})

   print(arrConverted)
</code>```

You can change your order also:

.orderedAscending
.orderedSame
.orderedDescending

ContentLicense: CC BY-SA 3.0

Title: How to sort dates of string?

Body:
I have an array of date as 2017-07-06,2017-06-07,2017-07-07. I want to sort these dates in ascending order. So 2017-06-07 will come first. But it is not happening at all. I am using below code for this:

func sortDates(array:NSMutableArray)->[String]  {

        var strArray:[String] = []
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"// yyyy-MM-dd"
        var convertedArray: [Date] = []
        for dat in array {
            let date = dateFormatter.date(from: dat as! String)
            convertedArray.append(date!)
        }
        let arrDates = convertedArray.sorted(by: { $0.compare($1) == .orderedAscending })
        for value in arrDates {
            let formatter = DateFormatter()
            // initially set the format based on your datepicker date
            formatter.dateFormat = "yyyy-MM-dd"
            let myString = formatter.string(from: value)
            // convert your string to date
            let yourDate = formatter.date(from: myString)
            if yourDate != nil {
                //then again set the date format whhich type of output you need
                formatter.dateFormat = "yyyy-MM-dd"
                // again convert your date to string
                let myStringafd = formatter.string(from: yourDate!)
                strArray.append(myStringafd)
            }
        }
        return strArray
    }

Please guide me where I am doing wrong ?

Body:
Here is mine code:

   let arrCurrentDate = [“2017-07-06”, “2017-06-07", “2017-07-07”]
   var arrConverted: [Date] = []

   let dateFrmt = DateFormatter()
   dateFrmt.dateFormat = “yyyy-MM-dd”

   for dateCurrent in arrCurrentDate {
     let date = dateFrmt.date(from: dateCurrent)
     arrConverted.append(date!)
   }
   arrConverted.sort(by: {$0.compare($1) == .orderedAscending})
   arrConverted.sorted(by: {$0.timeIntervalSince1970 < $1.timeIntervalSince1970})

   print(arrConverted)

You can change your order also:

.orderedAscending
.orderedSame
.orderedDescending


问:
Store user authorized in react
I'm looking for a way, when a user authorized, I store user authorized status so every time I can check if the user is authorized or not. However, when I execute the following code user is not authorized: (Master.jsx -> render())

```<code><Route exact path="/" render={() => {
  console.log('this.props.authed: ', this.props.authed, "this.props: ", this.props)
  return (
  this.props.authed
  ? <Home />
  : <Redirect from="/" to="/login"/>
)}
}/>
</code>```

I check user authorization via firebase in componentWillMount() and store it the following code:(Master.jsx -> componentWillMount())

```<code>componentWillMount = () => {

  firebaseAuth().onAuthStateChanged((user) => {

        if (user) {
        this.props.login(user)
        } else {
         this.props.logout()
        }
      })
}
</code>```

The problem is that will componentWillMount will be executed after <Route .. so the user will be authorized after routing. I there any way to fix it?

答:
This is a classic use case of react-redux. I would recommend all the authentications to be handled at the server side where server responds with true or false for authorized or unauthorized user. Until this happens you can show a loading icon on the UI.

But, incase you want to go ahead and want to authenticate user on the UI, look into react-redux.

Essentially you will have to do this

When user logs in

Dispatch a logIn action in your action.js

Catch the logIn action in your reduce.js and store the user credentials in the store

When user reloads/ opens the page

Dispatch a isLoggedIn action in your action.js

Reduce isLoggedIn action and check if the user already exits in the state. If yes, return allow the program to proceed. If no, ask user to log in again.

Hope that helps!

Title: Store user authorized in react

Body:
I'm looking for a way, when a user authorized, I store user authorized status so every time I can check if the user is authorized or not. However, when I execute the following code user is not authorized: (Master.jsx -> render())

<Route exact path="/" render={() => {
  console.log('this.props.authed: ', this.props.authed, "this.props: ", this.props)
  return (
  this.props.authed
  ? <Home />
  : <Redirect from="/" to="/login"/>
)}
}/>

I check user authorization via firebase in componentWillMount() and store it the following code:(Master.jsx -> componentWillMount())

componentWillMount = () => {

  firebaseAuth().onAuthStateChanged((user) => {

        if (user) {
        this.props.login(user)
        } else {
         this.props.logout()
        }
      })
}

The problem is that will componentWillMount will be executed after <Route .. so the user will be authorized after routing. I there any way to fix it?


问:
How to view DLL functions?
I have a DLL file. How can I view the functions in that DLL?</p>

答: Use the free DLL Export Viewer, it is very easy to use.</p>

Title: How to view DLL functions?


问:
Changing the format of mysql table using mysql query
I have the following table in mysql database

i want to get the result in the following format

答:
This is a typical table pivot issue, try following:</p>

```<code>select
    customerName,
    coalesce(max(case when month(`date`) = 1 then paidamount end), '-') as `January` ,
    coalesce(max(case when month(`date`) = 2 then paidamount end), '-') as `February`,
    coalesce(max(case when month(`date`) = 3 then paidamount end), '-') as `March`,
    coalesce(max(case when month(`date`) = 4 then paidamount end), '-') as `April`,
    coalesce(max(case when month(`date`) = 5 then paidamount end), '-') as `May`,
    coalesce(max(case when month(`date`) = 6 then paidamount end), '-') as `June`,
    coalesce(max(case when month(`date`) = 7 then paidamount end), '-') as `July`,
    coalesce(max(case when month(`date`) = 8 then paidamount end), '-') as `August`,
    coalesce(max(case when month(`date`) = 9 then paidamount end), '-') as `September`,
    coalesce(max(case when month(`date`) = 10 then paidamount end), '-') as `October`,
    coalesce(max(case when month(`date`) = 11 then paidamount end), '-') as `November`,
    coalesce(max(case when month(`date`) = 12 then paidamount end), '-') as `December`
from yourtable
group by customerName
</code>```

Body:
This is a typical table pivot issue, try following:

select
    customerName,
    coalesce(max(case when month(`date`) = 1 then paidamount end), '-') as `January` ,
    coalesce(max(case when month(`date`) = 2 then paidamount end), '-') as `February`,
    coalesce(max(case when month(`date`) = 3 then paidamount end), '-') as `March`,
    coalesce(max(case when month(`date`) = 4 then paidamount end), '-') as `April`,
    coalesce(max(case when month(`date`) = 5 then paidamount end), '-') as `May`,
    coalesce(max(case when month(`date`) = 6 then paidamount end), '-') as `June`,
    coalesce(max(case when month(`date`) = 7 then paidamount end), '-') as `July`,
    coalesce(max(case when month(`date`) = 8 then paidamount end), '-') as `August`,
    coalesce(max(case when month(`date`) = 9 then paidamount end), '-') as `September`,
    coalesce(max(case when month(`date`) = 10 then paidamount end), '-') as `October`,
    coalesce(max(case when month(`date`) = 11 then paidamount end), '-') as `November`,
    coalesce(max(case when month(`date`) = 12 then paidamount end), '-') as `December`
from yourtable
group by customerName


问:
How to connect to postgresql locally with node.js on Ubuntu 16.04?
Soo I am using Digitalocean droplet and used this tutorial https://www.digitalocean.com/community/tutorials/how-to-install-and-use-postgresql-on-ubuntu-16-04 to set it up. The postgres works on the machine when I connect using my user.

When I try to connect to the postgres database using node.js it doesn't work.

```<code>var pg = require('pg');
var conString = "postgres://myuser:password@localhost:5432/dbname";

var client = new pg.Client(conString);
client.connect();
</code>```

When I look at the node.js error logs it says that

```<code>error: password authentication failed for user "myuser"
    at Connection.parseE (/usr/lib/node_modules/pg/lib/connection.js:572:11)
    at Connection.parseMessage (/usr/lib/node_modules/pg/lib/connection.js:396:$
    at Socket.<anonymous> (/usr/lib/node_modules/pg/lib/connection.js:132:22)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at readableAddChunk (_stream_readable.js:176:18)
    at Socket.Readable.push (_stream_readable.js:134:10)
    at TCP.onread (net.js:547:20)
</code>```

I'm not sure what password it is meaning. The only password I have entered is the one I used to create myuser on Ubuntu just like the tutorial instructed. I'm sure that the password matches the one I entered for myuser. I also tried to leave it blank but that's not working either.

But I assume the connection works, and only the authentication fails? Is there some default password for new postgres databases?

答:
Okay I found a way

```<code>$ sudo -u myuser psql myuser
postgres=# \password myuser
</code>```

Then it asked for my password I entered the same password as in the connection string and now it works, weird.

Body:
Soo I am using Digitalocean droplet and used this tutorial https://www.digitalocean.com/community/tutorials/how-to-install-and-use-postgresql-on-ubuntu-16-04 to set it up. The postgres works on the machine when I connect using my user.

When I try to connect to the postgres database using node.js it doesn't work.

var pg = require('pg');
var conString = "postgres://myuser:password@localhost:5432/dbname";

var client = new pg.Client(conString);
client.connect();

When I look at the node.js error logs it says that

error: password authentication failed for user "myuser"
    at Connection.parseE (/usr/lib/node_modules/pg/lib/connection.js:572:11)
    at Connection.parseMessage (/usr/lib/node_modules/pg/lib/connection.js:396:$
    at Socket.<anonymous> (/usr/lib/node_modules/pg/lib/connection.js:132:22)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at readableAddChunk (_stream_readable.js:176:18)
    at Socket.Readable.push (_stream_readable.js:134:10)
    at TCP.onread (net.js:547:20)

I'm not sure what password it is meaning. The only password I have entered is the one I used to create myuser on Ubuntu just like the tutorial instructed. I'm sure that the password matches the one I entered for myuser. I also tried to leave it blank but that's not working either.

But I assume the connection works, and only the authentication fails? Is there some default password for new postgres databases?

Body:
Okay I found a way

$ sudo -u myuser psql myuser
postgres=# \password myuser

Then it asked for my password I entered the same password as in the connection string and now it works, weird.


问:
ArrayList Limit to hold 10 Values
I am using an ArrayList within my code which gets populated by a EditText field but I am wanting to limit the ArrayList so it can only hold 10 values. After 10 values have been added if another tries to get added I just need it to not add into the Array. Anyone got any ideas how to do that?

```<code>private static ArrayList<String> playerList = new ArrayList<String>();
</code>```

答:
ArrayList doesn't have a way of limiting the size; you could extend it to include a limit:

```<code>public class FixedSizeLimitedArrayList extends ArrayList<Object> {
  @Override
  public boolean add(Object o) {

      int n=10;
      if (this.size() < n) {
          return super.add(o);
      }
      return false;
  }
}
</code>```

Other options include:

Use an array, which is limited.

Modify the code that uses the list to enforce the limit (e.g. ArrayList Limit to hold 10 Values)

Find a list implementation that has a limit (some examples listed here): Any way to set max size of a collection?

Title: ArrayList Limit to hold 10 Values

Body:
I am using an ArrayList within my code which gets populated by a EditText field but I am wanting to limit the ArrayList so it can only hold 10 values. After 10 values have been added if another tries to get added I just need it to not add into the Array. Anyone got any ideas how to do that?

private static ArrayList<String> playerList = new ArrayList<String>();

Body:
ArrayList doesn't have a way of limiting the size; you could extend it to include a limit:

public class FixedSizeLimitedArrayList extends ArrayList<Object> {
  @Override
  public boolean add(Object o) {

      int n=10;
      if (this.size() < n) {
          return super.add(o);
      }
      return false;
  }
}

Other options include:

Use an array, which is limited.

Modify the code that uses the list to enforce the limit (e.g. ArrayList Limit to hold 10 Values)

Find a list implementation that has a limit (some examples listed here): Any way to set max size of a collection?


问:
Searching for something in Database - SELECT - Need to search in 2 tables

As you can see in the print screen above, I am wondering, if it is possible to check if there is one thing in two tables at once. Without making 2 queries. I need to look, if "fajne-to-jest" is in table1 or table2. I'm doing it in 2 queries... but question is, is it possible to check this information using one query? Mabye something else? Most efficent way? The best way?

答:
You can use exists in the select:

```<code>select (exists (select 1 from table1 where url = 'fajne-to-jest')) as in_table1,
       (exists (select 1 from table2 where url = 'fajne-to-jest')) as in_table2;
</code>```

Body:
You can use exists in the select:

select (exists (select 1 from table1 where url = 'fajne-to-jest')) as in_table1,
       (exists (select 1 from table2 where url = 'fajne-to-jest')) as in_table2;


问:
Validate prefilled jQuery form (invalidate on first field clear, ASP.NET and unobtrustive)
I have a form that can be filled, saved, loaded and re-edited.

When it is loaded and re-edited, it probably begins its life valid. When a field is valid upon load, I want it to invalidate immediately when it is edited contrary to rules. That's my question in a nutshell, and I suspect this is supported by some configuration option I can't find.

Currently, it works properly (the way desired above) only after: 1) it is edited, 2) then the field loses focus while valid, 3) then is edited it again. So it takes an extra valid loss of focus to visualize errors for a pre-filled form.

If it is empty on load (such as the first visit) it should not show errors.

I'm using the following already in my framework:

jQuery.validate (the 'approved' one, and the focus of my question)

jQuery unobtrusive validation adapter for ASP.NET MVC 3

I don't currently run any custom code to activate this, since the 'unobtrusive' adapter initializes validation (but I'd be happy to, to fix this). I've tried adding 'form.valid()' on page load, but it doesn't fix the above and in fact breaks more stuff.

Thanks,
Shannon

答:
This constructor works for me:</p>

```<code>$('form').validate({
    onfocusout: function(element) {
       this.element(element);
    }, ...
});
</code>```

Body:
This constructor works for me:

$('form').validate({
    onfocusout: function(element) {
       this.element(element);
    }, ...
});


问:
Sending value of rows to webservice in JSON format (Android)
Rating Activity

Task: Application is receiving values in JSON format and Student Name and Current rating are populated dynamically in the List View. Now, application need to send rating and comments for individual student in JSON format.
Problem: The values given in Rating and comment can be retrieved in Adapter class(where a single row is populated) but cannot be accessed outside this class. I want to access these values within ListView.onClickListener method.

This is Adapter class:

```<code>class StudentAdapter extends BaseAdapter {

    ArrayList<Student> studentList;
    ArrayList<Student> studentList1;
    LayoutInflater inflater;

    public StudentAdapter(ArrayList<Student> studentList) {
        this.studentList = studentList;
        inflater = LayoutInflater.from(RatingActivity.this);
    }

    @Override
    public int getCount() {
        return studentList.size();
    }

    @Override
    public Object getItem(int position) {
        return studentList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent)
    {
        final View row = inflater.inflate(R.layout.rowactivity3, parent, false);
        //  TextView id = (TextView) row.findViewById(R.id.tvId);
        TextView name = (TextView) row.findViewById(R.id.tvName);
        final RatingBar rv=(RatingBar)row.findViewById(R.id.ratingBar);
        final RatingBar rv1=(RatingBar)row.findViewById(R.id.ratingBar1);
        final Button b1=(Button)row.findViewById(R.id.btnDialog);
        final String[] values = {null,null};
        name.setText(studentList.get(position).getSname());
        rv1.setRating(studentList.get(position).getRate());
        b1.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(RatingActivity.this);
                builder.setTitle("Comment here:");

                final EditText input = new EditText(RatingActivity.this);
                input.setInputType(InputType.TYPE_CLASS_TEXT |InputType.TYPE_CLASS_TEXT);
                builder.setView(input);

                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        m_Text = input.getText().toString();
                        Log.d("comment",m_Text);
                        values[0]=m_Text;
                        b1.setBackgroundColor(Color.BLUE);
                    }
                });
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                builder.show();
            }
        });
        return row;
    }
}
</code>```

This is layout of single row:

```<code><TextView
    android:layout_margin="8dp"
    android:id="@+id/tvName"
    android:text="enter name.."
    android:padding="12dp"
    android:layout_width="220dp"
    android:layout_height="wrap_content"
    android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"/>
<RatingBar
    android:id="@+id/ratingBar"
    style="@style/customRatingBar"
    android:layout_marginLeft="15dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:numStars="5"
    android:stepSize="0.1" />
<Button
    android:id="@+id/btnDialog"
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="70dp"
    android:text="Click"/>
<RatingBar
    android:id="@+id/ratingBar1"
    android:layout_marginLeft="80dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:numStars="5"
    android:isIndicator="true"
    android:stepSize="0.1" />
</code>```

答:
Try this:

Create interface

```<code>public interface AdapterItemClickListener {
   void AdapterItemClicked(int position, Bundle data);
}
</code>```

Then add code in your adapter class:

```<code>class StudentAdapter extends BaseAdapter {

ArrayList<Student> studentList;
ArrayList<Student> studentList1;
LayoutInflater inflater;
AdapterItemClickListener adapterItemClickListener;

public StudentAdapter(ArrayList<Student> studentList) {
this.studentList = studentList;
inflater = LayoutInflater.from(RatingActivity.this);
}

@Override
public int getCount() {
return studentList.size();
}

@Override
public Object getItem(int position) {
return studentList.get(position);
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(final int position, View convertView,     ViewGroup parent)
{
final View row = inflater.inflate(R.layout.rowactivity3, parent, false);
//  TextView id = (TextView) row.findViewById(R.id.tvId);
TextView name = (TextView) row.findViewById(R.id.tvName);
final RatingBar rv=(RatingBar)row.findViewById(R.id.ratingBar);
final RatingBar rv1=(RatingBar)row.findViewById(R.id.ratingBar1);
final Button b1=(Button)row.findViewById(R.id.btnDialog);
final String[] values = {null,null};
name.setText(studentList.get(position).getSname());
rv1.setRating(studentList.get(position).getRate());
b1.setOnClickListener(new View.OnClickListener()
{
    @Override
    public void onClick(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(RatingActivity.this);
        builder.setTitle("Comment here:");

        final EditText input = new EditText(RatingActivity.this);
        input.setInputType(InputType.TYPE_CLASS_TEXT |InputType.TYPE_CLASS_TEXT);
        builder.setView(input);

        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                m_Text = input.getText().toString();
                Log.d("comment",m_Text);
                values[0]=m_Text;
                b1.setBackgroundColor(Color.BLUE);
         //pass your data in bundle and pass adapter position
     adapterItemClickListener.AdapterItemClicked(position,bundle);
     dialog.cancel();
            }
        });
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.show();
    }
});
return row;
}

// create adapter item click listener and call from fragment or activity class
public void setAdapterItemClickListener(AdapterItemClickListener adapterItemClickListener){
    this.adapterItemClickListener=adapterItemClickListener;
 }

}
</code>```

Then call studentAdapter.setAdapterItemClickListener(this) from fragment or activity and override  void AdapterItemClicked(int position, Bundle data); . You get data in bundle in this method.

Note: This code not tested. So if you face any problem then debug and check. I hope this will work.

Body:
Rating Activity

Task: Application is receiving values in JSON format and Student Name and Current rating are populated dynamically in the List View. Now, application need to send rating and comments for individual student in JSON format.
Problem: The values given in Rating and comment can be retrieved in Adapter class(where a single row is populated) but cannot be accessed outside this class. I want to access these values within ListView.onClickListener method.

This is Adapter class:

class StudentAdapter extends BaseAdapter {

    ArrayList<Student> studentList;
    ArrayList<Student> studentList1;
    LayoutInflater inflater;

    public StudentAdapter(ArrayList<Student> studentList) {
        this.studentList = studentList;
        inflater = LayoutInflater.from(RatingActivity.this);
    }

    @Override
    public int getCount() {
        return studentList.size();
    }

    @Override
    public Object getItem(int position) {
        return studentList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent)
    {
        final View row = inflater.inflate(R.layout.rowactivity3, parent, false);
        //  TextView id = (TextView) row.findViewById(R.id.tvId);
        TextView name = (TextView) row.findViewById(R.id.tvName);
        final RatingBar rv=(RatingBar)row.findViewById(R.id.ratingBar);
        final RatingBar rv1=(RatingBar)row.findViewById(R.id.ratingBar1);
        final Button b1=(Button)row.findViewById(R.id.btnDialog);
        final String[] values = {null,null};
        name.setText(studentList.get(position).getSname());
        rv1.setRating(studentList.get(position).getRate());
        b1.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(RatingActivity.this);
                builder.setTitle("Comment here:");

                final EditText input = new EditText(RatingActivity.this);
                input.setInputType(InputType.TYPE_CLASS_TEXT |InputType.TYPE_CLASS_TEXT);
                builder.setView(input);

                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        m_Text = input.getText().toString();
                        Log.d("comment",m_Text);
                        values[0]=m_Text;
                        b1.setBackgroundColor(Color.BLUE);
                    }
                });
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                builder.show();
            }
        });
        return row;
    }
}

This is layout of single row:

<TextView
    android:layout_margin="8dp"
    android:id="@+id/tvName"
    android:text="enter name.."
    android:padding="12dp"
    android:layout_width="220dp"
    android:layout_height="wrap_content"
    android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"/>
<RatingBar
    android:id="@+id/ratingBar"
    style="@style/customRatingBar"
    android:layout_marginLeft="15dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:numStars="5"
    android:stepSize="0.1" />
<Button
    android:id="@+id/btnDialog"
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="70dp"
    android:text="Click"/>
<RatingBar
    android:id="@+id/ratingBar1"
    android:layout_marginLeft="80dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:numStars="5"
    android:isIndicator="true"
    android:stepSize="0.1" />

Body:
Try this:

Create interface

public interface AdapterItemClickListener {
   void AdapterItemClicked(int position, Bundle data);
}

Then add code in your adapter class:

class StudentAdapter extends BaseAdapter {

ArrayList<Student> studentList;
ArrayList<Student> studentList1;
LayoutInflater inflater;
AdapterItemClickListener adapterItemClickListener;

public StudentAdapter(ArrayList<Student> studentList) {
this.studentList = studentList;
inflater = LayoutInflater.from(RatingActivity.this);
}

@Override
public int getCount() {
return studentList.size();
}

@Override
public Object getItem(int position) {
return studentList.get(position);
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(final int position, View convertView,     ViewGroup parent)
{
final View row = inflater.inflate(R.layout.rowactivity3, parent, false);
//  TextView id = (TextView) row.findViewById(R.id.tvId);
TextView name = (TextView) row.findViewById(R.id.tvName);
final RatingBar rv=(RatingBar)row.findViewById(R.id.ratingBar);
final RatingBar rv1=(RatingBar)row.findViewById(R.id.ratingBar1);
final Button b1=(Button)row.findViewById(R.id.btnDialog);
final String[] values = {null,null};
name.setText(studentList.get(position).getSname());
rv1.setRating(studentList.get(position).getRate());
b1.setOnClickListener(new View.OnClickListener()
{
    @Override
    public void onClick(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(RatingActivity.this);
        builder.setTitle("Comment here:");

        final EditText input = new EditText(RatingActivity.this);
        input.setInputType(InputType.TYPE_CLASS_TEXT |InputType.TYPE_CLASS_TEXT);
        builder.setView(input);

        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                m_Text = input.getText().toString();
                Log.d("comment",m_Text);
                values[0]=m_Text;
                b1.setBackgroundColor(Color.BLUE);
         //pass your data in bundle and pass adapter position
     adapterItemClickListener.AdapterItemClicked(position,bundle);
     dialog.cancel();
            }
        });
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.show();
    }
});
return row;
}

// create adapter item click listener and call from fragment or activity class
public void setAdapterItemClickListener(AdapterItemClickListener adapterItemClickListener){
    this.adapterItemClickListener=adapterItemClickListener;
 }

}

Then call studentAdapter.setAdapterItemClickListener(this) from fragment or activity and override  void AdapterItemClicked(int position, Bundle data); . You get data in bundle in this method.

Note: This code not tested. So if you face any problem then debug and check. I hope this will work.


问:
Hidden Features of ASP.NET

This question exists because it has
  historical significance, but it is not
  considered a good, on-topic question
  for this site, so please do not use it
  as evidence that you can ask similar
   questions here.

More info: https://stackoverflow.com/faq

There are always features that would be useful in fringe scenarios, but for that very reason most people don't know them. I am asking for features that are not typically taught by the text books.

What are the ones that you know?

答: Application variables can be used with web application for communicating across the whole application. It is initialized in Global.asax file and used over the pages in that web application by all the user independent of the session they create.</p>

OwnerDisplayName: Vaibhav

Title: Hidden Features of ASP.NET

LastEditorDisplayName: John Sheehan

ContentLicense: CC BY-SA 2.5


问:
Show div on checkbox tick
I know this question has been asked and I've tried a few different methods but can't seem to get this to work. I'm trying to insert a div to extend a form based on a checkbox being ticked. Nothing seems to work at the moment. It's probably something stupid, I'd appreciate the assistance:

https://jsfiddle.net/4ydybrdd/#&togetherjs=qG3ypyIQsa

html:

```<code>    <form method="post" autocomplete="off">
                <div class="row resetpword">
                    <div class="container-fluid addblog"style="margin-
    top:-40px;margin-bottom:20px;"><h2>Registration</h2></div>
                    <div class="container-fluid" style="margin-left:37px;">
                        <label>
                            First Name<span class="req">*</span>
                        </label>
                        <input type="text" required autocomplete="off"
    name="firstname" />
                    </div>
                    <div class="container-fluid" style="margin-left:35px;">
                        <label>
                            Last Name<span class="req">*</span>
                        </label>
                        <input type="text" required autocomplete="off"
    name="lastname" />
                    </div>
                </div>
                <div class="row resetpword" style="margin-top:0;">
                    <div class="container-fluid" style="margin-left:10px;">
                        <label>
                            Email Address<span class="req">*</span>
                        </label>
                        <input type="email" required autocomplete="off"
    name="email" />
                    </div>
                </div>
                <div class="row resetpword" style="margin-top:0;">
                    <div class="container-fluid">
                        <label>
                            Set A Password<span class="req">*</span>
                        </label>
                        <input type="password"required autocomplete="off"
    name="password"/>
                    </div>
                </div>
                <div class="container-fluid resetpword countrydropdown"
    style="margin-top:0;margin-left:-15px;">
                    <label>
                        Country of origin<span class="req">*</span>
                    </label>
                    <select>
                        <option value="AF">Afghanistan</option>
                        <option value="AX">Åland Islands</option>
                    </select>
                </div>
                <div class="container-fluid resetpword" style="margin-top:0;">
                    <label>
                        Are you a blogger?<span class="req">*</span>
                    </label>
                    <input type="checkbox" name="check1" id="blogger"/>
                </div>
                <div class="addblog"><p>sausage</p></div>
                <button type="submit" class="resetb button button-block"
    name="register">Register</button>
   </form>
</code>```

js:

```<code>jQuery("#blogger").click(function() {
if($(this).is(":checked")) {
    jQuery(".addblog").show(300);
}
else {
    jQuery(".addblog").hide(300);;
}
});
</code>```

答:
Post the  js code after document.ready and don't forget to add jquery  link

Updated fiddle

/*!
* can yo u solve my issue? :) I don't understand why it won't wor
 */
 $(document).ready(function(){
jQuery("#blogger").change(function() {
    if($(this).is(":checked")) {
        jQuery(".addblog").show(300);
    }
 else {
        jQuery(".addblog").hide(300);;
    }
});
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" autocomplete="off">
    <div class="row resetpword">
     <div class="container-fluid addblog"style="margin-top:-40px;margin-bottom:20px;"><h2>Registration</h2></div>
     <div class="container-fluid" style="margin-left:37px;">
      <label>
       First Name<span class="req">*</span>
      </label>
      <input type="text" required autocomplete="off" name="firstname" />
     </div>
     <div class="container-fluid" style="margin-left:35px;">
      <label>
       Last Name<span class="req">*</span>
      </label>
      <input type="text" required autocomplete="off" name="lastname" />
     </div>
    </div>
    <div class="row resetpword" style="margin-top:0;">
     <div class="container-fluid" style="margin-left:10px;">
      <label>
       Email Address<span class="req">*</span>
      </label>
      <input type="email" required autocomplete="off" name="email" />
     </div>
    </div>
    <div class="row resetpword" style="margin-top:0;">
     <div class="container-fluid">
      <label>
       Set A Password<span class="req">*</span>
      </label>
      <input type="password"required autocomplete="off" name="password"/>
     </div>
    </div>
    <div class="container-fluid resetpword countrydropdown" style="margin-top:0;margin-left:-15px;">
     <label>
      Country of origin<span class="req">*</span>
     </label>
     <select>
      <option value="AF">Afghanistan</option>
      <option value="AX">Åland Islands</option>
     </select>
    </div>
    <div class="container-fluid resetpword" style="margin-top:0;">
     <label>
      Are you a blogger?<span class="req">*</span>
     </label>
     <input type="checkbox" name="check1" id="blogger"/>
    </div>
    <div class="addblog"><p>sausage</p></div>
    <button type="submit" class="resetb button button-block" name="register">Register</button>
</form></code>```

Title: Show div on checkbox tick

Body:
I know this question has been asked and I've tried a few different methods but can't seem to get this to work. I'm trying to insert a div to extend a form based on a checkbox being ticked. Nothing seems to work at the moment. It's probably something stupid, I'd appreciate the assistance:

https://jsfiddle.net/4ydybrdd/#&togetherjs=qG3ypyIQsa

html:

    <form method="post" autocomplete="off">

Registration

                            First Name*

                        <input type="text" required autocomplete="off"
    name="firstname" />

                            Last Name*

                        <input type="text" required autocomplete="off"
    name="lastname" />

                            Email Address*

                        <input type="email" required autocomplete="off"
    name="email" />

                            Set A Password*

                        <input type="password"required autocomplete="off"
    name="password"/>

                        Country of origin*

                    <select>
                        <option value="AF">Afghanistan</option>
                        <option value="AX">Åland Islands</option>
                    </select>

                        Are you a blogger?*

                    <input type="checkbox" name="check1" id="blogger"/>

sausage

                <button type="submit" class="resetb button button-block"
    name="register">Register</button>
   </form>

js:

jQuery("#blogger").click(function() {
if($(this).is(":checked")) {
    jQuery(".addblog").show(300);
}
else {
    jQuery(".addblog").hide(300);;
}
});

Body:
Post the  js code after document.ready and don't forget to add jquery  link

Updated fiddle

/*!
* can yo u solve my issue? :) I don't understand why it won't wor
 */
 $(document).ready(function(){
jQuery("#blogger").change(function() {
    if($(this).is(":checked")) {
        jQuery(".addblog").show(300);
    }
 else {
        jQuery(".addblog").hide(300);;
    }
});
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" autocomplete="off">
    <div class="row resetpword">
     <div class="container-fluid addblog"style="margin-top:-40px;margin-bottom:20px;"><h2>Registration</h2></div>
     <div class="container-fluid" style="margin-left:37px;">
      <label>
       First Name<span class="req">*</span>
      </label>
      <input type="text" required autocomplete="off" name="firstname" />
     </div>
     <div class="container-fluid" style="margin-left:35px;">
      <label>
       Last Name<span class="req">*</span>
      </label>
      <input type="text" required autocomplete="off" name="lastname" />
     </div>
    </div>
    <div class="row resetpword" style="margin-top:0;">
     <div class="container-fluid" style="margin-left:10px;">
      <label>
       Email Address<span class="req">*</span>
      </label>
      <input type="email" required autocomplete="off" name="email" />
     </div>
    </div>
    <div class="row resetpword" style="margin-top:0;">
     <div class="container-fluid">
      <label>
       Set A Password<span class="req">*</span>
      </label>
      <input type="password"required autocomplete="off" name="password"/>
     </div>
    </div>
    <div class="container-fluid resetpword countrydropdown" style="margin-top:0;margin-left:-15px;">
     <label>
      Country of origin<span class="req">*</span>
     </label>
     <select>
      <option value="AF">Afghanistan</option>
      <option value="AX">Åland Islands</option>
     </select>
    </div>
    <div class="container-fluid resetpword" style="margin-top:0;">
     <label>
      Are you a blogger?<span class="req">*</span>
     </label>
     <input type="checkbox" name="check1" id="blogger"/>
    </div>
    <div class="addblog"><p>sausage</p></div>
    <button type="submit" class="resetb button button-block" name="register">Register</button>
</form>


问:
How do you change a column value after a certain time interval - Cassandra
I have a column family in Cassandra in which one of the column name is status with value  Y. This status has to be updated to a new value - X after 30 minutes if it wasn't updated to some other value say N within the 30 minutes.

Basically, I want to mark the column to Expired - X if there wasn't any update within the specified time interval.

Also, once this is expired, it needs to trigger off an event to notify another system(API) saying that it was expired.

答:
Agree with Ashraful's answer. If you use Spring Data for Apache Cassandra 2.0 (currently milestone), then you would use the following code to implements Ashraful's example:</p>

```<code>@Table("users")
public class User {

    @PrimaryKey("user_name")
    String userName;
    String password;
}

WriteOptions options = WriteOptions.builder().ttl(1800).build();

template.update(query(where("userName").is("cbrown")).queryOptions(options),
                update("password", "ch@ngem4a"),
                User.class);
</code>```

Body:
Agree with Ashraful's answer. If you use Spring Data for Apache Cassandra 2.0 (currently milestone), then you would use the following code to implements Ashraful's example:

@Table("users")
public class User {

    @PrimaryKey("user_name")
    String userName;
    String password;
}

WriteOptions options = WriteOptions.builder().ttl(1800).build();

template.update(query(where("userName").is("cbrown")).queryOptions(options),
                update("password", "ch@ngem4a"),
                User.class);


问:
PostgreSQL RETURNING fails with REGEXP_REPLACE
I'm running PostgreSQL 9.4 and are inserting a lot of records into my database. I use the RETURNING clause for further use after an insert.

When I simply run:

```<code>... RETURNING my_car, brand, color, contact
</code>```

everything works, but if I try to use REGEXP_REPLACE it fails:

```<code>... RETURNing my_car, brand, color, REGEXP_REPLACE(contact, '^(\+?|00)', '') AS contact
</code>```

it fails with:

```<code>ERROR: invalid regular expression: quantifier operand invalid
</code>```

If I simply run the query directly in PostgreSQL it does work and return a nice output.

答:
Tried to reproduce and failed:

```<code>t=# create table s1(t text);
CREATE TABLE
t=# insert into s1 values ('+4422848566') returning REGEXP_REPLACE(t, '^(\+?|00)', '');
 regexp_replace
----------------
 4422848566
(1 row)

INSERT 0 1
</code>```

So elaborated @pozs suggested reason:

```<code>set standard_conforming_strings to off;
</code>```

leads to

```<code>WARNING:  nonstandard use of escape in a string literal
LINE 1: ...alues ('+4422848566') returning REGEXP_REPLACE(t, '^(\+?|00)...
                                                             ^
HINT:  Use the escape string syntax for escapes, e.g., E'\r\n'.
ERROR:  invalid regular expression: quantifier operand invalid
</code>```

update
As OP author says standard_conforming_strings is on as supposed from 9.1 by default working with psql and is off working with pg-prommise

update from vitaly-t

The issue is simply with the JavaScript literal escaping, not with the
  flag.

He elaborates further in his answer

Body:
I'm running PostgreSQL 9.4 and are inserting a lot of records into my database. I use the RETURNING clause for further use after an insert.

When I simply run:

... RETURNING my_car, brand, color, contact

everything works, but if I try to use REGEXP_REPLACE it fails:

... RETURNing my_car, brand, color, REGEXP_REPLACE(contact, '^(\+?|00)', '') AS contact

it fails with:

ERROR: invalid regular expression: quantifier operand invalid

If I simply run the query directly in PostgreSQL it does work and return a nice output.

Body:
Tried to reproduce and failed:

t=# create table s1(t text);
CREATE TABLE
t=# insert into s1 values ('+4422848566') returning REGEXP_REPLACE(t, '^(\+?|00)', '');
 regexp_replace
----------------
 4422848566
(1 row)

INSERT 0 1

So elaborated @pozs suggested reason:

set standard_conforming_strings to off;

leads to

WARNING:  nonstandard use of escape in a string literal
LINE 1: ...alues ('+4422848566') returning REGEXP_REPLACE(t, '^(\+?|00)...
                                                             ^
HINT:  Use the escape string syntax for escapes, e.g., E'\r\n'.
ERROR:  invalid regular expression: quantifier operand invalid

update
As OP author says standard_conforming_strings is on as supposed from 9.1 by default working with psql and is off working with pg-prommise

update from vitaly-t

The issue is simply with the JavaScript literal escaping, not with the
  flag.

He elaborates further in his answer


问:
php db query to display certain user data (Smarty included)
I have managed to create a login form which GETS user data from database and displays user data, but i would now like to display the table_name to which that user is related to.

The thing is i will have to use an JOIN because it needs to query the data from 2 tables.

My Problem

I keep getting an error, im not sure if my query in my php file has the wrong syntax and if my method is just the wrong approach.

Connection

Keep in mind my database connections ($db) works perfectly as the user can already log in with username and password

Error

Notice: Undefined variable: rows in C:\xampp\htdocs\score4score\table.php on line 42

Database: tables

```<code>table: sc_tables
+------+----------+-------------+
| t_id | user_id  | table_name  |
+------+----------+-------------+
|  1   |     1    | bobs        |
+------+----------+-------------+

table: sc_scores
+------+----------+-------------+-------+
| s_id | user_id  |    t_id     | score |
+------+----------+-------------+-------+
|  1   |     1    |      1      |  50   |
+------+----------+-------------+-------+
</code>```

PHP

```<code><?php
   include("config.php");
   session_start();

   $userId = (isset($_GET["user_id"]) && is_numeric($_GET["user_id"]) && (int)$_GET["user_id"] > 0) ? (int)$_GET["user_id"] : 0;

   $query = "SELECT `a`.`table_name` FROM `sc_tables` AS `a` JOIN `sc_scores` AS `b` ON `a`.`t_id` = `b`.`t_id`";

   $result = mysqli_query($db, $query);

     $rows = array();

     while ($row = mysql_fetch_array($result)) {
     $rows[] = $row;
     }

   $smarty->assign('rows', $rows);
   include("header.php");
   $smarty->display('records.tpl');

 ?>
</code>```

TPL (records.tpl)

```<code><div>
 <div>
    The current rankings table:
    <table>

        {foreach from=$rows item="row"}
        <tr>
            <td>{$row.table_name}</td>
        </tr>
        {/foreach}

    </table>
 </div>
</div>
</code>```

It would be much appreciated if someone can just point me in the right direction. thanks

答:
There is no table_id field in the tables. So, you should have:

```<code>$query = "SELECT `a`.`table_name` FROM `sc_tables` AS `a` JOIN `sc_scores` AS `b` ON `a`.`t_id` = `b`.`t_id`";
</code>```

The error says that the value FALSE is passed as argument to mysql_fetch_array($result). E.g. your mysqli_query() returns FALSE, not a mysqli_result object, as it should.

If problem persists after upper changes, without seeing any error, then you should use also mysqli_errno(), mysqli_error()and mysqli_error_list().

Good luck!

Body:
I have managed to create a login form which GETS user data from database and displays user data, but i would now like to display the table_name to which that user is related to.

The thing is i will have to use an JOIN because it needs to query the data from 2 tables.

My Problem

I keep getting an error, im not sure if my query in my php file has the wrong syntax and if my method is just the wrong approach.

Connection

Keep in mind my database connections ($db) works perfectly as the user can already log in with username and password

Error

Notice: Undefined variable: rows in C:\xampp\htdocs\score4score\table.php on line 42

Database: tables

table: sc_tables
+------+----------+-------------+
| t_id | user_id  | table_name  |
+------+----------+-------------+
|  1   |     1    | bobs        |
+------+----------+-------------+

table: sc_scores
+------+----------+-------------+-------+
| s_id | user_id  |    t_id     | score |
+------+----------+-------------+-------+
|  1   |     1    |      1      |  50   |
+------+----------+-------------+-------+

PHP

<?php
   include("config.php");
   session_start();

   $userId = (isset($_GET["user_id"]) && is_numeric($_GET["user_id"]) && (int)$_GET["user_id"] > 0) ? (int)$_GET["user_id"] : 0;

   $query = "SELECT `a`.`table_name` FROM `sc_tables` AS `a` JOIN `sc_scores` AS `b` ON `a`.`t_id` = `b`.`t_id`";

   $result = mysqli_query($db, $query);

     $rows = array();

     while ($row = mysql_fetch_array($result)) {
     $rows[] = $row;
     }

   $smarty->assign('rows', $rows);
   include("header.php");
   $smarty->display('records.tpl');

 ?>

TPL (records.tpl)

    The current rankings table:

        {foreach from=$rows item="row"}

            {$row.table_name}

        {/foreach}

It would be much appreciated if someone can just point me in the right direction. thanks

Body:
There is no table_id field in the tables. So, you should have:

$query = "SELECT `a`.`table_name` FROM `sc_tables` AS `a` JOIN `sc_scores` AS `b` ON `a`.`t_id` = `b`.`t_id`";

The error says that the value FALSE is passed as argument to mysql_fetch_array($result). E.g. your mysqli_query() returns FALSE, not a mysqli_result object, as it should.

If problem persists after upper changes, without seeing any error, then you should use also mysqli_errno(), mysqli_error()and mysqli_error_list().

Good luck!


问:
How to stop Visual Studio 2013 automatic reformatting
How do I stop the following from happening in VS2013?  It doesn't happen in VS2008 - possibly from VS2010 onwards.  I type

```<code>int GetCount() const { return count
</code>```

And everything is OK.  When I type the ; it becomes

```<code>int GetCount() const {
    return count;
</code>```

And when I type the }, it becomes

```<code>int GetCount() const {
    return count;
}
</code>```

What I'd really, really want is

```<code>int GetCount() const { return count; }
</code>```

If I don't type in the ; and go back and insert it, it behaves as I would like it to, except that I have to remember to go back and insert the ;

I have looked at Tools -> Options -> Text Editior -> C/C++.  I haven't tried all the options but from the descriptions, I can't figure out what would stop this behaviour.

答:
These options are in

Text Editor >> C/C++ >> Formatting >> General

The one you want is

Automatically format statement when I type a ;

The particular formatting settings that are being applied when you  press ; are those set in Formatting >> New Lines.

Body:
How do I stop the following from happening in VS2013?  It doesn't happen in VS2008 - possibly from VS2010 onwards.  I type

int GetCount() const { return count

And everything is OK.  When I type the ; it becomes

int GetCount() const {
    return count;

And when I type the }, it becomes

int GetCount() const {
    return count;
}

What I'd really, really want is

int GetCount() const { return count; }

If I don't type in the ; and go back and insert it, it behaves as I would like it to, except that I have to remember to go back and insert the ;

I have looked at Tools -> Options -> Text Editior -> C/C++.  I haven't tried all the options but from the descriptions, I can't figure out what would stop this behaviour.


答: looking at your example it seems that your were missing the jquery library as well as some html changes</p>

Title: Show div on checkbox tick


问:
Finding orders made within any ISO week of a specific year using T-SQL
As part of a reporting setup, I have a SQL query fetching the number of orders placed each week:

```<code>select datepart(isowk, order_date), count(*)
from orders where year(order_date) = @Year
group by datepart(isowk, order_date), year(order_date)
order by 1
</code>```

Note that I am using the new isowk format in the datepart function call, as business in Denmark typically use ISO week numbers.

Running this query with @Year = 2010 yields a result set simialar to this:

```<code>1           5
2           7
3           10
...
53          3
</code>```

You and I both know that 2010 isn't over yet, and certainly there has been no week 53 yet. Actually, there has - the first three days of the year belonged to ISO week 53 of 2009. While it might be possible to explain this to other programmers, the people who are going to read my reports are never going to understand this. Hence, I want to get rid of this week 53, by "moving" the data over to 2009.

How can I rewrite my WHERE clause to filter the data set to orders made between monday of week 1 and friday of the last week (52 or 53) in the year defined as @Year?

答:
I am going to take a stab at this myself, using the approach described in my comments on Manfred's answer. The idea is to find the first day of the first ISO week of the specified year and the year after, allowing for index-enabled between filtering of the input records.

First, I create a function which will find the first day of the first ISO week  in a specific year:

```<code>create function firstIsoDay(@year int) returns datetime as begin
    declare @first datetime
    select @first = cast(cast(@year as char(4)) as datetime)
    select @first = dateadd(ww, datediff(ww, 0, @first), 0)
    if datepart(isowk, @first) > 1 set @first = @first + 7
    return @first
end
</code>```

Disclaimer: This function is untested (having no Sql Server 2008 available at the moment).

The actual data query can then be made using two invocations of this function in a between filter:

```<code>select datepart(isowk, order_date), count(*) from orders
where order_date between firstIsoDay(@Year) and firstIsoDay(@Year + 1)
group by datepart(isowk, order_date), year(order_date)
order by 1
</code>```

Remember that between is two-way inclusive. If the values in order_date contain truncated dates (no time), -1 should be added to the end of the where clause. In my use case, order_date has both date and time, so between two dates at midnight should do just fine.

Body:
As part of a reporting setup, I have a SQL query fetching the number of orders placed each week:

select datepart(isowk, order_date), count(*)
from orders where year(order_date) = @Year
group by datepart(isowk, order_date), year(order_date)
order by 1

Note that I am using the new isowk format in the datepart function call, as business in Denmark typically use ISO week numbers.

Running this query with @Year = 2010 yields a result set simialar to this:

1           5
2           7
3           10
...
53          3

You and I both know that 2010 isn't over yet, and certainly there has been no week 53 yet. Actually, there has - the first three days of the year belonged to ISO week 53 of 2009. While it might be possible to explain this to other programmers, the people who are going to read my reports are never going to understand this. Hence, I want to get rid of this week 53, by "moving" the data over to 2009.

How can I rewrite my WHERE clause to filter the data set to orders made between monday of week 1 and friday of the last week (52 or 53) in the year defined as @Year?

Body:
I am going to take a stab at this myself, using the approach described in my comments on Manfred's answer. The idea is to find the first day of the first ISO week of the specified year and the year after, allowing for index-enabled between filtering of the input records.

First, I create a function which will find the first day of the first ISO week  in a specific year:

create function firstIsoDay(@year int) returns datetime as begin
    declare @first datetime
    select @first = cast(cast(@year as char(4)) as datetime)
    select @first = dateadd(ww, datediff(ww, 0, @first), 0)
    if datepart(isowk, @first) > 1 set @first = @first + 7
    return @first
end

Disclaimer: This function is untested (having no Sql Server 2008 available at the moment).

The actual data query can then be made using two invocations of this function in a between filter:

select datepart(isowk, order_date), count(*) from orders
where order_date between firstIsoDay(@Year) and firstIsoDay(@Year + 1)
group by datepart(isowk, order_date), year(order_date)
order by 1

Remember that between is two-way inclusive. If the values in order_date contain truncated dates (no time), -1 should be added to the end of the where clause. In my use case, order_date has both date and time, so between two dates at midnight should do just fine.


问:
How to add daily stock price history col in mysql table in php using Cron Job
I am using cron job to update the stock price in my MySQL table which overwrites the daily price in the same col using Cron Job. Now I want to save daily closing price in a column to calculate Moving averages. I have more than 500 stocks on my table.

```<code>mysql_query("UPDATE `stock table`
set
    current_price='$current_price',
    change='$change',
    perchange='$perchange',
    post_modified='$updatetime',
    update='$update'
where ID='$postid'");
</code>```

What is the php code to add a col for the price when the date changes for 500 stocks rows?

答:
Kumar,

No one will write the code for you... if you have made an attempt at writing the code and if you are stuck, then someone can help out as to what's wrong with your code.

That said, if I understand what you are trying to achieve: you want a script that runs on a specified schedule (CRON) and fetches the stock prices of all 500 stocks and stores it in your stock table.

If that is the case--

Take a look at Yahoo! Finance API

Making use of that, you can write your script to fetch the prices. Doing a quick Google search, yielded this: https://benmarshall.me/php-stock-market-api/ Do not know how accurate/reliable etc. it is...

Give it a try and write the code yourself... In general never copy/paste otherwise you won't learn anything (among other reasons).

Hope this helps!

Best,

-Rush

Body:
I am using cron job to update the stock price in my MySQL table which overwrites the daily price in the same col using Cron Job. Now I want to save daily closing price in a column to calculate Moving averages. I have more than 500 stocks on my table.

mysql_query("UPDATE `stock table`
set
    current_price='$current_price',
    change='$change',
    perchange='$perchange',
    post_modified='$updatetime',
    update='$update'
where ID='$postid'");

What is the php code to add a col for the price when the date changes for 500 stocks rows?


问:
Mocked restTemplate.postForObject is not being used in execution of test
I have mocked a postForObject resttemplate call using mickito.

Mockito.when(restTemplate.postForObject(Mockito.eq(remoteServerlocation), Mockito.any(Input.class), Mockito.eq(String.class))).thenReturn(responseString);

But in the actual code, this mocked value is not being used and trying to call the remote location.

String responseString = restTemplate.postForObject(url, input, String.class);

As per my understanding , I have mocked exactly same call. But not working.
Any help on this will be thankful.

I'm autowiring the class which contains the testing method in testcase class. And this test class I have created restTemplate using new.

TestClass

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Application.class)
public class ActionImplTest {

    @Autowired
    private ActionImpl recommendation;

    RestTemplate restTemplate = new RestTemplate();

    @Test
    public void performActionTest() throws Exception {
        String textInput = "InputText";
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("convId", "C123");
        map.put("reID", 1);
        map.put("chID", "Chann_1");

        String convID = "1254356671563";
        String chId = "2";
        String responseString = "Success"
        Mockito.when(restTemplate.postForObject(Mockito.eq("remoteServerlocation"), Mockito.any(Input.class), Mockito.eq(String.class))).thenReturn(responseString);

        Map<String, Object> response = recommendation.performAction(textInput, map, convID, chId);
    }
}
</code>```

答:
Add a verify step at the end of your test, mockito will give you some hints on what was expected and what actually has been called:

```<code>Mockito.verify(restTemplate).postForObject(
    Mockito.eq(remoteServerlocation), Mockito.any(Input.class), Mockito.eq(String.class));
</code>```

Body:
I have mocked a postForObject resttemplate call using mickito.

Mockito.when(restTemplate.postForObject(Mockito.eq(remoteServerlocation), Mockito.any(Input.class), Mockito.eq(String.class))).thenReturn(responseString);

But in the actual code, this mocked value is not being used and trying to call the remote location.

String responseString = restTemplate.postForObject(url, input, String.class);

As per my understanding , I have mocked exactly same call. But not working.
Any help on this will be thankful.

I'm autowiring the class which contains the testing method in testcase class. And this test class I have created restTemplate using new.

TestClass

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Application.class)
public class ActionImplTest {

    @Autowired
    private ActionImpl recommendation;

    RestTemplate restTemplate = new RestTemplate();

    @Test
    public void performActionTest() throws Exception {
        String textInput = "InputText";
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("convId", "C123");
        map.put("reID", 1);
        map.put("chID", "Chann_1");

        String convID = "1254356671563";
        String chId = "2";
        String responseString = "Success"
        Mockito.when(restTemplate.postForObject(Mockito.eq("remoteServerlocation"), Mockito.any(Input.class), Mockito.eq(String.class))).thenReturn(responseString);

        Map<String, Object> response = recommendation.performAction(textInput, map, convID, chId);
    }
}

Body:
Add a verify step at the end of your test, mockito will give you some hints on what was expected and what actually has been called:

Mockito.verify(restTemplate).postForObject(
    Mockito.eq(remoteServerlocation), Mockito.any(Input.class), Mockito.eq(String.class));


问:
Angular 2 app - link to local file
In my app I'm viewing a list of files on the local machine (their paths are fetched from DB). When a file is being clicked, it should be opened. I tried the following with no success:

```<code><a href="file:///c:/path/to/file">FileName</a>
</code>```

When the user clicks the link above, nothing happens. When using chrome, I can see the following error message in the console (on firefox there's no message):

not allowed to load local resource

I have read this question, and understood that:

Mozilla browsers refuse to follow file URLs on a page that it has fetched with the HTTP protocol.

I also understood and that this feature was implemented in other browsers as well.

The presented files are not located in the server, but on the local machine. So I can't use a relative link (right?). Is there anyway to bypass this and create a link that opens a local file?

答:
You cannot access local resources from a website served over http because it is a security concern. Think of what would happen to your machine if any website could access files on it. You'll have other security restrictions for serving data from a different domain from your domain as well.

What exactly are you trying to accomplish by accessing a local file? Giving additional insight into the reason might get you more useful suggestions. Otherwise, the answer is that you can't and shouldn't do this.

Title: Angular 2 app - link to local file

Body:
In my app I'm viewing a list of files on the local machine (their paths are fetched from DB). When a file is being clicked, it should be opened. I tried the following with no success:

FileName

When the user clicks the link above, nothing happens. When using chrome, I can see the following error message in the console (on firefox there's no message):

not allowed to load local resource

I have read this question, and understood that:

Mozilla browsers refuse to follow file URLs on a page that it has fetched with the HTTP protocol.

I also understood and that this feature was implemented in other browsers as well.

The presented files are not located in the server, but on the local machine. So I can't use a relative link (right?). Is there anyway to bypass this and create a link that opens a local file?


答: you have user .addblog class name in two divs.so when you click on check box both divs get show and hide.so remove any one class or use different class name for new div to be inserted..

Title: Show div on checkbox tick


问:
Date and time of the applications last launch
In my application, you need to get the date and time of the all applications last  launch on the device. Can I somehow get this information by standard means?</p>

答:
Just save the time on every launch

```<code>SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
long lastLaunchMillis = sharedPref.getLong("lastLaunch", 0);
if (lastLaunchMillis != 0) {
    Calendar lastLaunch = Calendar.getInstance();
    lastLaunch.setTimeInMillis(lastLaunchMillis);
    //last launch found, handle
}
sharedPref.edit().putLong("lastLaunch", Calendar.getInstance().getTimeInMillis()).apply();
</code>```

Edit: For launch statistics of other apps, have a look at UsageStatsManager. You can find a sample on its usage here.

Body:
Just save the time on every launch

SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
long lastLaunchMillis = sharedPref.getLong("lastLaunch", 0);
if (lastLaunchMillis != 0) {
    Calendar lastLaunch = Calendar.getInstance();
    lastLaunch.setTimeInMillis(lastLaunchMillis);
    //last launch found, handle
}
sharedPref.edit().putLong("lastLaunch", Calendar.getInstance().getTimeInMillis()).apply();

Edit: For launch statistics of other apps, have a look at UsageStatsManager. You can find a sample on its usage here.


问:
body-parser(node.js) not able to understand form POST using fetch browser api
on sending form data using fetch api  as 'application/x-www-form-urlencoded' from browser to nodejs server, body-parser at node.js server not showing data sent but some object that is not understandable.

Here is the html form code:

```<code><body>
<form action="#" id="formToSubmit">
    <input type="text" name="name" value="xyz">
    <input type="text" name="phone" value="7777777777">
    <input type="submit" value="submit" onClick="submitForm()">
</form>

<script>
    function submitForm(){
        var form = new FormData(document.getElementById("formToSubmit"));
        fetch("http://localhost:8080/ppum", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: form // problem is here
        })
        .then(res => res.json())
        .then(data => console.log(data));

    }
</script>
</code>```

Here is the node server code for body parser:

```<code>app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
</code>```

Here is the output of "req.body" at server:

```<code>{"------WebKitFormBoundary5jfSRwRQ4GjgeApo\r\nContent-Disposition: form-data; name":"\"name\"\r\n\r\nxyz\r\n------WebKitFormBoundary5jfSRwRQ4GjgeApo\r\nContent-Disposition: form-data; name=\"phone\"\r\n\r\n7777777777\r\n------WebKitFormBoundary5jfSRwRQ4GjgeApo--\r\n"}
</code>```

problem is how to send data as 'application/x-www-form-urlencoded' from client side.

why is the output like as shown and how to correct  it.

Note:was previously using stackoverflow.com/a/37562814/3690154 and it workes. if you have some suggesting on how to convert FormData to something like in this answer that will be highly appreciated

答:
Here, we are rebuilding formBody from FormData object:

```<code><body>
<form action="#" id="formToSubmit">
    <input type="text" name="name" value="xyz">
    <input type="text" name="phone" value="7777777777">
    <input type="button" value="submit" onClick="submitForm()">
</form>

<script>
    function submitForm(){
        var form = new FormData(document.getElementById("formToSubmit"));
        var formBody = [];
        for ( var key of form.keys()){
            var encodedKey = encodeURIComponent(key);
            var encodedValue = encodeURIComponent(form.get(key));
            formBody.push(encodedKey + "=" + encodedValue);
        }
        formBody = formBody.join("&");
        fetch("http://localhost:8080/ppum", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: formBody
        })
        .then(res => res.json())
        .then(data => console.log(data));

    }
</script>
</code>```

Now body-parser is able to parse it correctly:

```<code>{"name":"xyz","phone":"7777777777"}
</code>```

Also changed the type of submit button from 'submit' to 'button' as per Quentin suggested.

Note: You can also apply this answer
https://stackoverflow.com/a/37562814/3690154

Body:
on sending form data using fetch api  as 'application/x-www-form-urlencoded' from browser to nodejs server, body-parser at node.js server not showing data sent but some object that is not understandable.

Here is the html form code:

<form action="#" id="formToSubmit">
    <input type="text" name="name" value="xyz">
    <input type="text" name="phone" value="7777777777">
    <input type="submit" value="submit" onClick="submitForm()">
</form>

Here is the node server code for body parser:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

Here is the output of "req.body" at server:

{"------WebKitFormBoundary5jfSRwRQ4GjgeApo\r\nContent-Disposition: form-data; name":"\"name\"\r\n\r\nxyz\r\n------WebKitFormBoundary5jfSRwRQ4GjgeApo\r\nContent-Disposition: form-data; name=\"phone\"\r\n\r\n7777777777\r\n------WebKitFormBoundary5jfSRwRQ4GjgeApo--\r\n"}

problem is how to send data as 'application/x-www-form-urlencoded' from client side.

why is the output like as shown and how to correct  it.

Note:was previously using stackoverflow.com/a/37562814/3690154 and it workes. if you have some suggesting on how to convert FormData to something like in this answer that will be highly appreciated

Body:
Here, we are rebuilding formBody from FormData object:

<body>
<form action="#" id="formToSubmit">
    <input type="text" name="name" value="xyz">
    <input type="text" name="phone" value="7777777777">
    <input type="button" value="submit" onClick="submitForm()">
</form>

<script>
    function submitForm(){
        var form = new FormData(document.getElementById("formToSubmit"));
        var formBody = [];
        for ( var key of form.keys()){
            var encodedKey = encodeURIComponent(key);
            var encodedValue = encodeURIComponent(form.get(key));
            formBody.push(encodedKey + "=" + encodedValue);
        }
        formBody = formBody.join("&");
        fetch("http://localhost:8080/ppum", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: formBody
        })
        .then(res => res.json())
        .then(data => console.log(data));

    }
</script>

Now body-parser is able to parse it correctly:

{"name":"xyz","phone":"7777777777"}

Also changed the type of submit button from 'submit' to 'button' as per Quentin suggested.

Note: You can also apply this answer
https://stackoverflow.com/a/37562814/3690154


问:
Tidy up PHP echo code
Apologies in advance though I've tried and failed several different things and obviously I'm not a php pro just yet.
I'm looking for a way to tidy up my code here, I'm pretty certain I don't need to continually type "echo" for each line but can't work out how to combine my code to achieve the same result, any ideas?

<?php
$values = get_field('bothscoreno');
$url    = "$values";
$arr    = str_split("$url, PHP_URL_QUERY");
if ($url) {
    echo $arr[11];
    echo $arr[12];
    echo $arr[13];
    echo $arr[14];
    echo $arr[15];
    echo $arr[16];
} else {
    echo 'No';
}
?>```

Thanks in advance.

答:
in PHP you're able to use a . as concatenation operator.

See the code below:

<?php
$values = get_field('bothscoreno');
$url    = "$values";
$arr    = str_split("$url, PHP_URL_QUERY");
if ($url) {
    echo $arr[11].
    $arr[12].
    $arr[13].
    $arr[14].
    $arr[15].
    $arr[16];
} else {
    echo 'No';
}```

Hope this helps!

Title: Tidy up PHP echo code

Body:
Apologies in advance though I've tried and failed several different things and obviously I'm not a php pro just yet.
I'm looking for a way to tidy up my code here, I'm pretty certain I don't need to continually type "echo" for each line but can't work out how to combine my code to achieve the same result, any ideas?

<?php
$values = get_field('bothscoreno');
$url    = "$values";
$arr    = str_split("$url, PHP_URL_QUERY");
if ($url) {
    echo $arr[11];
    echo $arr[12];
    echo $arr[13];
    echo $arr[14];
    echo $arr[15];
    echo $arr[16];
} else {
    echo 'No';
}
?>

Thanks in advance.

Body:
in PHP you're able to use a . as concatenation operator.

See the code below:

<?php
$values = get_field('bothscoreno');
$url    = "$values";
$arr    = str_split("$url, PHP_URL_QUERY");
if ($url) {
    echo $arr[11].
    $arr[12].
    $arr[13].
    $arr[14].
    $arr[15].
    $arr[16];
} else {
    echo 'No';
}

Hope this helps!


问:
Managing PHP Errors
I have been searching all over the net to try and find a way to catch all errors thrown by PHP (5.3)

I have been reading through the documentation and it looks like set_error_handler is what I need but it doesn't get fatal/parse errors. I'm not sure if this is possible...

Here is my source: https://github.com/tarnfeld/PHP-Error-Handler
Feel free to fork/commit if you know better solutions to all of this.

Thanks in advanced!

Updated!

Using the answers below I finished writing an error handler, it takes care of E_ERROR|E_PARSE|E_WARNING|E_NOTICE and will kill the script when it is fatal! :-)

答:
So called "fatal errors" is perhaps the most annoying bug in php. The best we can do about it is to convince "php group" to recognize this bug as such, by voting for this request http://bugs.php.net/bug.php?id=28331.

As long as this is not fixed, we're doomed to use dirty hacks like shutdown error handlers or autoloads.

Title: Managing PHP Errors


问:
Angular2 update binding
i have small question. I'll show my problem on this example:

```<code>    export class UserComponent {
      users: User[] = new Array<User>();
      removeAll(){
       this.users = new Array<User>();
      }
    }

<button (click)="removeAll">Remove</button>
<ul>
<li *ngFor="let user of users>{{user.name}}</li>
</ul>
</code>```

When I click on remove button they should be empty  but ul has all previous values. How to refresh binding?
Thanks

答:
```<code>(click)="removeAll"
</code>```

should be

```<code>(click)="removeAll()"
</code>```

Title: Angular2 update binding

Body:
i have small question. I'll show my problem on this example:

    export class UserComponent {
      users: User[] = new Array<User>();
      removeAll(){
       this.users = new Array<User>();
      }
    }

<button (click)="removeAll">Remove</button>

{{user.name}}

When I click on remove button they should be empty  but ul has all previous values. How to refresh binding?
Thanks

Body:
(click)="removeAll"

should be

(click)="removeAll()"


问:
PHP include VS loop
Using LOOP

```<code>for ($i=0; $i < 1000; $i++)
{
    echo "<li>content $i</li>";
}
</code>```

Using INCLUDE

```<code>include("file.php");
</code>```

the file.php contains same content as the loop but it is hard coded or static.

I've tried to run those two different codes on local host and monitor their response time. I can't decide which one to choose because the response time changes over time, some times the LOOP is faster but some time the INCLUDE is faster.

I want to ask your recommendation on which one is best to use.

答:
Obviously, directly using the loop would be faster. The reason is that when you use the include function, the php compiler has to make a call to include function and then fetch the file. Although the cost of include function is negligible, ( nearly 100 include will cause a lag of 4 milliseconds , but that's not something to worry about).

In the end it all comes down to individual preferences, as this loop might be having a lot of lines of code in the real world and you might want to keep it in a different file for structural purposes

Read This
What's the performance cost of "include" in PHP?

Title: PHP include VS loop

Body:
Using LOOP

for ($i=0; $i < 1000; $i++)
{
    echo "
content $i
";
}

Using INCLUDE

include("file.php");

the file.php contains same content as the loop but it is hard coded or static.

I've tried to run those two different codes on local host and monitor their response time. I can't decide which one to choose because the response time changes over time, some times the LOOP is faster but some time the INCLUDE is faster.

I want to ask your recommendation on which one is best to use.


问:
Using Mail.php it showing the following error?
While using mail.php it shows following error

Failed to connect to ssl://smtp.gmail.com:465 [SMTP: Failed to connect socket: An attempt was made to access a socket in a way forbidden by its access permissions. (code: -1, response: )]

答:
Try It..

```<code>{imap.gmail.com:993/imap/ssl}
</code>```

or

```<code>{imap.gmail.com:993/imap/ssl/novalidate-cert}
</code>```

Body:
Try It..

{imap.gmail.com:993/imap/ssl}

or

{imap.gmail.com:993/imap/ssl/novalidate-cert}


问:
Spring, hibernate entity fields depending on profile
i have something like this:

```<code>@Entity
@Table(name = "schedules")
public class ScheduleDO {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Long id;

@Column(name = "begin_time", columnDefinition = "TIMESTAMP WITH TIME ZONE",
nullable = false)
private OffsetDateTime beginTime;
}
</code>```

And i want to be able to change the "beginTime" variable anotation based on active profile. Something like this:

```<code>   @Profile("dev")
   @Column(name = "begin_time_dev", columnDefinition = "TIMESTAMP WITH TIME ZONE",
   nullable = false)
   @Profile("test")
   @Column(name = "begin_time_test", columnDefinition = "TIMESTAMP WITH TIME ZONE",
   nullable = false)
   private OffsetDateTime beginTime;
</code>```

is something like that possible?

答:
I think that you could possibly :

1)Create two different fields and different setters.

2)Add all JPA annotations on method level rather than on fields.

3)Since spring 4.1 you can profile methods, so use profiles on setters.

The @Profile annotation may be used in any of the following ways: as a type-level annotation on any class directly or indirectly annotated with @Component, including @Configuration classes. As a meta-annotation, for the purpose of composing custom stereotype annotations. As a method-level annotation on any @Bean method

PROFILE DOCS

Body:
i have something like this:

@Entity
@Table(name = "schedules")
public class ScheduleDO {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Long id;

@Column(name = "begin_time", columnDefinition = "TIMESTAMP WITH TIME ZONE",
nullable = false)
private OffsetDateTime beginTime;
}

And i want to be able to change the "beginTime" variable anotation based on active profile. Something like this:

   @Profile("dev")
   @Column(name = "begin_time_dev", columnDefinition = "TIMESTAMP WITH TIME ZONE",
   nullable = false)
   @Profile("test")
   @Column(name = "begin_time_test", columnDefinition = "TIMESTAMP WITH TIME ZONE",
   nullable = false)
   private OffsetDateTime beginTime;

is something like that possible?