问:
Webpack angular 4 file-loader
I'm using angular-starter.

Right now I'm trying to deploy to a test server. My problem is with the images located at src/assets/img.

My angular 4 code (component and view):

```<code>// Component
public ngOnInit() {
  this.logoUrl = require('../../assets/img/co-logo.png');
}

// View
<img flex src="{{logoUrl}}" alt="Logo">
</code>```

Till here I don't have any issue.

My problem is understanding the behavior of webpack.

I've file-loader installed and I've added this piece of code (and tried a lot of others options) to webpack.common.js:
Have tried with this options:

```<code>{
  test: /\.(png|jpe?g|gif)$/,
  use: [
    {
      loader: 'file-loader',
      options: {
        outputPath: '/assets/img/',
        publicPath: '/',
        name: '[hash]_[name].[ext]',
      }
    }
  ],
}
</code>```

The output seems not bad at all, I get this:

```<code> » app
  » dist
   » assets
    » img
    - b1249ef43aea4c57bcc7782f6a0ebb99_co-logo.png
</code>```

The issue

When loading the page, if I check the url of the image, it only retrieve me this:

```<code>/app/dist/01b401fa5bdbfdc4e3daf75d72fa76b9.png
</code>```

I was expecting something like:

```<code>/app/dist/assets/img/b1249ef43aea4c57bcc7782f6a0ebb99_co-logo.png
</code>```

I've tried, at least, with this parameters:

```<code>publicPath: '/assets/img/'
name: '/assets/img/[hash]_[name].[ext]'
</code>```

Can anyone help me on this? I'm struggling with this since yesterday :/

Thank you all!

Edit: webpack code

答:
Couple of things to make things clear and simple while resolving the issue

Make sure webpack config has output.path pointed to the
destination folder. I believe its app folder in your case. Do note
that output.path takes absolute path i.e use path module.

Take out publicPath in file-loader till we resolve the issue.

Use relative path for file-loader's outputPath i.e. assets/img

Once you do those changes, things should work as expected. Then you can try putting back publicPath for file-loader depending on your need.

In general, i wouldn't use publicPath unless i have different environments to be taken care for ex. prod and dev. But thats just me.

Title: Webpack angular 4 file-loader

Body:
I'm using angular-starter.

Right now I'm trying to deploy to a test server. My problem is with the images located at src/assets/img.

My angular 4 code (component and view):

// Component
public ngOnInit() {
  this.logoUrl = require('../../assets/img/co-logo.png');
}

// View

Till here I don't have any issue.

My problem is understanding the behavior of webpack.

I've file-loader installed and I've added this piece of code (and tried a lot of others options) to webpack.common.js:
Have tried with this options:

{
  test: /\.(png|jpe?g|gif)$/,
  use: [
    {
      loader: 'file-loader',
      options: {
        outputPath: '/assets/img/',
        publicPath: '/',
        name: '[hash]_[name].[ext]',
      }
    }
  ],
}

The output seems not bad at all, I get this:

 » app
  » dist
   » assets
    » img
    - b1249ef43aea4c57bcc7782f6a0ebb99_co-logo.png

The issue

When loading the page, if I check the url of the image, it only retrieve me this:

/app/dist/01b401fa5bdbfdc4e3daf75d72fa76b9.png

I was expecting something like:

/app/dist/assets/img/b1249ef43aea4c57bcc7782f6a0ebb99_co-logo.png

I've tried, at least, with this parameters:

publicPath: '/assets/img/'
name: '/assets/img/[hash]_[name].[ext]'

Can anyone help me on this? I'm struggling with this since yesterday :/

Thank you all!

Edit: webpack code


来源: stackexchange

问:
Preventing spam direct POST request customer registrations in Magento
I've begun to have some issues with spam POST requests on a Magento site where a bot is making spam users (this is even with the action attribute being removed, captcha, etc) as these bots I believe are just making direct POST requests to the standard Magento account url.

Here's 3 examples of valid POST requests I've seen in the log:

```<code>x.x.x.x - - [06/Nov/2017:13:54:47 -0500] "POST /customer/account/createpost/ HTTP/1.1" 302 - "https://www.example.com/customer/account/create/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36"

x.x.x.x - - [05/Nov/2017:11:34:42 -0500] "POST /customer/account/createpost/ HTTP/1.1" 302 - "https://www.example.com/customer/account/create/" "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"

x.x.x.x - - [05/Nov/2017:19:33:15 -0500] "POST /customer/account/createpost/ HTTP/1.1" 302 - "https://www.example.com/customer/account/create/" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"
</code>```

I've anonymized the IP addresses at the beginning, as well as the url. However, notice that the 2nd url is /customer/account/create/ while the first url is /customer/account/createpost/

Here's 3 examples of spam POST requests:

```<code>112.96.164.18 - - [05/Nov/2017:11:43:43 -0500] "POST /customer/account/createpost/ HTTP/1.1" 302 - "https://www.example.com/customer/account/createpost/" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0"

112.96.164.18 - - [05/Nov/2017:12:03:17 -0500] "POST /customer/account/createpost/ HTTP/1.1" 302 - "https://www.example.com/customer/account/createpost/" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0"

112.96.100.2 - - [05/Nov/2017:13:53:45 -0500] "POST /customer/account/createpost/ HTTP/1.1" 302 - "https://www.example.com/customer/account/createpost/" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0"
</code>```

As far as I can tell on every single spam request, both the first and second url are /customer/account/createpost/

What is the 2nd url in this, compared to the first? Is one where the request was sent and the other where it came from?

/customer/account/createpost/ should probably never be the origin, since that's where the form is actually sent, and visiting it directly redirect /customer/account/create/

My main question is, how do I reliably block the second set of POST requests?

答:
So I created a simple php file with a echo statement. Then added a .htaccess with below content

```<code>RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_METHOD} POST
RewriteCond %{REQUEST_URI} ^/customer/account/createpost/$
RewriteCond %{HTTP_REFERER} !^http://dev\.tarunlalwani\.com:8088/customer/account/create/$
RewriteRule ^.* - [F,L]
</code>```

Now some tests

Wrong Referer

```<code>$ curl -X POST -H "Referer: http://dev.tarunlalwani.com:8088/customer/account/creates/" dev.tarunlalwani.com:8088/customer/account/createpost/
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>403 Forbidden</title>
</head><body>
<h1>Forbidden</h1>
<p>You don't have permission to access /customer/account/createpost/
on this server.<br />
</p>
<hr>
<address>Apache/2.4.18 (Ubuntu) Server at dev.tarunlalwani.com Port 8088</address>
</body></html>
</code>```

Correct Referer

```<code>$ curl -X POST -H "Referer: http://dev.tarunlalwani.com:8088/customer/account/create/" dev.tarunlalwani.com:8088/customer/account/createpost/
Tarun here
</code>```

As you can anytime the referer is not exactly http://dev.tarunlalwani.com:8088/customer/account/create/ the POST request is denied. I think same should work for you. Just remember to update the domain name and remove the port. Change http to https if needed

ContentLicense: CC BY-SA 3.0

Body:
I've begun to have some issues with spam POST requests on a Magento site where a bot is making spam users (this is even with the action attribute being removed, captcha, etc) as these bots I believe are just making direct POST requests to the standard Magento account url.

Here's 3 examples of valid POST requests I've seen in the log:

x.x.x.x - - [06/Nov/2017:13:54:47 -0500] "POST /customer/account/createpost/ HTTP/1.1" 302 - "https://www.example.com/customer/account/create/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36"

x.x.x.x - - [05/Nov/2017:11:34:42 -0500] "POST /customer/account/createpost/ HTTP/1.1" 302 - "https://www.example.com/customer/account/create/" "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"

x.x.x.x - - [05/Nov/2017:19:33:15 -0500] "POST /customer/account/createpost/ HTTP/1.1" 302 - "https://www.example.com/customer/account/create/" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"

I've anonymized the IP addresses at the beginning, as well as the url. However, notice that the 2nd url is /customer/account/create/ while the first url is /customer/account/createpost/

Here's 3 examples of spam POST requests:

112.96.164.18 - - [05/Nov/2017:11:43:43 -0500] "POST /customer/account/createpost/ HTTP/1.1" 302 - "https://www.example.com/customer/account/createpost/" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0"

112.96.164.18 - - [05/Nov/2017:12:03:17 -0500] "POST /customer/account/createpost/ HTTP/1.1" 302 - "https://www.example.com/customer/account/createpost/" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0"

112.96.100.2 - - [05/Nov/2017:13:53:45 -0500] "POST /customer/account/createpost/ HTTP/1.1" 302 - "https://www.example.com/customer/account/createpost/" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0"

As far as I can tell on every single spam request, both the first and second url are /customer/account/createpost/

What is the 2nd url in this, compared to the first? Is one where the request was sent and the other where it came from?

/customer/account/createpost/ should probably never be the origin, since that's where the form is actually sent, and visiting it directly redirect /customer/account/create/

My main question is, how do I reliably block the second set of POST requests?

Body:
So I created a simple php file with a echo statement. Then added a .htaccess with below content

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_METHOD} POST
RewriteCond %{REQUEST_URI} ^/customer/account/createpost/$
RewriteCond %{HTTP_REFERER} !^http://dev\.tarunlalwani\.com:8088/customer/account/create/$
RewriteRule ^.* - [F,L]

Now some tests

Wrong Referer

$ curl -X POST -H "Referer: http://dev.tarunlalwani.com:8088/customer/account/creates/" dev.tarunlalwani.com:8088/customer/account/createpost/
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>403 Forbidden</title>
</head><body>
<h1>Forbidden</h1>
<p>You don't have permission to access /customer/account/createpost/
on this server.<br />
</p>
<hr>
<address>Apache/2.4.18 (Ubuntu) Server at dev.tarunlalwani.com Port 8088</address>
</body></html>

Correct Referer

$ curl -X POST -H "Referer: http://dev.tarunlalwani.com:8088/customer/account/create/" dev.tarunlalwani.com:8088/customer/account/createpost/
Tarun here

As you can anytime the referer is not exactly http://dev.tarunlalwani.com:8088/customer/account/create/ the POST request is denied. I think same should work for you. Just remember to update the domain name and remove the port. Change http to https if needed


问:
Node.js POST method error 404
I built an index.js file which sends SMS based on body input while posting with Postman. The code is working and looks like this (I have hidden my apiKey and apiSecret for this preview)

```<code>const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const Nexmo = require('nexmo');
const nexmo = new Nexmo({
   apiKey: 'hidden.apiKey',
   apiSecret: 'hidden.apiSecret'
   });

app.post('/send', (req, res) => {
// Sending SMS via Nexmo
nexmo.message.sendSms(
    '4542542445', req.body.toNumber, req.body.message, {type: 'unicode'},
  (err, responseData) => {if (responseData) {console.log(responseData)}}
);
});
const server = app.listen(3000);
console.log("starting server")
</code>```

It woks fine and I receive an SMS message when I run the file, and a post to the route using Postman.

I am trying to implement the same in my bigger project, where I have separate client and server folders representing my frontend and backend.

When I add the code to my app.js file, I run into Status code 404 not found error. Here is the code of my app.js:

```<code>const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const morgan = require('morgan')
const {sequelize} = require('./models')
const config = require('./config/config')
const Nexmo = require('nexmo')

const app = express()

app.use(morgan('combined'))

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

app.use(cors())

require('./routes')(app)

sequelize.sync()
.then(() => {
    app.listen(config.port)
    console.log(`Server started on port ${config.port}`)
})

const nexmo = new Nexmo({
apiKey: 'hidden.apiKey',
apiSecret: 'hidden.apiSecret'
}, {debug: true})

app.post('/send', (req, res) => {
// Sending SMS via Nexmo
nexmo.message.sendSms(
    '4542542445', req.body.toNumber, req.body.message, {type: 'unicode'},
  (err, responseData) => {if (responseData) {console.log(responseData)}}
);
  });
</code>```

I am asking for help to try figure out what is wrong and why it does not hit the route, instead returning status code 404.

I can share my github or we can talk on discord: soko#8667

I appreciate your thoughts and help.

答:
Routes in express should be written :</p>

```<code>let route =  require('routes');
app.use('/', route);
</code>```

Title: Node.js POST method error 404

Body:
I built an index.js file which sends SMS based on body input while posting with Postman. The code is working and looks like this (I have hidden my apiKey and apiSecret for this preview)

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const Nexmo = require('nexmo');
const nexmo = new Nexmo({
   apiKey: 'hidden.apiKey',
   apiSecret: 'hidden.apiSecret'
   });

app.post('/send', (req, res) => {
// Sending SMS via Nexmo
nexmo.message.sendSms(
    '4542542445', req.body.toNumber, req.body.message, {type: 'unicode'},
  (err, responseData) => {if (responseData) {console.log(responseData)}}
);
});
const server = app.listen(3000);
console.log("starting server")

It woks fine and I receive an SMS message when I run the file, and a post to the route using Postman.

I am trying to implement the same in my bigger project, where I have separate client and server folders representing my frontend and backend.

When I add the code to my app.js file, I run into Status code 404 not found error. Here is the code of my app.js:

const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const morgan = require('morgan')
const {sequelize} = require('./models')
const config = require('./config/config')
const Nexmo = require('nexmo')

const app = express()

app.use(morgan('combined'))

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

app.use(cors())

require('./routes')(app)

sequelize.sync()
.then(() => {
    app.listen(config.port)
    console.log(`Server started on port ${config.port}`)
})

const nexmo = new Nexmo({
apiKey: 'hidden.apiKey',
apiSecret: 'hidden.apiSecret'
}, {debug: true})

app.post('/send', (req, res) => {
// Sending SMS via Nexmo
nexmo.message.sendSms(
    '4542542445', req.body.toNumber, req.body.message, {type: 'unicode'},
  (err, responseData) => {if (responseData) {console.log(responseData)}}
);
  });

I am asking for help to try figure out what is wrong and why it does not hit the route, instead returning status code 404.

I can share my github or we can talk on discord: soko#8667

I appreciate your thoughts and help.

Body:
Routes in express should be written :

let route =  require('routes');
app.use('/', route);


问:
How can I speed up this SQL update query?
The A table is huge (50+ millions rows) table. So this update method is too slow for MSSQL server. In addition to it runs in a store procedure's while loop. I think this solution is not quite effective.

Has Somebody any good idea to solve this problem?

Thanks!

A table's definition

```<code>CREATE TABLE [dbo].[A](
    [E_NUM] [int] NOT NULL,
    [ID] [char](1) NOT NULL,
    [NUM] [int] NOT NULL,
    [h_out] [smallint] NOT NULL,
    [TAG] [smallint] NOT NULL,
    [TAG1] [smallint] NOT NULL,

 CONSTRAINT [PK_A] PRIMARY KEY CLUSTERED
(
    [E_NUM] ASC,
    [ID] ASC,
    [NUM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
</code>```

B table's definition

```<code>CREATE TABLE [dbo].[B](
    [NUM] [int] NOT NULL,
    [NUM2] [int] NOT NULL,
    [TYPE] [char](1) NOT NULL,
    [R_DATE] [datetime] NULL,
    [Note] [varchar](100) NULL,
 CONSTRAINT [PK_B] PRIMARY KEY CLUSTERED
(
    [NUM] ASC,
    [NUM2] ASC,
    [TYPE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
</code>```

UPDATE

```<code> UPDATE A_1
 SET A_1.TAG1 = -1
 FROM A
 INNER JOIN B ON A.NUM = B.NUM
 INNER JOIN A AS A_1 ON B.NUM2 = A_1.NUM
 WHERE A.TAG1 = -1 AND A.TAG = -1 AND B.TYPE='X'
 AND  A.E_num = A_1.E_num AND A.ID=A_1.[ID];
</code>```

答:
Assuming I didn't make any mistakes, this should be equivalent to your UPDATE statement:

```<code> UPDATE upd
    SET upd.TAG1 = -1
   FROM A upd

   JOIN A
     ON A.ID    = upd.ID
    AND A.E_NUM = upd.E_NUM
    AND A.TAG1 = -1
    AND A.TAG  = -1

   JOIN B
     ON B.NUM  = A.NUM
    AND B.NUM2 = upd.NUM
    AND B.TYPE = 'X'
</code>```

Since you don't have any indexes for things like B.TYPE or A.TAG etc.. the system is pretty much obliged to go over the entire table to find the applicable records. If your table is HUGE, then yes, this will takes some time.

Add these indexes and then try again:

```<code>CREATE INDEX idx1_A ON A (TAG, TAG1, ID, E_NUM) INCLUDE (NUM) -- NUM is implicit due to PK if you think about it
CREATE INDEX idx1_B ON B (TYPE, NUM, NUM2)
</code>```

You're right to assume that updating TAG1 will require updating idx1_A too, but this will still be a lot faster than scanning the entire table. (**)

You might want to add

```<code>  WHERE upd.TAG1 <> -1
</code>```

to avoid having to update when the right value is already present to minimize the impact.

(**: if your update affects 80% of the records it might not be worth having the index on table A, but keep in mind that it would be a gigantic operation and as such will need a lot of time simply because it's a lot of work!)

Body:
The A table is huge (50+ millions rows) table. So this update method is too slow for MSSQL server. In addition to it runs in a store procedure's while loop. I think this solution is not quite effective.

Has Somebody any good idea to solve this problem?

Thanks!

A table's definition

CREATE TABLE [dbo].[A](
    [E_NUM] [int] NOT NULL,
    [ID] [char](1) NOT NULL,
    [NUM] [int] NOT NULL,
    [h_out] [smallint] NOT NULL,
    [TAG] [smallint] NOT NULL,
    [TAG1] [smallint] NOT NULL,

 CONSTRAINT [PK_A] PRIMARY KEY CLUSTERED
(
    [E_NUM] ASC,
    [ID] ASC,
    [NUM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

B table's definition

CREATE TABLE [dbo].[B](
    [NUM] [int] NOT NULL,
    [NUM2] [int] NOT NULL,
    [TYPE] [char](1) NOT NULL,
    [R_DATE] [datetime] NULL,
    [Note] [varchar](100) NULL,
 CONSTRAINT [PK_B] PRIMARY KEY CLUSTERED
(
    [NUM] ASC,
    [NUM2] ASC,
    [TYPE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

UPDATE

 UPDATE A_1
 SET A_1.TAG1 = -1
 FROM A
 INNER JOIN B ON A.NUM = B.NUM
 INNER JOIN A AS A_1 ON B.NUM2 = A_1.NUM
 WHERE A.TAG1 = -1 AND A.TAG = -1 AND B.TYPE='X'
 AND  A.E_num = A_1.E_num AND A.ID=A_1.[ID];

Body:
Assuming I didn't make any mistakes, this should be equivalent to your UPDATE statement:

 UPDATE upd
    SET upd.TAG1 = -1
   FROM A upd

   JOIN A
     ON A.ID    = upd.ID
    AND A.E_NUM = upd.E_NUM
    AND A.TAG1 = -1
    AND A.TAG  = -1

   JOIN B
     ON B.NUM  = A.NUM
    AND B.NUM2 = upd.NUM
    AND B.TYPE = 'X'

Since you don't have any indexes for things like B.TYPE or A.TAG etc.. the system is pretty much obliged to go over the entire table to find the applicable records. If your table is HUGE, then yes, this will takes some time.

Add these indexes and then try again:

CREATE INDEX idx1_A ON A (TAG, TAG1, ID, E_NUM) INCLUDE (NUM) -- NUM is implicit due to PK if you think about it
CREATE INDEX idx1_B ON B (TYPE, NUM, NUM2)

You're right to assume that updating TAG1 will require updating idx1_A too, but this will still be a lot faster than scanning the entire table. (**)

You might want to add

  WHERE upd.TAG1 <> -1

to avoid having to update when the right value is already present to minimize the impact.

(**: if your update affects 80% of the records it might not be worth having the index on table A, but keep in mind that it would be a gigantic operation and as such will need a lot of time simply because it's a lot of work!)


问:
Symfony validation: range between two numbers, OR a value
I would like to validate a number to be between 10 and 20, or 30 and 40 or equal to 99.

I could imagine the code to be something similar to this, but it does not work:

In Entity\NameOfFile.php:

```<code>/*
 * @Assert\Range(
 *   min=10,
 *   max=20
 * )
 *
 * @Assert\Range(
 *  min=30,
 *  max=40
 * )
 *
 * @Assert\IdenticalTo(value = 99)
 */
 private $myVariable;
</code>```

Or maybe something similar to this:

```<code> /*
  * @Assert\Choice({
  *  Range({min = 10, max = 20}),
  *  Range({min = 10, max = 20}),
  *  99
  * )}
  */
  private $myVariable;
</code>```

I also added min and max messages.

In the first option, apparently only the first Assert is taken into consideration and the second one is ignored. The second option, does not work at all.

Ps: Please, a solution without Regex

EDIT:
Following the advice of M Khalid Juanid, the code looks like this:

```<code>/**
 * @Assert\Expression(
 *     "this.getmyVariable() in 10..20 or this.getmyVariable() in 30..40 or this.getmyVariable() == 99",
 *     message="Your error message", groups{"groupA"}
 * )
*private $myVariable;
 */

  ***
if($appendForm->isValid(array($groupA))
{
***
}
</code>```

It works fine, but only when the validation is not assigned to groupA. How can, the validation be assigned to a group, in this case?

答:
You can use a custom validation constraint. To create one you can refer to the official documentation: http://symfony.com/doc/3.4/validation/custom_constraint.html

You will have to put all your constraints in the validate function of the Validator class.

Body:
I would like to validate a number to be between 10 and 20, or 30 and 40 or equal to 99.

I could imagine the code to be something similar to this, but it does not work:

In Entity\NameOfFile.php:

/*
 * @Assert\Range(
 *   min=10,
 *   max=20
 * )
 *
 * @Assert\Range(
 *  min=30,
 *  max=40
 * )
 *
 * @Assert\IdenticalTo(value = 99)
 */
 private $myVariable;

Or maybe something similar to this:

 /*
  * @Assert\Choice({
  *  Range({min = 10, max = 20}),
  *  Range({min = 10, max = 20}),
  *  99
  * )}
  */
  private $myVariable;

I also added min and max messages.

In the first option, apparently only the first Assert is taken into consideration and the second one is ignored. The second option, does not work at all.

Ps: Please, a solution without Regex

EDIT:
Following the advice of M Khalid Juanid, the code looks like this:

/**
 * @Assert\Expression(
 *     "this.getmyVariable() in 10..20 or this.getmyVariable() in 30..40 or this.getmyVariable() == 99",
 *     message="Your error message", groups{"groupA"}
 * )
*private $myVariable;
 */

  ***
if($appendForm->isValid(array($groupA))
{
***
}

It works fine, but only when the validation is not assigned to groupA. How can, the validation be assigned to a group, in this case?


问:
Android change Activity after few seconds
I need some help with my first Android project.
I want to write a app which is showing you a picture with a ImageView for a few seconds I would say so about 4 seconds and after that it change to a second activity which shows a button(only for testing).

My Problem is that my app after I started it in my AVD jump over the picture and shows immediately the button.

How can I fix it? I looked up so long and tried so many things I hope someone of you have a idea :)

Thanks for helping

Here my Code of my MainActivity:

```<code>     package com.example.parkourspots;
 public class MainActivity extends Activity {

private ViewTreeObserver vto;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final View myLayout = findViewById(R.id.startscreen);

    vto = myLayout.getViewTreeObserver();

    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){

        @Override
        public void onGlobalLayout(){
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            Intent intent = new Intent(MainActivity.this, select_activity_class.class);

            startActivity(intent);

    }
});

}}
</code>```

答:
Proper and short solution

Make a handler and give them a delay to call back itself:

```<code>final Handler h = new Handler();

h.postDelayed(new Runnable() {

   @Override

   public void run() {

     //Do something after 1s

   }

}, 1000);
</code>```

Remember that 1 sec = 1000 milliseconds

Adjust time with that formula.

Happy Coding.

Body:
I need some help with my first Android project.
I want to write a app which is showing you a picture with a ImageView for a few seconds I would say so about 4 seconds and after that it change to a second activity which shows a button(only for testing).

My Problem is that my app after I started it in my AVD jump over the picture and shows immediately the button.

How can I fix it? I looked up so long and tried so many things I hope someone of you have a idea :)

Thanks for helping

Here my Code of my MainActivity:

     package com.example.parkourspots;
 public class MainActivity extends Activity {

private ViewTreeObserver vto;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final View myLayout = findViewById(R.id.startscreen);

    vto = myLayout.getViewTreeObserver();

    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){

        @Override
        public void onGlobalLayout(){
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            Intent intent = new Intent(MainActivity.this, select_activity_class.class);

            startActivity(intent);

    }
});

}}

Body:
Proper and short solution

Make a handler and give them a delay to call back itself:

final Handler h = new Handler();

h.postDelayed(new Runnable() {

   @Override

   public void run() {

     //Do something after 1s

   }

}, 1000);

Remember that 1 sec = 1000 milliseconds

Adjust time with that formula.

Happy Coding.


问:
Convert Array of Dictionary to custom object swift
I have:

```<code>    let countries : [[String : Any]] = [
            [
                "name" : "Afghanistan",
                "dial_code": "+93",
                "code": "AF"
            ],
            [
                "name": "Aland Islands",
                "dial_code": "+358",
                "code": "AX"
            ],
            [
                "name": "Albania",
                "dial_code": "+355",
                "code": "AL"
            ],
            [
                "name": "Algeria",
                "dial_code": "+213",
                "code": "DZ"
            ]
]
</code>```

I want to add all this array of dictionary to my custom object like

```<code>let country:[Country] = countries
</code>```

My custom object looks like this:

```<code>class Country: NSObject {
        let name: String
        let dial_code : String
        let code: String

        init(name: String, dial_code: String, code: String) {
            self.name = name
            self.dial_code = dial_code
            self.code = code
        }
    }
</code>```

I understand that I need a loop thru the array but idk what is the next step. Would be great to have an example.

答:
First you need to initialize an empty array type of Country Class</p>

```<code>var countryArray = [Country]()
//then you have to loop thru the countries dictionary
//and after casting them adding it to this empty array with class initializer

countries.forEach { (dict) in

    countryArray.append(Country(name: dict["name"] as! String, dial_code: dict["dial_code"] as! String, code: dict["code"] as! String))

}
//this is how you reach to properties
countryArray.forEach { (country) in
    print(country.name)
}
</code>```

Body:
I have:

    let countries : [[String : Any]] = [
            [
                "name" : "Afghanistan",
                "dial_code": "+93",
                "code": "AF"
            ],
            [
                "name": "Aland Islands",
                "dial_code": "+358",
                "code": "AX"
            ],
            [
                "name": "Albania",
                "dial_code": "+355",
                "code": "AL"
            ],
            [
                "name": "Algeria",
                "dial_code": "+213",
                "code": "DZ"
            ]
]

I want to add all this array of dictionary to my custom object like

let country:[Country] = countries

My custom object looks like this:

class Country: NSObject {
        let name: String
        let dial_code : String
        let code: String

        init(name: String, dial_code: String, code: String) {
            self.name = name
            self.dial_code = dial_code
            self.code = code
        }
    }

I understand that I need a loop thru the array but idk what is the next step. Would be great to have an example.

Body:
First you need to initialize an empty array type of Country Class

var countryArray = [Country]()
//then you have to loop thru the countries dictionary
//and after casting them adding it to this empty array with class initializer

countries.forEach { (dict) in

    countryArray.append(Country(name: dict["name"] as! String, dial_code: dict["dial_code"] as! String, code: dict["code"] as! String))

}
//this is how you reach to properties
countryArray.forEach { (country) in
    print(country.name)
}


问:
ORMLite DISTINCT With Where Condition
I am developing an android project using ORMLite and i have a problem to figure out. There is a picture below and how can i use DISTINCT sql query in ORMLite?
I have some parameters giving to where condition and according to this conditions i am getting number list...

In this picture you are going to see some numbers and some of these numbers are same but i don't want to get same numbers so how can i use DISTINCT in ORMLite with where condition.

Thanks for helping

Also some of my code is like this:

```<code>  private void modalShowEbat() {
    dbHelper = (DBHelper) OpenHelperManager.getHelper(this, DBHelper.class);
    RuntimeExceptionDao<Segment, Integer> segmentDao = dbHelper.getSegmentExceptionDao();
    List<Segment> list = segmentDao.queryForEq(Constant.QUERY_SEGMENT, editTextSegment.getText().toString().trim());

    final CharSequence items[] = new CharSequence[list.size()];
    for (int i = 0; i < list.size(); i++) {
        items[i] = list.get(i).getColumnEbat();
    }
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Segment seçiniz");
    builder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // the user clicked on colors[which]
            editTextEbat.setText(items[which].toString());
            if (alertDialog != null && alertDialog.isShowing()) {
                alertDialog.dismiss();
            }
        }
    });
    alertDialog = builder.create();
    alertDialog.show();
}
</code>```

This is my image of result

答:
Use this - </p>

```<code>segmentDao.queryBuilder().distinct().where().eq("name", "value").query();
</code>```

Title: ORMLite DISTINCT With Where Condition

Body:
I am developing an android project using ORMLite and i have a problem to figure out. There is a picture below and how can i use DISTINCT sql query in ORMLite?
I have some parameters giving to where condition and according to this conditions i am getting number list...

In this picture you are going to see some numbers and some of these numbers are same but i don't want to get same numbers so how can i use DISTINCT in ORMLite with where condition.

Thanks for helping

Also some of my code is like this:

  private void modalShowEbat() {
    dbHelper = (DBHelper) OpenHelperManager.getHelper(this, DBHelper.class);
    RuntimeExceptionDao<Segment, Integer> segmentDao = dbHelper.getSegmentExceptionDao();
    List<Segment> list = segmentDao.queryForEq(Constant.QUERY_SEGMENT, editTextSegment.getText().toString().trim());

    final CharSequence items[] = new CharSequence[list.size()];
    for (int i = 0; i < list.size(); i++) {
        items[i] = list.get(i).getColumnEbat();
    }
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Segment seçiniz");
    builder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // the user clicked on colors[which]
            editTextEbat.setText(items[which].toString());
            if (alertDialog != null && alertDialog.isShowing()) {
                alertDialog.dismiss();
            }
        }
    });
    alertDialog = builder.create();
    alertDialog.show();
}

This is my image of result

Body:
Use this -

segmentDao.queryBuilder().distinct().where().eq("name", "value").query();


问:
How to correctly update a MongoDB timeseries array without duplicates?
I have the following timeseries array (named "data"), nested in a mongodb document:

```<code>"_id" : ObjectId("5a235e645bb1000704593960"),
"data" : [
    {
       "Volume" : NumberLong(41527200),
       "Adj Close" : 171.850006,
       "High" : 172.139999,
       "Low" : 168.440002,
       "Date" : ISODate("2017-11-30T00:00:00.000+0000"),
       "Close" : 171.850006,
       "Open" : 170.429993
    },
    {
        "Volume" : NumberLong(39726100),
        "Adj Close" : 171.050003,
        "High" : 171.669998,
        "Low" : 168.5,
        "Date" : ISODate("2017-12-01T00:00:00.000+0000"),
        "Close" : 171.050003,
        "Open" : 169.949997
    },
    {
        "Volume" : NumberLong(39759300),
        "Adj Close" : 171.050003,
        "High" : 171.669998,
        "Low" : 168.5,
        "Date" : ISODate("2017-12-01T00:00:00.000+0000"),
        "Close" : 171.050003,
            "Open" : 169.949997
        },

    ],
    "ticker" : "AAPL",
    "last_update" : ISODate("2017-12-07T00:00:00.000+0000")
}
</code>```

My issue is that when I update the timeseries, some array elements for a given date may change. For example, in the array there are 2 records for 2017-12-01. All fields are the same except "Volume." When I update the array however, a new record is added to the array, instead of updating the existing 2017-01-01 record.

I am currently updating the document with the following:

```<code>self.__db.equity_data.update({'ticker': ticker,
                              'last_update': {'$lt': record['last_update']}},
                             {'$set': {'last_update':record['last_update']},
                              '$addToSet': {'data': {'$each': record['data']}}},
                               upsert=True
                                 )
</code>```

Is there any way that I can ensure that a duplicate item (based on the date) is not added to the array, and instead update the existing array element?

Thanks for any help.

答:
I am unfamiliar with pymongo, but have you tried setting upsert flag to false? It should prevent creating new documents instead of updating the old ones if the rest of the statements is correct. Also, you should try adding the multi flag because the above code will only update one document by default.
Good luck!

Body:
I have the following timeseries array (named "data"), nested in a mongodb document:

"_id" : ObjectId("5a235e645bb1000704593960"),
"data" : [
    {
       "Volume" : NumberLong(41527200),
       "Adj Close" : 171.850006,
       "High" : 172.139999,
       "Low" : 168.440002,
       "Date" : ISODate("2017-11-30T00:00:00.000+0000"),
       "Close" : 171.850006,
       "Open" : 170.429993
    },
    {
        "Volume" : NumberLong(39726100),
        "Adj Close" : 171.050003,
        "High" : 171.669998,
        "Low" : 168.5,
        "Date" : ISODate("2017-12-01T00:00:00.000+0000"),
        "Close" : 171.050003,
        "Open" : 169.949997
    },
    {
        "Volume" : NumberLong(39759300),
        "Adj Close" : 171.050003,
        "High" : 171.669998,
        "Low" : 168.5,
        "Date" : ISODate("2017-12-01T00:00:00.000+0000"),
        "Close" : 171.050003,
            "Open" : 169.949997
        },

    ],
    "ticker" : "AAPL",
    "last_update" : ISODate("2017-12-07T00:00:00.000+0000")
}

My issue is that when I update the timeseries, some array elements for a given date may change. For example, in the array there are 2 records for 2017-12-01. All fields are the same except "Volume." When I update the array however, a new record is added to the array, instead of updating the existing 2017-01-01 record.

I am currently updating the document with the following:

self.__db.equity_data.update({'ticker': ticker,
                              'last_update': {'$lt': record['last_update']}},
                             {'$set': {'last_update':record['last_update']},
                              '$addToSet': {'data': {'$each': record['data']}}},
                               upsert=True
                                 )

Is there any way that I can ensure that a duplicate item (based on the date) is not added to the array, and instead update the existing array element?

Thanks for any help.


问:
Twilio Logs on Console for Error 21614
I have successfully attempted sending SMS to a phone number using Twilio REST API in PHP. Currently I am using a trial account. I can see logs on Twilio console too. When I attempt to send SMS to an invalid number, Twilio REST API gives me error:
    Error 21614 - 'To' number is not a valid mobile number.
I can't view this error in Twilio Programmable SMS logs or Debugger Logs. So when I submit a bulk of numbers to Twilio, how can I find at the end, that which numbers failed to receive the SMSs because of error 21614, on Twilio Console? Currenty, I do not want to log it through my PHP code.

Thank you.

答:
EDIT

If you want to go through the console you can see this link as you do not want to manage it via php

For managing at your end with StatusCallback

You need to use optional parameter StatusCallback and specify a callback URL where Twilio will POST each time your message status changes to one of the following:

queued,

failed,

sent,

delivered,

or undelivered.

Twilio will POST the MessageSid along with the other standard request parameters as well as MessageStatus and ErrorCode. If this parameter passed in addition to a MessagingServiceSid, Twilio will override the Status Callback URL of the Messaging Service. URLs must contain a valid hostname (underscores are not allowed). You can learn more about it here

you can add your php code there to keep track of every new message and keep updating the logs for that message.

Hope that helps

Title: Twilio Logs on Console for Error 21614


问:
How to write data from datagridview to XML
I have added a lot of blank lines to the datagridview and I want to write the data to xml. I've done a few little researches, but I'm glad that you did not do it the way I wanted to.

```<code>DataTable dt = new DataTable();
dt.TableName = "SD";
dt = dataGridView1.DataSource as DataTable;
dt.WriteXml("SD.xml");
</code>```

it's not working or i couldn't run it.

Its error message:

System.NullReferenceException: 'Object reference not set to an
  instance of an object.'

答:
It's very likely that your dt is coming back null in dt = dataGridView1.DataSource as DataTable;, therefore throwing System.NullReferenceException: 'Object reference not set to an instance of an object. Make sure your dataGridView1.DataSource can actually be cast as DataTable

Here's a full snippet.

```<code>using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace DataGridViewToXML_47696565
{
    public partial class Form1 : Form
    {

        DataTable dgvdt = new DataTable();
        DataGridView dgv = new DataGridView();
        Button btn = new Button();
        public Form1()
        {
            InitializeComponent();
            InitOurStuff();
        }

        private void InitOurStuff()
        {
            this.Controls.Add(dgv);
            dgv.DataSource = dgvdt;
            dgv.Dock = DockStyle.Top;

            dgvdt.TableName = "SD";
            dgvdt.Columns.Add();
            for (int i = 0; i < 10; i++)
            {
                dgvdt.Rows.Add($"row {i}");
            }

            this.Controls.Add(btn);
            btn.Location = new Point(5, dgv.Location.Y + dgv.Height + 5);
            btn.Text = "Click me";
            btn.Click += Btn_Click;

        }

        private void Btn_Click(object sender, EventArgs e)
        {
            dgvdt.WriteXml(@"c:\temp\mydtxml.xml");
        }
    }
}
</code>```

Here's another snippet where my DataSource is not already a DataTable.

```<code>using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace DataGridViewToXML_47696565
{
    public partial class Form2 : Form
    {
        BindingList<dgventry> dgvdata = new BindingList<dgventry>();
        DataGridView dgv = new DataGridView();
        Button btn = new Button();

        public Form2()
        {
            InitializeComponent();
            initOurStuff();
        }

        private void initOurStuff()
        {
            dgv.Dock = DockStyle.Top;
            dgv.DataSource = dgvdata;
            this.Controls.Add(dgv);

            for (int i = 0; i < 10; i++)
            {
                dgvdata.Add(new dgventry { col1 = $"col1 row{i}", col2 = $"col2 row{i}", col3 = $"col3 row{i}" });
            }

            this.Controls.Add(btn);
            btn.Location = new Point(5, dgv.Location.Y + dgv.Height + 5);
            btn.Text = "Click me";
            btn.Click += Btn_Click; ;
        }

        private void Btn_Click(object sender, EventArgs e)
        {

            /*The DataSource connected to the DGV is not already a DataTable,
             so I'll traverse the DataGridView and create my own DataTable out of it*/
            DataTable dt = new DataTable();//create the data table
            dt.TableName = "SD";//give it a name
            //create the appropriate number of columns
            for (int i = 0; i < dgv.Columns.Count; i++)
            {
                dt.Columns.Add(dgv.Columns[i].HeaderText);
            }

            //loop through each row of the DataGridView
            foreach (DataGridViewRow currentRow in dgv.Rows)
            {
                dt.Rows.Add();
                int runningCount = 0;
                //loop trough each column of the row
                foreach (DataGridViewCell item in currentRow.Cells)
                {
                    dt.Rows[dt.Rows.Count - 1][runningCount] = item.FormattedValue;
                    runningCount++;
                }
            }

            if (dt != null)
            {
                dt.WriteXml(@"c:\temp\mynewxml.xml");
            }

        }
    }

    public class dgventry
    {
        public string col1 { get; set; }
        public string col2 { get; set; }
        public string col3 { get; set; }
    }
}
</code>```

Here's another snippet. In this one, the DataGridView starts empty. The user has to manually enter data into it.

```<code>using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace DataGridViewToXML_47696565
{
    public partial class Form3 : Form
    {

        DataGridView dgv = new DataGridView();
        Button btn = new Button();

        public Form3()
        {
            InitializeComponent();
            initOurStuff();
        }

        private void initOurStuff()
        {
            dgv.Dock = DockStyle.Top;
            this.Controls.Add(dgv);
            for (int i = 0; i < 10; i++)
            {
                DataGridViewColumn newcol = new DataGridViewTextBoxColumn();
                newcol.Name = $"col{i}";
                dgv.Columns.Add(newcol);
            }

            this.Controls.Add(btn);
            btn.Location = new Point(5, dgv.Location.Y + dgv.Height + 5);
            btn.Text = "Click me";
            btn.Click += Btn_Click; ;
        }

        private void Btn_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();//create the data table
            dt.TableName = "SD";//give it a name
            //create the appropriate number of columns
            for (int i = 0; i < dgv.Columns.Count; i++)
            {
                dt.Columns.Add(dgv.Columns[i].HeaderText);
            }

            //loop through each row of the DataGridView
            foreach (DataGridViewRow currentRow in dgv.Rows)
            {
                dt.Rows.Add();
                int runningCount = 0;
                //loop trough each column of the row
                foreach (DataGridViewCell item in currentRow.Cells)
                {
                    dt.Rows[dt.Rows.Count - 1][runningCount] = item.FormattedValue;
                    runningCount++;
                }
            }

            if (dt != null)
            {
                dt.WriteXml(@"c:\temp\mynewxml.xml");
            }
        }
    }
}
</code>```

Body:
I have added a lot of blank lines to the datagridview and I want to write the data to xml. I've done a few little researches, but I'm glad that you did not do it the way I wanted to.

DataTable dt = new DataTable();
dt.TableName = "SD";
dt = dataGridView1.DataSource as DataTable;
dt.WriteXml("SD.xml");

it's not working or i couldn't run it.

Its error message:

System.NullReferenceException: 'Object reference not set to an
  instance of an object.'

Body:
It's very likely that your dt is coming back null in dt = dataGridView1.DataSource as DataTable;, therefore throwing System.NullReferenceException: 'Object reference not set to an instance of an object. Make sure your dataGridView1.DataSource can actually be cast as DataTable

Here's a full snippet.

using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace DataGridViewToXML_47696565
{
    public partial class Form1 : Form
    {

        DataTable dgvdt = new DataTable();
        DataGridView dgv = new DataGridView();
        Button btn = new Button();
        public Form1()
        {
            InitializeComponent();
            InitOurStuff();
        }

        private void InitOurStuff()
        {
            this.Controls.Add(dgv);
            dgv.DataSource = dgvdt;
            dgv.Dock = DockStyle.Top;

            dgvdt.TableName = "SD";
            dgvdt.Columns.Add();
            for (int i = 0; i < 10; i++)
            {
                dgvdt.Rows.Add($"row {i}");
            }

            this.Controls.Add(btn);
            btn.Location = new Point(5, dgv.Location.Y + dgv.Height + 5);
            btn.Text = "Click me";
            btn.Click += Btn_Click;

        }

        private void Btn_Click(object sender, EventArgs e)
        {
            dgvdt.WriteXml(@"c:\temp\mydtxml.xml");
        }
    }
}

Here's another snippet where my DataSource is not already a DataTable.

using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace DataGridViewToXML_47696565
{
    public partial class Form2 : Form
    {
        BindingList<dgventry> dgvdata = new BindingList<dgventry>();
        DataGridView dgv = new DataGridView();
        Button btn = new Button();

        public Form2()
        {
            InitializeComponent();
            initOurStuff();
        }

        private void initOurStuff()
        {
            dgv.Dock = DockStyle.Top;
            dgv.DataSource = dgvdata;
            this.Controls.Add(dgv);

            for (int i = 0; i < 10; i++)
            {
                dgvdata.Add(new dgventry { col1 = $"col1 row{i}", col2 = $"col2 row{i}", col3 = $"col3 row{i}" });
            }

            this.Controls.Add(btn);
            btn.Location = new Point(5, dgv.Location.Y + dgv.Height + 5);
            btn.Text = "Click me";
            btn.Click += Btn_Click; ;
        }

        private void Btn_Click(object sender, EventArgs e)
        {

            /*The DataSource connected to the DGV is not already a DataTable,
             so I'll traverse the DataGridView and create my own DataTable out of it*/
            DataTable dt = new DataTable();//create the data table
            dt.TableName = "SD";//give it a name
            //create the appropriate number of columns
            for (int i = 0; i < dgv.Columns.Count; i++)
            {
                dt.Columns.Add(dgv.Columns[i].HeaderText);
            }

            //loop through each row of the DataGridView
            foreach (DataGridViewRow currentRow in dgv.Rows)
            {
                dt.Rows.Add();
                int runningCount = 0;
                //loop trough each column of the row
                foreach (DataGridViewCell item in currentRow.Cells)
                {
                    dt.Rows[dt.Rows.Count - 1][runningCount] = item.FormattedValue;
                    runningCount++;
                }
            }

            if (dt != null)
            {
                dt.WriteXml(@"c:\temp\mynewxml.xml");
            }

        }
    }

    public class dgventry
    {
        public string col1 { get; set; }
        public string col2 { get; set; }
        public string col3 { get; set; }
    }
}

Here's another snippet. In this one, the DataGridView starts empty. The user has to manually enter data into it.

using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace DataGridViewToXML_47696565
{
    public partial class Form3 : Form
    {

        DataGridView dgv = new DataGridView();
        Button btn = new Button();

        public Form3()
        {
            InitializeComponent();
            initOurStuff();
        }

        private void initOurStuff()
        {
            dgv.Dock = DockStyle.Top;
            this.Controls.Add(dgv);
            for (int i = 0; i < 10; i++)
            {
                DataGridViewColumn newcol = new DataGridViewTextBoxColumn();
                newcol.Name = $"col{i}";
                dgv.Columns.Add(newcol);
            }

            this.Controls.Add(btn);
            btn.Location = new Point(5, dgv.Location.Y + dgv.Height + 5);
            btn.Text = "Click me";
            btn.Click += Btn_Click; ;
        }

        private void Btn_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();//create the data table
            dt.TableName = "SD";//give it a name
            //create the appropriate number of columns
            for (int i = 0; i < dgv.Columns.Count; i++)
            {
                dt.Columns.Add(dgv.Columns[i].HeaderText);
            }

            //loop through each row of the DataGridView
            foreach (DataGridViewRow currentRow in dgv.Rows)
            {
                dt.Rows.Add();
                int runningCount = 0;
                //loop trough each column of the row
                foreach (DataGridViewCell item in currentRow.Cells)
                {
                    dt.Rows[dt.Rows.Count - 1][runningCount] = item.FormattedValue;
                    runningCount++;
                }
            }

            if (dt != null)
            {
                dt.WriteXml(@"c:\temp\mynewxml.xml");
            }
        }
    }
}


问:
Regarding User control design for win apps c#
i want to design a user control in win application such a way that when i drag & drop that user control on form it will just place at the top of the form just like menu control. so please tell me what extra code i need to add in my user control.

thanks

答:
Set the Dock property to Top

https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-6165908.html

ContentLicense: CC BY-SA 2.5


问:
Apple Music Offline Files Have no URL?
It seems that the property MPMediaItemPropertyAssetURL on a MPMediaItem returns null when the file is one that was from Apple Music and has been made "available offline".

On the other hand, items from my original library which I uploaded to iTunes match/apple music and then make available offline don't seem to have this problem.

Is this a bug? Have I done something wrong? Anyone having similar issues?

答:
Things have changed a little and this isn't true anymore. MPMediaItemPropertyAssetURL is not nil on iOS 11 for songs saved offline via Apple Music but AVPlayer is unable to play them since they are still DRM protected. The same song returns MPMediaItemPropertyAssetURL nil on iOS 9.

If you are interested in checking for DRM protected songs or in playing such songs, you can read my detailed answer here: https://stackoverflow.com/a/47694472/4331787

Title: Apple Music Offline Files Have no URL?


问:
webpack failing to import npm package
I've got a very simple webpack config

```<code>const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: "./scripts/app.ts",
  output: {
    filename: "./www/scripts/appBundle.js",
  },
  resolve: {
    extensions: [".ts", ".js"]
  },
  devServer: {
    contentBase: './www'
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: [
          {
            loader: "ts-loader",
            options: {
              configFile: "scripts/tsconfig.json"
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './www/index.ejs'
    })
  ],
  devtool: "source-map"
};
</code>```

I'm importing an npm package (nouislider), build works fine but when I run the app I get an error (noUiSlider is undefined).

I've set up a debug on chrome to try and find out what's happening - when I inspect the import I see an error - ReferenceError: noUiSlider is not defined at eval but when I inspect the actual execution line the debugger does recognize the import.

The execution still fails as the import is not recognized.

So far I've tried to add the babel-loader thinking it might be failing there, but I'm getting the same error.

Any idea what I'm missing?

答:
Just a guess but you might have not installed this npm module?

could you try running:

```<code>npm install html-webpack-plugin --save-dev
</code>```

Title: webpack failing to import npm package

Body:
I've got a very simple webpack config

const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: "./scripts/app.ts",
  output: {
    filename: "./www/scripts/appBundle.js",
  },
  resolve: {
    extensions: [".ts", ".js"]
  },
  devServer: {
    contentBase: './www'
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: [
          {
            loader: "ts-loader",
            options: {
              configFile: "scripts/tsconfig.json"
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './www/index.ejs'
    })
  ],
  devtool: "source-map"
};

I'm importing an npm package (nouislider), build works fine but when I run the app I get an error (noUiSlider is undefined).

I've set up a debug on chrome to try and find out what's happening - when I inspect the import I see an error - ReferenceError: noUiSlider is not defined at eval but when I inspect the actual execution line the debugger does recognize the import.

The execution still fails as the import is not recognized.

So far I've tried to add the babel-loader thinking it might be failing there, but I'm getting the same error.

Any idea what I'm missing?

Body:
Just a guess but you might have not installed this npm module?

could you try running:

npm install html-webpack-plugin --save-dev


问:
Incorrect claim Type
I am currently working on an API.  The tokens are returned from an IdentityServer4.

I am trying to get back the sub id which is the id of the currently authorized user from the token claim.   I can see it in the Claim here.

```<code>{
  "nbf": 1512632838,
  "exp": 1512636438,
  "iss": "http://localhost:5000",
  "aud": [
    "http://localhost:5000/resources",
    "testapi"
  ],
  "client_id": "ServiceAccountAccess",
  "sub": "21248582",
  "auth_time": 1512632823,
  "idp": "local",
  "name": "TestUser",
  "resource_id": "21260601",
  "xena_fiscal_id": "21875",
  "fiscal_name": "My company",
  "picture_url": "/Content/images/avatar-company-xena.jpg",
  "application_id": "16140911",
  "scope": [
    "openid",
    "profile",
    "testapi"
  ],
  "amr": [
    "password"
  ]
}
</code>```

My API call is quite simple

```<code>    [Authorize]
    public async Task<ActionResult> ChangeFiscal([FromBody] long fiscalId)
    {

        var name = User.Claims.Where(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier")
            .Select(c => c.Value).SingleOrDefault();

    }
</code>```

What i cant understand is why sub or subject is being turned into

"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"

I can see from the api that its done it to quite a few of the claims

```<code>{
  "nbf": 1512653706,
  "exp": 1512657306,
  "iss": "http://localhost:5000",
  "aud": [
    "http://localhost:5000/resources",
    "testapi"
  ],
  "client_id": "ServiceAccountAccess",
  "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier": "21248582",
  "auth_time": 1512652100,
  "http://schemas.microsoft.com/identity/claims/identityprovider": "local",
  "name": "TestUser",
  "supporter": "21248582",
  "http://schemas.microsoft.com/claims/authnmethodsreferences": "password",
  "resource_id": "21527443",
  "xena_fiscal_id": "21876",
  "fiscal_name": "this",
  "picture_url": "/Content/images/avatar-company-xena.jpg",
  "scope": [
    "openid",
    "profile",
    "testapi"
  ]
}
</code>```

答:
Its taken an hour to figure out that the Microsoft JWT handler turns these standard claims into Microsoft proprietary ones.

By adding the following line to the startup Configure method i was able to turn off this annoying "feature"

```<code>JwtSecurityTokenHandler.InboundClaimTypeMap.Clear()
</code>```

Title: Incorrect claim Type

Body:
I am currently working on an API.  The tokens are returned from an IdentityServer4.

I am trying to get back the sub id which is the id of the currently authorized user from the token claim.   I can see it in the Claim here.

{
  "nbf": 1512632838,
  "exp": 1512636438,
  "iss": "http://localhost:5000",
  "aud": [
    "http://localhost:5000/resources",
    "testapi"
  ],
  "client_id": "ServiceAccountAccess",
  "sub": "21248582",
  "auth_time": 1512632823,
  "idp": "local",
  "name": "TestUser",
  "resource_id": "21260601",
  "xena_fiscal_id": "21875",
  "fiscal_name": "My company",
  "picture_url": "/Content/images/avatar-company-xena.jpg",
  "application_id": "16140911",
  "scope": [
    "openid",
    "profile",
    "testapi"
  ],
  "amr": [
    "password"
  ]
}

My API call is quite simple

    [Authorize]
    public async Task<ActionResult> ChangeFiscal([FromBody] long fiscalId)
    {

        var name = User.Claims.Where(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier")
            .Select(c => c.Value).SingleOrDefault();

    }

What i cant understand is why sub or subject is being turned into

"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"

I can see from the api that its done it to quite a few of the claims

{
  "nbf": 1512653706,
  "exp": 1512657306,
  "iss": "http://localhost:5000",
  "aud": [
    "http://localhost:5000/resources",
    "testapi"
  ],
  "client_id": "ServiceAccountAccess",
  "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier": "21248582",
  "auth_time": 1512652100,
  "http://schemas.microsoft.com/identity/claims/identityprovider": "local",
  "name": "TestUser",
  "supporter": "21248582",
  "http://schemas.microsoft.com/claims/authnmethodsreferences": "password",
  "resource_id": "21527443",
  "xena_fiscal_id": "21876",
  "fiscal_name": "this",
  "picture_url": "/Content/images/avatar-company-xena.jpg",
  "scope": [
    "openid",
    "profile",
    "testapi"
  ]
}

Body:
Its taken an hour to figure out that the Microsoft JWT handler turns these standard claims into Microsoft proprietary ones.

By adding the following line to the startup Configure method i was able to turn off this annoying "feature"

JwtSecurityTokenHandler.InboundClaimTypeMap.Clear()


问:
Get specific container using lxc/lxd-list command
When I run the following command:

I get the following output:

But I only want to get the container specified in the command not all of them.

How can I do that?

答:
You can use POSIX Extended Regular Expressions:

```<code>lxc list -c n '^ubuntu$'

+--------+
|  NAME  |
+--------+
| ubuntu |
+--------+
</code>```

If you don't want the formatting just use the --format csv switch, which will output just ubuntu

Body:
You can use POSIX Extended Regular Expressions:

lxc list -c n '^ubuntu$'

+--------+
|  NAME  |
+--------+
| ubuntu |
+--------+

If you don't want the formatting just use the --format csv switch, which will output just ubuntu


问:
How does git reset <filename> work?
There are 2 statements about git reset that are true but I find them contradictory given my limited knowledge of how Git works.

Is there a way to reconcile the 2 statements?

Statement 1:
Git reset file1 will un-add file1 from the staging area.

This is the command to use when you added file1 to staging and you changed your mind and want to remove it from the staging area.

Statement 2:
Git reset file1 will copy files from HEAD to the staging area.

According to statement 2, git reset adds files to the staging area.

So how do the files become removed from the staging area when they were just copied to it from HEAD?

答:
How does git reset  work?

Lets take an example :-

We added octodog.txt into our family octofamily

```<code>git add octofamily/octodog.txtcode
</code>```

So now that octodog is part of the family, octocat (our previous file) is all depressed.

Since we love octocat more than octodog, we'll turn his frown around by removing octodog.txt

You can unstage files by using the git reset command. Go ahead and remove octofamily/octodog.txt.

```<code>git reset octofamily/octodog.txt
</code>```

git reset did a great job of unstaging octodog.txt, but you'll notice that he's still there. He's just not staged anymore. It would be great if we could go back to how things were before octodog came around and ruined the party.

Files can be changed back to how they were at the last commit by using the command:

git checkout -- <target>

Go ahead and get rid of all the changes since the last commit for octocat.txt

```<code>git checkout -- octocat.txt
</code>```

for further reference and git knowledge here is one git game

hope it will clear your all git related doubt's :)

Title: How does git reset <filename> work?

Body:
How does git reset  work?

Lets take an example :-

We added octodog.txt into our family octofamily

git add octofamily/octodog.txtcode

So now that octodog is part of the family, octocat (our previous file) is all depressed.

Since we love octocat more than octodog, we'll turn his frown around by removing octodog.txt

You can unstage files by using the git reset command. Go ahead and remove octofamily/octodog.txt.

git reset octofamily/octodog.txt

git reset did a great job of unstaging octodog.txt, but you'll notice that he's still there. He's just not staged anymore. It would be great if we could go back to how things were before octodog came around and ruined the party.

Files can be changed back to how they were at the last commit by using the command:

git checkout -- <target>

Go ahead and get rid of all the changes since the last commit for octocat.txt

git checkout -- octocat.txt

for further reference and git knowledge here is one git game

hope it will clear your all git related doubt's :)


问:
LuaJit predefine struct
I'm trying to make some structs that are dependant on each other in Lua like so. But I'm having problems doing it. Is there anyway I can predefine Foo as an empty struct and define it afterwards?

Thanks.

```<code>ffi.cdef[[
    typedef struct {
        Foo* foo;
    } Bar;
]]

ffi.cdef[[
    typedef struct {
        Bar* bar;
    } Foo;
]]
</code>```

答:
This is not a problem specific of LuaJIT and the FFI but how to declare interdependent data structures and functions in C.

C requires that a function has been defined before using it. For instance:

```<code>int foo() {
    bar();
}

int bar() {
    return 42;
}
</code>```

To solve this issue is necessary to declare function bar() at the beginning of the file. The behavior of the function can be defined later.

```<code>int bar();

int foo() {
    bar();
}

int bar() {
    return 42;
}
</code>```

Similarly, you need to declare Foo before using it in Bar. Also notice it's possible to put all the C definitions in the same block.

```<code>ffi.cdef[[
   typedef struct Foo Foo;

   typedef struct {
      Foo* Foo;
   } Bar;

   typedef struct {
      Bar* bar;
   } Foo;
]]
</code>```

Title: LuaJit predefine struct

Body:
I'm trying to make some structs that are dependant on each other in Lua like so. But I'm having problems doing it. Is there anyway I can predefine Foo as an empty struct and define it afterwards?

Thanks.

ffi.cdef[[
    typedef struct {
        Foo* foo;
    } Bar;
]]

ffi.cdef[[
    typedef struct {
        Bar* bar;
    } Foo;
]]

Body:
This is not a problem specific of LuaJIT and the FFI but how to declare interdependent data structures and functions in C.

C requires that a function has been defined before using it. For instance:

int foo() {
    bar();
}

int bar() {
    return 42;
}

To solve this issue is necessary to declare function bar() at the beginning of the file. The behavior of the function can be defined later.

int bar();

int foo() {
    bar();
}

int bar() {
    return 42;
}

Similarly, you need to declare Foo before using it in Bar. Also notice it's possible to put all the C definitions in the same block.

ffi.cdef[[
   typedef struct Foo Foo;

   typedef struct {
      Foo* Foo;
   } Bar;

   typedef struct {
      Bar* bar;
   } Foo;
]]


问:
Rails - Images API for quick Resizing? Something like Google App Engine's Images Python API
Google's app engine has this speedy image resizing api which appears to perform significantly faster than the rails paperclip resizing alternative.

Anyone know of any rails/heroku friend image resizing api's that could work with paperclip to be a faster resizing solution?

Thanks

答:
When you do images on heroku, you're usually storing them up on S3.

You can upload the file directly to S3, then use delayed job to process the file in the background. Your users will see a zippier/faster processing time.


问:
Proper Flag position over histogram bell curve
I am using histogram bell curve for a project, everything is working fine except flag position like given in picture.

Here is link of my jsfiddle https://jsfiddle.net/8q1t3mwb/4

```<code>var data = [1,2,3,4,5,6,7,8,9,10];

Highcharts.chart('container', {

    title: {
        text: 'Bell curve'
    },

    xAxis: [{
        title: { text: 'Data' }
    }, {
        title: { text: 'Bell curve' },
        opposite: true
    }],

    yAxis: [{
        title: { text: 'Data' }
    }, {
        title: { text: 'Bell curve' },
        opposite: true
    }],

    series: [{
        name: 'Bell curve',
        type: 'bellcurve',
        id:'dataseries',
        xAxis: 1,
        yAxis: 1,
        baseSeries: 1,
        zIndex: -1,
        color: {
            linearGradient: {
                x1: 0,
                y1: 0,
                x2: 1,
                y2: 0
            },
            stops: [
                [0, 'rgb(255, 255, 255)'],
                [1, 'rgb(200, 200, 255)']
            ]
        }
    }]
});
</code>```

See full code here, https://jsfiddle.net/8q1t3mwb/4

答:
You see the points where they currently are because your flags are on the scatter axis. If you turn on the scatter points, you will see that.

Therefore, if you set the following for the flag series:

```<code>{
  yAxis: 1,
  xAxis: 1,
  name: 'Pointer',
  type: 'flags',
  ...
}
</code>```

And adjust your x value according to the number on the bell curve you will be able to see the flag connected to the curve.

Working example: https://jsfiddle.net/ewolden/8q1t3mwb/6/

Body:
I am using histogram bell curve for a project, everything is working fine except flag position like given in picture.

Here is link of my jsfiddle https://jsfiddle.net/8q1t3mwb/4

var data = [1,2,3,4,5,6,7,8,9,10];

Highcharts.chart('container', {

    title: {
        text: 'Bell curve'
    },

    xAxis: [{
        title: { text: 'Data' }
    }, {
        title: { text: 'Bell curve' },
        opposite: true
    }],

    yAxis: [{
        title: { text: 'Data' }
    }, {
        title: { text: 'Bell curve' },
        opposite: true
    }],

    series: [{
        name: 'Bell curve',
        type: 'bellcurve',
        id:'dataseries',
        xAxis: 1,
        yAxis: 1,
        baseSeries: 1,
        zIndex: -1,
        color: {
            linearGradient: {
                x1: 0,
                y1: 0,
                x2: 1,
                y2: 0
            },
            stops: [
                [0, 'rgb(255, 255, 255)'],
                [1, 'rgb(200, 200, 255)']
            ]
        }
    }]
});

See full code here, https://jsfiddle.net/8q1t3mwb/4

Body:
You see the points where they currently are because your flags are on the scatter axis. If you turn on the scatter points, you will see that.

Therefore, if you set the following for the flag series:

{
  yAxis: 1,
  xAxis: 1,
  name: 'Pointer',
  type: 'flags',
  ...
}

And adjust your x value according to the number on the bell curve you will be able to see the flag connected to the curve.

Working example: https://jsfiddle.net/ewolden/8q1t3mwb/6/


问:
How to change font for the CodeMirror editor
I am trying to change font-family and font-size of my CodeMirror editor. I tried changing it by setting the according CSS attributes but it does not seem to work for me:

```<code>.codemirror-textarea {
    font-family: Arial, monospace;
    font-size: 16px;
}
</code>```

Do I have to import something in order to achieve this or might I have to edit the libraries CSS file directly? What am I doing wrong?

答:
Try setting the CSS on:

```<code>.CodeMirror {
font-family: Arial, monospace;
font-size: 16px;
}
</code>```

This selects the element that contains all the formatted code.

Body:
I am trying to change font-family and font-size of my CodeMirror editor. I tried changing it by setting the according CSS attributes but it does not seem to work for me:

.codemirror-textarea {
    font-family: Arial, monospace;
    font-size: 16px;
}

Do I have to import something in order to achieve this or might I have to edit the libraries CSS file directly? What am I doing wrong?

Body:
Try setting the CSS on:

.CodeMirror {
font-family: Arial, monospace;
font-size: 16px;
}

This selects the element that contains all the formatted code.


问:
Angular 2 Testing PrimeNG ConfirmationDialog
I'm writing jasmine unit test for following code:

```<code>this.confirmationService.confirm({
  message: 'Are you sure that you want to delete?',
  accept: () => {
   //some code to test
  }
});
</code>```

How I can fake clicking of Yes in the dialog, to test code inside
accept() function?

答:
In your template:

```<code><p-confirmDialog #confirmDialog header="Confirmation" icon="fa fa-question-circle" width="425"></p-confirmDialog>
</code>```

In your component:

```<code>@ViewChild('confirmDialog') confirmDialog: ConfirmDialog;
</code>```

then you're able to invoke confirmDialog.accept().

Body:
I'm writing jasmine unit test for following code:

this.confirmationService.confirm({
  message: 'Are you sure that you want to delete?',
  accept: () => {
   //some code to test
  }
});

How I can fake clicking of Yes in the dialog, to test code inside
accept() function?

Body:
In your template:

<p-confirmDialog #confirmDialog header="Confirmation" icon="fa fa-question-circle" width="425"></p-confirmDialog>

In your component:

@ViewChild('confirmDialog') confirmDialog: ConfirmDialog;

then you're able to invoke confirmDialog.accept().


答:
Not related  but remove NSObject until you are required

That is very simple thing you just need to think a bit

Create Object like this

```<code>var arr = [Country]()
</code>```

Now Loop your array of dictionary

```<code>  for dict in countries {
      // Condition required to check for type safety :)
        guard let name = dict["name"] as? String,
              let dialCode = dict["dial_code"] as? String,
              let code = dict["code"] as? String else {
              print("Something is not well")
             continue
         }
        let object = Country(name: name, dial_code:dialCode, code:code)
         arr.append(object)
    }

</code>```

That's it  You have converted array of dict to Custom Object

Hope it is helpful to you

Title: Convert Array of Dictionary to custom object swift

Body:
I have:

    let countries : [[String : Any]] = [
            [
                "name" : "Afghanistan",
                "dial_code": "+93",
                "code": "AF"
            ],
            [
                "name": "Aland Islands",
                "dial_code": "+358",
                "code": "AX"
            ],
            [
                "name": "Albania",
                "dial_code": "+355",
                "code": "AL"
            ],
            [
                "name": "Algeria",
                "dial_code": "+213",
                "code": "DZ"
            ]
]

I want to add all this array of dictionary to my custom object like

let country:[Country] = countries

My custom object looks like this:

class Country: NSObject {
        let name: String
        let dial_code : String
        let code: String

        init(name: String, dial_code: String, code: String) {
            self.name = name
            self.dial_code = dial_code
            self.code = code
        }
    }

I understand that I need a loop thru the array but idk what is the next step. Would be great to have an example.

Body:
Not related  but remove NSObject until you are required

That is very simple thing you just need to think a bit

Create Object like this

var arr = [Country]()

Now Loop your array of dictionary

  for dict in countries {
      // Condition required to check for type safety :)
        guard let name = dict["name"] as? String,
              let dialCode = dict["dial_code"] as? String,
              let code = dict["code"] as? String else {
              print("Something is not well")
             continue
         }
        let object = Country(name: name, dial_code:dialCode, code:code)
         arr.append(object)
    }

That's it  You have converted array of dict to Custom Object

Hope it is helpful to you

ContentLicense: CC BY-SA 4.0


问:
Fetching queries from MySQL and printing it in a javascript calendar
I have a hardcoded javascript calendar and I need to print the events from my database which is a PHP MySQL server side database. But I'm not sure how to fetch the queries from mysql and print it into the javascript calendar :/ I found something that makes use of VBSCRIPT but its very confusing :/ </p>

答:
The general outline:

Use PHP to access the database and fetch rows of calendar data (using a query). Then, print it out to a Javascript data structure like JSON or native Javascript that is loaded into the browser. Then, work with the Javascript calendar code to load the data into the view the browser presents to the user on the webpage.

There's a lot of variation that can occur here, but roughly (in semi-psuedo code):

Within page contains the calendar (outputs in JSON notation)

```<code><script type="text/javascript">
<?php

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');

$result = mysql_query('SELECT * FROM Events', $link);

$count = 0;

echo "var events = {";

while ($row = mysql_fetch_assoc($result)) {
    if ($count !== 0) echo ",";
    echo "{";
    echo "'eventid':'" . add_slashes($row['eventid']) . "',";
    echo "'title':'" . add_slashes($row['title']) . "',";
    echo "'description':'" . add_slashes($row['description']) . "',";
    echo "'date':'" . add_slashes($row['date']) . "',";
    echo "'time':'" . add_slashes($row['time']) . "'";
    echo "}";
    count++;
}

echo "};";

?>

$calendar = new Calendar(events);

</script>
</code>```

Of course, there are a number of ways that this could be done, but this is one way it could flow. This is only an example; dropping this code into a PHP page on a server will not work, it's only meant to demonstrate how in general it could flow.

Body:
The general outline:

Use PHP to access the database and fetch rows of calendar data (using a query). Then, print it out to a Javascript data structure like JSON or native Javascript that is loaded into the browser. Then, work with the Javascript calendar code to load the data into the view the browser presents to the user on the webpage.

There's a lot of variation that can occur here, but roughly (in semi-psuedo code):

Within page contains the calendar (outputs in JSON notation)

<script type="text/javascript">
<?php

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');

$result = mysql_query('SELECT * FROM Events', $link);

$count = 0;

echo "var events = {";

while ($row = mysql_fetch_assoc($result)) {
    if ($count !== 0) echo ",";
    echo "{";
    echo "'eventid':'" . add_slashes($row['eventid']) . "',";
    echo "'title':'" . add_slashes($row['title']) . "',";
    echo "'description':'" . add_slashes($row['description']) . "',";
    echo "'date':'" . add_slashes($row['date']) . "',";
    echo "'time':'" . add_slashes($row['time']) . "'";
    echo "}";
    count++;
}

echo "};";

?>

$calendar = new Calendar(events);

</script>

Of course, there are a number of ways that this could be done, but this is one way it could flow. This is only an example; dropping this code into a PHP page on a server will not work, it's only meant to demonstrate how in general it could flow.


问:
Error message when trying to compare data from Textbox to data from database
I'm trying to make a login page where I take the Password and Email from a SQL Server database. I want to compare the password and the Email.

```<code>private void buttoninloggen_Click(object sender, EventArgs e)
{
    using (SqlConnection connection = new SqlConnection(connectionstring))
    {
        connection.Open();

        string emailinlog = textBoxEmailLogin.Text;
        string passwordinlog = textBoxPasswordLogin.Text;
        string vergelijken = "select * from Account where Email = @email and Password = @password";

        SqlDataAdapter adapter = new SqlDataAdapter(vergelijken, connection);

        MessageBox.Show("tot hier is t goed");

        using (SqlCommand ophalen = new SqlCommand(vergelijken, connection))
        {
            ophalen.Parameters.AddWithValue("@email", emailinlog);
            ophalen.Parameters.AddWithValue("@password", passwordinlog);

            DataTable tafel = new DataTable();
            adapter.Fill(tafel);

            if (tafel.Rows.Count > 0)
            {
                MessageBox.Show("ingelogd");
            }
        }
    }
}
</code>```

I get this error message:

System.Data.SqlClient.SqlException: 'Must declare the scalar variable "@email".'

What am I doing wrong?

答:
Consider changing your syntax to the working code from my program:</p>

```<code>ophalen.Parameters.Add(new SqlParameter("@email", emailinlog));
</code>```

Body:
I'm trying to make a login page where I take the Password and Email from a SQL Server database. I want to compare the password and the Email.

private void buttoninloggen_Click(object sender, EventArgs e)
{
    using (SqlConnection connection = new SqlConnection(connectionstring))
    {
        connection.Open();

        string emailinlog = textBoxEmailLogin.Text;
        string passwordinlog = textBoxPasswordLogin.Text;
        string vergelijken = "select * from Account where Email = @email and Password = @password";

        SqlDataAdapter adapter = new SqlDataAdapter(vergelijken, connection);

        MessageBox.Show("tot hier is t goed");

        using (SqlCommand ophalen = new SqlCommand(vergelijken, connection))
        {
            ophalen.Parameters.AddWithValue("@email", emailinlog);
            ophalen.Parameters.AddWithValue("@password", passwordinlog);

            DataTable tafel = new DataTable();
            adapter.Fill(tafel);

            if (tafel.Rows.Count > 0)
            {
                MessageBox.Show("ingelogd");
            }
        }
    }
}

I get this error message:

System.Data.SqlClient.SqlException: 'Must declare the scalar variable "@email".'

What am I doing wrong?

Body:
Consider changing your syntax to the working code from my program:

ophalen.Parameters.Add(new SqlParameter("@email", emailinlog));


问:
Return the Worksheet that an Excel Chart is referencing using VBA
I need to be able to identify the worksheet that an excel chart (on a worksheet) is getting it's data from. I only need the data sheet which series 1 is referencing. I've started trying to extract the sheet name from .SeriesCollection(1).Formula but it gets realy complex. here's what I've got so far:

```<code>Sub GetChartDataSheet()

Dim DataSheetName As String
Dim DataSheet As Worksheet

DataSheetName = ActiveChart.SeriesCollection(1).Formula

DataSheetName = Left(DataSheetName, InStr(1, DataSheetName, "!$") - 1)
DataSheetName = WorksheetFunction.Replace(DataSheetName, 1, Len("=series("), "")
If Left(DataSheetName, 1) = "'" And Right(DataSheetName, 1) = "'" Then DataSheetName = Mid(DataSheetName, 2, Len(DataSheetName) - 2)
DataSheetName = Replace(DataSheetName, "''", "'")

Set DataSheet = Sheets(DataSheetName)

End Sub
</code>```

this works in a lot of cases, but if my users have a strange worksheet name (eg Sh'e e$,,t!3!$) it fails. the same goes if series 1 has been named (eg .SeriesCollection(1).Formula = "=SERIES(**"Hell,o !"**,'Sh''e e$,,t!3!$'!$B$2:$B$18,'Sh''e e$,,t!3!$'!$C$2:$C$18,1)".

Is there a simple way to solve this?

答:
I thought this is an easy one, turns out it's not. One of the cases where Excel has the information but will not give it away for free. I ended up with a function like this - maybe this helps:</p>

```<code>Function getSheetNameOfSeries(s As Series) As String

Dim f As String, i As Integer
Dim withQuotes As Boolean

' Skip leading comma if not all parts of series is filled. Check if sheetname is in single quotes
For i = 9 To Len(s.Formula)
    If Mid(s.Formula, i, 1) <> "," Then
        If Mid(s.Formula, i, 1) = "'" Then
            withQuotes = True
            f = Mid(s.Formula, i + 1)
        Else
            withQuotes = False
            f = Mid(s.Formula, i)
        End If
        Exit For
    End If
Next i

' "f" now contains a part of the formula with the sheetname as start
' now we search to the end of the sheet name.
' If name is in quotes, we are looking for the "closing" quote
' If not in quotes, we are looking for "!"
i = 1
Do While True

    If withQuotes Then
        ' Sheet name is in quotes, found closes quote --> we're done
        ' (but if next char is also a quote, we have the case the the sheet names contains a quote, so we have to continue working)
        If Mid(f, i, 1) = "'" Then
            If Mid(f, i + 1, 1) <> "'" Then
                getSheetNameOfSeries = Mid(f, 1, i - 1)
                Exit Do
            Else
                i = i + 1       ' Skip 2nd quote
            End If
        End If
    Else
        ' Sheet name is quite normal, so "!" will indicate the end of sheetname
        If Mid(f, i, 1) = "!" Then
            getSheetNameOfSeries = Mid(f, 1, i - 1)
            Exit Do
        End If
    End If

    i = i + 1
Loop

getSheetNameOfSeries = Replace(getSheetNameOfSeries, "''", "'")

End Function
</code>```

Body:
I need to be able to identify the worksheet that an excel chart (on a worksheet) is getting it's data from. I only need the data sheet which series 1 is referencing. I've started trying to extract the sheet name from .SeriesCollection(1).Formula but it gets realy complex. here's what I've got so far:

Sub GetChartDataSheet()

Dim DataSheetName As String
Dim DataSheet As Worksheet

DataSheetName = ActiveChart.SeriesCollection(1).Formula

DataSheetName = Left(DataSheetName, InStr(1, DataSheetName, "!$") - 1)
DataSheetName = WorksheetFunction.Replace(DataSheetName, 1, Len("=series("), "")
If Left(DataSheetName, 1) = "'" And Right(DataSheetName, 1) = "'" Then DataSheetName = Mid(DataSheetName, 2, Len(DataSheetName) - 2)
DataSheetName = Replace(DataSheetName, "''", "'")

Set DataSheet = Sheets(DataSheetName)

End Sub

this works in a lot of cases, but if my users have a strange worksheet name (eg Sh'e e$,,t!3!$) it fails. the same goes if series 1 has been named (eg .SeriesCollection(1).Formula = "=SERIES(**"Hell,o !"**,'Sh''e e$,,t!3!$'!$B$2:$B$18,'Sh''e e$,,t!3!$'!$C$2:$C$18,1)".

Is there a simple way to solve this?

Body:
I thought this is an easy one, turns out it's not. One of the cases where Excel has the information but will not give it away for free. I ended up with a function like this - maybe this helps:

Function getSheetNameOfSeries(s As Series) As String

Dim f As String, i As Integer
Dim withQuotes As Boolean

' Skip leading comma if not all parts of series is filled. Check if sheetname is in single quotes
For i = 9 To Len(s.Formula)
    If Mid(s.Formula, i, 1) <> "," Then
        If Mid(s.Formula, i, 1) = "'" Then
            withQuotes = True
            f = Mid(s.Formula, i + 1)
        Else
            withQuotes = False
            f = Mid(s.Formula, i)
        End If
        Exit For
    End If
Next i

' "f" now contains a part of the formula with the sheetname as start
' now we search to the end of the sheet name.
' If name is in quotes, we are looking for the "closing" quote
' If not in quotes, we are looking for "!"
i = 1
Do While True

    If withQuotes Then
        ' Sheet name is in quotes, found closes quote --> we're done
        ' (but if next char is also a quote, we have the case the the sheet names contains a quote, so we have to continue working)
        If Mid(f, i, 1) = "'" Then
            If Mid(f, i + 1, 1) <> "'" Then
                getSheetNameOfSeries = Mid(f, 1, i - 1)
                Exit Do
            Else
                i = i + 1       ' Skip 2nd quote
            End If
        End If
    Else
        ' Sheet name is quite normal, so "!" will indicate the end of sheetname
        If Mid(f, i, 1) = "!" Then
            getSheetNameOfSeries = Mid(f, 1, i - 1)
            Exit Do
        End If
    End If

    i = i + 1
Loop

getSheetNameOfSeries = Replace(getSheetNameOfSeries, "''", "'")

End Function


问:
How to access popup elements using Selenium in Java
I am trying to get and access the elements from a pop-up/alert using selenium in java. Here is the code:

```<code>import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Test {

public static void main(String[] args) throws InterruptedException {

    System.setProperty("webdriver.gecko.driver", "path_to_gecko_driver");

    FirefoxDriver firefoxDriver = new FirefoxDriver();

    firefoxDriver.get("some_url_which_needs_webcam_and_microphone");
    WebElement element = new WebDriverWait(firefoxDriver, 20).until(ExpectedConditions.presenceOfElementLocated(new By.ByClassName("button_id")));
    element.click();

    JavascriptExecutor js = (JavascriptExecutor) firefoxDriver;
    String title = String.valueOf(js.executeScript("return document.title"));

    System.out.println("Title ==== " + title);

    Object rezult = js.executeScript("return document.getElementById(\'nav-bar\')");
    System.out.println("Browser element ==== " + rezult); //===>null

    System.out.println("FINISH");

    }
}
</code>```

I am trying to access the browser pop-up elements, so I can choose between the available webcams or microphones and allow or deny the access. The JS code works just fine in the browser's console, but not in Java.

Any time I try to access any element in Java by using the JavascriptExecutor the element is null.

How can I access the pop-up elements by using the JavascriptExecutor in Java? Are there any other predefined configs or any other prerequisites that I am missing? Thank you

答:
As you are invoking click() prior to this action we should induce WebDriverWait for the WebElement identified as getElementById('nav-bar') to render properly through ExpectedConditions.elementToBeClickable and try the following :

```<code>js.executeScript("return document.getElementById('nav-bar')");
</code>```

Body:
I am trying to get and access the elements from a pop-up/alert using selenium in java. Here is the code:

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Test {

public static void main(String[] args) throws InterruptedException {

    System.setProperty("webdriver.gecko.driver", "path_to_gecko_driver");

    FirefoxDriver firefoxDriver = new FirefoxDriver();

    firefoxDriver.get("some_url_which_needs_webcam_and_microphone");
    WebElement element = new WebDriverWait(firefoxDriver, 20).until(ExpectedConditions.presenceOfElementLocated(new By.ByClassName("button_id")));
    element.click();

    JavascriptExecutor js = (JavascriptExecutor) firefoxDriver;
    String title = String.valueOf(js.executeScript("return document.title"));

    System.out.println("Title ==== " + title);

    Object rezult = js.executeScript("return document.getElementById(\'nav-bar\')");
    System.out.println("Browser element ==== " + rezult); //===>null

    System.out.println("FINISH");

    }
}

I am trying to access the browser pop-up elements, so I can choose between the available webcams or microphones and allow or deny the access. The JS code works just fine in the browser's console, but not in Java.

Any time I try to access any element in Java by using the JavascriptExecutor the element is null.

How can I access the pop-up elements by using the JavascriptExecutor in Java? Are there any other predefined configs or any other prerequisites that I am missing? Thank you

Body:
As you are invoking click() prior to this action we should induce WebDriverWait for the WebElement identified as getElementById('nav-bar') to render properly through ExpectedConditions.elementToBeClickable and try the following :

js.executeScript("return document.getElementById('nav-bar')");


问:
Outliner for java files
With the help of util::IDE library it is possible to create your own IDE features in Eclipse e.g. outliners or annotators. The documentation shows an example of how to do this for your own language. But how can this be done with Java files?

```<code>registerAnnotator("java", Tree (Tree t) { return t[@doc="Hello!"]; });
</code>```

I tried with above code as I thought I didn't have to register the java language. Or is still needed to create my own Java grammar?

Thanks in advance

答:
We did not wire contributions to the Java IDE in Eclipse indeed. That would be a nice feature request, however pretty hard to make happen since the JDT is so tangled and coupled with itself. </p>

<p>You could use the Java grammar in the library, which supports up to Java 6. It would need some extending for Java 8 and Java 9, and you could wire the builder as well using the M3 mapping to show error messages and warnings and such. This will also give you the opportunity to write your own outliner. </p>

Title: Outliner for java files

Body:
With the help of util::IDE library it is possible to create your own IDE features in Eclipse e.g. outliners or annotators. The documentation shows an example of how to do this for your own language. But how can this be done with Java files?

registerAnnotator("java", Tree (Tree t) { return t[@doc="Hello!"]; });

I tried with above code as I thought I didn't have to register the java language. Or is still needed to create my own Java grammar?

Thanks in advance

Body:
We did not wire contributions to the Java IDE in Eclipse indeed. That would be a nice feature request, however pretty hard to make happen since the JDT is so tangled and coupled with itself.

You could use the Java grammar in the library, which supports up to Java 6. It would need some extending for Java 8 and Java 9, and you could wire the builder as well using the M3 mapping to show error messages and warnings and such. This will also give you the opportunity to write your own outliner.


问:
Convert Array of Dictionary to custom object swift
I have:

```<code>    let countries : [[String : Any]] = [
            [
                "name" : "Afghanistan",
                "dial_code": "+93",
                "code": "AF"
            ],
            [
                "name": "Aland Islands",
                "dial_code": "+358",
                "code": "AX"
            ],
            [
                "name": "Albania",
                "dial_code": "+355",
                "code": "AL"
            ],
            [
                "name": "Algeria",
                "dial_code": "+213",
                "code": "DZ"
            ]
]
</code>```

I want to add all this array of dictionary to my custom object like

```<code>let country:[Country] = countries
</code>```

My custom object looks like this:

```<code>class Country: NSObject {
        let name: String
        let dial_code : String
        let code: String

        init(name: String, dial_code: String, code: String) {
            self.name = name
            self.dial_code = dial_code
            self.code = code
        }
    }
</code>```

I understand that I need a loop thru the array but idk what is the next step. Would be great to have an example.

答:
You can map the dictionary into the array. As a dictionary always returns an optional value for key (the value is not guaranteed to exist) you need a guard to make sure you proceed only if that is the case.

In this sample solution I throw if any of the values are not there - but this is really up to you to decide.

```<code>struct AnError: Error {}

do {
    let countryObjects: [Country] = try countries.map {
        guard let name = $0["name"] as? String,
              let dial_code = $0["dial_code"] as? String,
              let code = $0["code"] as? String else {throw AnError()}

        return Country(name: name, dial_code: dial_code, code: code)
    }
}
catch {
    //something went worng - handle the error
}
</code>```

Body:
You can map the dictionary into the array. As a dictionary always returns an optional value for key (the value is not guaranteed to exist) you need a guard to make sure you proceed only if that is the case.

In this sample solution I throw if any of the values are not there - but this is really up to you to decide.

struct AnError: Error {}

do {
    let countryObjects: [Country] = try countries.map {
        guard let name = $0["name"] as? String,
              let dial_code = $0["dial_code"] as? String,
              let code = $0["code"] as? String else {throw AnError()}

        return Country(name: name, dial_code: dial_code, code: code)
    }
}
catch {
    //something went worng - handle the error
}