问:
Osprey RAML Validation Error Handling
I am trying to custom handle response sent to caller due to RAML specification failure. At the moment my code does the following.

```<code>const cfg = require("./cfg");
const log = require('./logging');
const RAML = require('osprey');
const startMessage = "My Service started on port " + cfg.SERVER_PORT + " at " + cfg.API_MOUNT_POINT;

// start an express server
const start = x => {
  // server dependencies
  const fs = require('fs'),
  express = require('express'),
  app = express(),
  router = express.Router(),
  bodyParser = require('body-parser'),
  api = require('./api');

  RAML.loadFile(cfg.API_SPEC).then(_raml => {

    app.use(bodyParser.json({ extended: true }));
    // hide the useless "powered by express" header
    app.disable('x-powered-by');
    // RAML validation
    app.use(cfg.API_MOUNT_POINT, _raml);
    app.use(cfg.API_MOUNT_POINT, api);
  })
  .then(v => {
    app.listen(cfg.SERVER_PORT, function() {
        log.info(startMessage);
    });
  })
  .catch(e => log.error(e));
}
</code>```

This works well but the response sent to caller when validation fails is shown below.

```<code>{
  "errors": [
    {
      "type": "json",
      "dataPath": "redeemtype",
      "keyword": "required",
      "schema": true,
      "message": "Missing required property: redeemtype"
    }
  ],
  "stack": "BadRequestError: Request failed to validate against RAML definition\n    at createValidationError (/Volumes/Devel/dollardine/node_modules/osprey-method-handler/osprey-method-handler.js:735:14)\n    at ospreyJsonBody (/Volumes/Devel/dollardine/node_modules/osprey-method-handler/osprey-method-handler.js:448:21)\n    at handle (/Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:56:16)\n    at dispatch (/Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:39:20)\n    at next (/Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:37:24)\n    at jsonParser (/Volumes/Devel/dollardine/node_modules/body-parser/lib/types/json.js:94:7)\n    at handle (/Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:56:16)\n    at dispatch (/Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:39:20)\n    at middleware (/Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:41:16)\n    at /Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:10:16\n    at ospreyContentType (/Volumes/Devel/dollardine/node_modules/osprey-method-handler/osprey-method-handler.js:325:17)\n    at handle (/Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:56:16)\n    at dispatch (/Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:39:20)\n    at next (/Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:37:24)\n    at ospreyMethodHeader (/Volumes/Devel/dollardine/node_modules/osprey-method-handler/osprey-method-handler.js:262:12)\n    at handle (/Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:56:16)"
}
</code>```

This is great, but I do not want to send all this info to caller. I want just log it locally and just sent {"code": 400, "message": "Invalid input"}

How can I make osprey to give me ability to handle the error response?

答:
I found answer to my own question. In case anyone in future gets stuck here.

```<code>const start = x => {
  // server dependencies
  const fs = require('fs'),
  express = require('express'),
  app = express(),
  router = express.Router(),
  bodyParser = require('body-parser'),
    api = require('./api');

  const ramlConfig = {
    "server": {
      "notFoundHandler": false
    },
    "disableErrorInterception": true
  }

  osprey.loadFile(cfg.API_SPEC, ramlConfig).then(_raml => {

    app.use(bodyParser.json({ extended: true }));
    // hide the useless "powered by express" header
    app.disable('x-powered-by');
    // RAML validation
    app.use(cfg.API_MOUNT_POINT, _raml);
    app.use(customNotFoundHandler);
    app.use(ramlErrorChecker);

    app.use(cfg.API_MOUNT_POINT, api);
    //app.use(ramlErrorChecker);
  })
  .then(v => {
    app.listen(cfg.SERVER_PORT, function() {
        log.info(startMessage);
    });
  })
  .catch(e => log.error(e));
}

const ramlErrorChecker = (err, req, res, next) => {
  if (err) {
    log.error("RAML validation failed. Reason: " + err);
    res.status(400);
    return res.json(buildResponseJSON(400));
  }
  return next();
}

const customNotFoundHandler = (req, res, next) => {
  // Check for existence of the method handler.
  if (req.resourcePath) {
    return next()
  }
  res.status(404);
  return res.json({"message": "The path is not found"});
}
</code>```

The important part is ramlConfig which helps in putting some customisation. By setting "disableErrorInterception" to true, we are taking over the error handling which is much better for standardisation and most importantly hiding the fact the RAML is being used. Setting "notFoundHandler" to false means, the undeclared routes are reject gracefully instead of random html.

Title: Osprey RAML Validation Error Handling

Body:
I am trying to custom handle response sent to caller due to RAML specification failure. At the moment my code does the following.

const cfg = require("./cfg");
const log = require('./logging');
const RAML = require('osprey');
const startMessage = "My Service started on port " + cfg.SERVER_PORT + " at " + cfg.API_MOUNT_POINT;

// start an express server
const start = x => {
  // server dependencies
  const fs = require('fs'),
  express = require('express'),
  app = express(),
  router = express.Router(),
  bodyParser = require('body-parser'),
  api = require('./api');

  RAML.loadFile(cfg.API_SPEC).then(_raml => {

    app.use(bodyParser.json({ extended: true }));
    // hide the useless "powered by express" header
    app.disable('x-powered-by');
    // RAML validation
    app.use(cfg.API_MOUNT_POINT, _raml);
    app.use(cfg.API_MOUNT_POINT, api);
  })
  .then(v => {
    app.listen(cfg.SERVER_PORT, function() {
        log.info(startMessage);
    });
  })
  .catch(e => log.error(e));
}

This works well but the response sent to caller when validation fails is shown below.

{
  "errors": [
    {
      "type": "json",
      "dataPath": "redeemtype",
      "keyword": "required",
      "schema": true,
      "message": "Missing required property: redeemtype"
    }
  ],
  "stack": "BadRequestError: Request failed to validate against RAML definition\n    at createValidationError (/Volumes/Devel/dollardine/node_modules/osprey-method-handler/osprey-method-handler.js:735:14)\n    at ospreyJsonBody (/Volumes/Devel/dollardine/node_modules/osprey-method-handler/osprey-method-handler.js:448:21)\n    at handle (/Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:56:16)\n    at dispatch (/Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:39:20)\n    at next (/Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:37:24)\n    at jsonParser (/Volumes/Devel/dollardine/node_modules/body-parser/lib/types/json.js:94:7)\n    at handle (/Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:56:16)\n    at dispatch (/Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:39:20)\n    at middleware (/Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:41:16)\n    at /Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:10:16\n    at ospreyContentType (/Volumes/Devel/dollardine/node_modules/osprey-method-handler/osprey-method-handler.js:325:17)\n    at handle (/Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:56:16)\n    at dispatch (/Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:39:20)\n    at next (/Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:37:24)\n    at ospreyMethodHeader (/Volumes/Devel/dollardine/node_modules/osprey-method-handler/osprey-method-handler.js:262:12)\n    at handle (/Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:56:16)"
}

This is great, but I do not want to send all this info to caller. I want just log it locally and just sent {"code": 400, "message": "Invalid input"}

How can I make osprey to give me ability to handle the error response?

Body:
I found answer to my own question. In case anyone in future gets stuck here.

const start = x => {
  // server dependencies
  const fs = require('fs'),
  express = require('express'),
  app = express(),
  router = express.Router(),
  bodyParser = require('body-parser'),
    api = require('./api');

  const ramlConfig = {
    "server": {
      "notFoundHandler": false
    },
    "disableErrorInterception": true
  }

  osprey.loadFile(cfg.API_SPEC, ramlConfig).then(_raml => {

    app.use(bodyParser.json({ extended: true }));
    // hide the useless "powered by express" header
    app.disable('x-powered-by');
    // RAML validation
    app.use(cfg.API_MOUNT_POINT, _raml);
    app.use(customNotFoundHandler);
    app.use(ramlErrorChecker);

    app.use(cfg.API_MOUNT_POINT, api);
    //app.use(ramlErrorChecker);
  })
  .then(v => {
    app.listen(cfg.SERVER_PORT, function() {
        log.info(startMessage);
    });
  })
  .catch(e => log.error(e));
}

const ramlErrorChecker = (err, req, res, next) => {
  if (err) {
    log.error("RAML validation failed. Reason: " + err);
    res.status(400);
    return res.json(buildResponseJSON(400));
  }
  return next();
}

const customNotFoundHandler = (req, res, next) => {
  // Check for existence of the method handler.
  if (req.resourcePath) {
    return next()
  }
  res.status(404);
  return res.json({"message": "The path is not found"});
}

The important part is ramlConfig which helps in putting some customisation. By setting "disableErrorInterception" to true, we are taking over the error handling which is much better for standardisation and most importantly hiding the fact the RAML is being used. Setting "notFoundHandler" to false means, the undeclared routes are reject gracefully instead of random html.


来源: stackexchange

答:
Just use SUM AND GROUP BY

```<code>SELECT SUM(amount), Customer_No
from table
group by Customer_No
</code>```

ContentLicense: CC BY-SA 3.0

Title: Summing values for each in SQL

Body:
I have a table containing customer ledger entries, where every transaction amount is recorded (including charges and payments). I want to get the balance for each customer in a query probably using the sum function (The sum of the balances gives the balance).

How do i achieve it?

Here is some sample data (I have filtered for only one customer though I have thousands of them).

amount  Customer No.
-14,453.00  2709
-12,000.00  2709
-9,200.00   2709
-8,000.00   2709
-8,000.00   2709
-8,000.00   2709
-8,000.00   2709
-7,998.20   2709
-7,997.20   2709
-5,568.00   2709
-4,300.00   2709
-4,001.80   2709
-4,000.20   2709
-4,000.00   2709
-4,000.00   2709
-4,000.00   2709
-4,000.00   2709
-4,000.00   2709
-4,000.00   2709
-4,000.00   2709
-4,000.00   2709
-3,999.80   2709
-3,998.20   2709
-2,953.00   2709
-2,841.80   2709
-2,596.80   2709
-2,558.20   2709
-2,381.20   2709
-2,101.80   2709
-2,000.00   2709
-1,800.00   2709
-1,771.80   2709
-1,737.00   2709
-1,737.00   2709
-1,737.00   2709
-1,736.80   2709
-1,500.00   2709
-1,368.80   2709
-1,181.20   2709
-870    2709
-870    2709
-870    2709
-870    2709
-870    2709
-870    2709
-870    2709
-870    2709
-870    2709
-851.2  2709
-820    2709
-816.8  2709
-800    2709
-800    2709
-580    2709
-580    2709
-580    2709
-580    2709
-580    2709
-580    2709
-580    2709
-580    2709
-580    2709
-580    2709
-580    2709
-580    2709
-580    2709
-580    2709
-580    2709
-580    2709
-580    2709
-580    2709
-571.8  2709
-533.2  2709
-370    2709
-368.2  2709
-356.2  2709
-200    2709
-200    2709
-176.8  2709
-131.8  2709
-41.8   2709
-28.2   2709
-23.2   2709
-2.8    2709
-2.8    2709
-1.8    2709
-0.2    2709
1.8 2709
1.8 2709
2.8 2709
23.2    2709
131.8   2709
200 2709
200 2709
200 2709
368.2   2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
800 2709
820 2709
870 2709
870 2709
870 2709
870 2709
870 2709
870 2709
870 2709
870 2709
870 2709
870 2709
870 2709
870 2709
870 2709
1,160.00    2709
1,500.00    2709
1,737.00    2709
1,737.00    2709
1,737.00    2709
1,737.00    2709
1,737.00    2709
1,737.00    2709
1,800.00    2709
2,000.00    2709
2,101.80    2709
2,953.00    2709
2,953.00    2709
2,953.00    2709
2,953.00    2709
2,953.00    2709
2,953.00    2709
3,375.00    2709
3,375.00    2709
3,998.20    2709
4,000.00    2709
4,000.00    2709
4,000.00    2709
4,000.00    2709
4,000.00    2709
4,000.00    2709
4,000.00    2709
4,300.00    2709
5,568.00    2709
7,868.20    2709
7,976.80    2709
8,000.00    2709
8,000.00    2709
8,000.00    2709
8,000.00    2709
8,000.00    2709
8,000.00    2709
8,000.00    2709
9,200.00    2709
14,450.20   2709

Body:
Just use SUM AND GROUP BY

SELECT SUM(amount), Customer_No
from table
group by Customer_No


问:
Add values inside the Java while loop and stop it using a sentinel
I want to make a loop where the user inputs multiple values and when they want to stop input their values they input -1. I know it has to use a sentinel but I don't know how.</p>

```<code>Scanner myInput = new Scanner(System.in);
int total = 0;
int count = 0;

while(values >= 0)
{
    int values;
    total += values;
    count ++;

    System.out.println("Please input your value, type - 1 to stop entering values.");
    values = myInput.nextInt();
}

System.out.println ("The sum of all your values is " + total);
</code>```

答:
```<code>import java.util.Scanner;
class Demo{

    public static void main(String args[]){
                java.util.Scanner myInput = new java.util.Scanner(System.in);

                int total = 0; int count = 0;
                int values=0;

                while(values >= 0)

                {

                        total += values; count ++;

                        System.out.println("Please input your value, type - 1 to stop entering values."); values = myInput.nextInt();

                }

                System.out.println ("The sum of all your values is " + total);
        }

}
</code>```

Body:
I want to make a loop where the user inputs multiple values and when they want to stop input their values they input -1. I know it has to use a sentinel but I don't know how.

Scanner myInput = new Scanner(System.in);
int total = 0;
int count = 0;

while(values >= 0)
{
    int values;
    total += values;
    count ++;

    System.out.println("Please input your value, type - 1 to stop entering values.");
    values = myInput.nextInt();
}

System.out.println ("The sum of all your values is " + total);


问:
Cassini Error: "This type of page is not served"
I'm trying to use the Server class from Cassini to include a basic web server in my own application.  I just started playing around with it to get familiar with the way the server works and I setup a simple app that is as follows:

```<code>    static void Main(string[] args)
    {
        Server server = new Server(80, "/", @"C:\Projects\");
        server.Start();
        Console.ReadLine();
        server.Stop();
    }
</code>```

It lets me browse through the directories, however if I try to click on a file, a C# source file (*.cs) for example, it gives the following error:

Server Error in '/' Application.

This type of page is not served.

Description: The type of page you have
  requested is not served because it has
  been explicitly forbidden.  The
  extension '.cs' may be incorrect.

  Please review the URL below and make
  sure that it is spelled correctly.

I tried searching for that error text in the Cassini libraries, but didn't find anything.

Where is this error coming from?  How can I make it serve up any file?
I know it's meant to do asp.net and HTML, but I want it to also server up any file like a normal server would.

答:
.cs files and many source code types are prevented from rendering because they are handled by ASP.NET's forbidden file handler.

This is initially configured in the following setting in the master web.config in c:\windows\microsoft.net\v2.0.50727\CONFIG\web.config:

Look for in the <httpHandlers> section, you see settings like:

```<code><add path="*.cs" verb="*" type="System.Web.HttpForbiddenHandler" validate="True"/>
</code>```

Generally this is a good idea because it prevents casual browsing of your source code which may contain sensitive data such as connection strings.

You should be able to remove this restriction in your app's local web.config by doing:

```<code><configuration>
   <system.web>
      <httpHandlers>
         <remove verb="*" path="*.cs"/>
      </httpHandlers>
   </system.web>
</configuration>
</code>```

I probably wouldn't recommend doing this on a web facing production environment.

OwnerDisplayName: Adam Haile

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to use the Server class from Cassini to include a basic web server in my own application.  I just started playing around with it to get familiar with the way the server works and I setup a simple app that is as follows:

    static void Main(string[] args)
    {
        Server server = new Server(80, "/", @"C:\Projects\");
        server.Start();
        Console.ReadLine();
        server.Stop();
    }

It lets me browse through the directories, however if I try to click on a file, a C# source file (*.cs) for example, it gives the following error:

Server Error in '/' Application.

This type of page is not served.

Description: The type of page you have
  requested is not served because it has
  been explicitly forbidden.  The
  extension '.cs' may be incorrect.

  Please review the URL below and make
  sure that it is spelled correctly.

I tried searching for that error text in the Cassini libraries, but didn't find anything.

Where is this error coming from?  How can I make it serve up any file?
I know it's meant to do asp.net and HTML, but I want it to also server up any file like a normal server would.

Body:
.cs files and many source code types are prevented from rendering because they are handled by ASP.NET's forbidden file handler.

This is initially configured in the following setting in the master web.config in c:\windows\microsoft.net\v2.0.50727\CONFIG\web.config:

Look for in the <httpHandlers> section, you see settings like:

<add path="*.cs" verb="*" type="System.Web.HttpForbiddenHandler" validate="True"/>

Generally this is a good idea because it prevents casual browsing of your source code which may contain sensitive data such as connection strings.

You should be able to remove this restriction in your app's local web.config by doing:

<configuration>
   <system.web>
      <httpHandlers>
         <remove verb="*" path="*.cs"/>
      </httpHandlers>
   </system.web>
</configuration>

I probably wouldn't recommend doing this on a web facing production environment.

OwnerDisplayName: Kev

LastEditorDisplayName: Kev


问:
Find and take value of href using protractor
enter image description here

I had search and read many guides but it doesnot work. Could someone please help me? I want to get the href value like in the image. Thanks for reading my post.

答:
You can use getAttribute() method to get the value of any property available in the webelement. In your case you need to find the respective element and can use below code to get the href value,

```<code>element(by.css("a")).getAttribute("href").then(function(hrefValue){
  console.log("href value",hrefValue);
})
</code>```

Body:
You can use getAttribute() method to get the value of any property available in the webelement. In your case you need to find the respective element and can use below code to get the href value,

element(by.css("a")).getAttribute("href").then(function(hrefValue){
  console.log("href value",hrefValue);
})


问:
How to write user input 2D array?
I am new to java. Trying to make this into a user input 2D array which is 4*4. But when I try scanner, the row and col always got messed up.

```<code>public static void main(String[] args) {
        String array = "1 2 2 1,1 3 3 1,1 3 3 2,2 2 2 2";
        int[][] input = parseInt(array, 4, 4);
}
</code>```

And I also want the user input can output as:

```<code>1 2 2 1
1 3 3 1
1 3 3 2
2 2 2 2
</code>```

Appreciate for everybody's help!

答:
Use following method to convert array String in 2D array.</p>

```<code>int[][] parseInt(String array, int row, int col) {
    int[][] arr = new int[row][col];

    String[] rowStr = array.split(",");

    for (int i = 0; i < rowStr.length; i++) {
        String[] colStr = rowStr[i].split(" ");
        for (int j = 0; j < colStr.length; j++) {
            arr[i][j] = Integer.parseInt(colStr[j]);
        }
    }
    return arr;
}
</code>```

Title: How to write user input 2D array?

Body:
I am new to java. Trying to make this into a user input 2D array which is 4*4. But when I try scanner, the row and col always got messed up.

public static void main(String[] args) {
        String array = "1 2 2 1,1 3 3 1,1 3 3 2,2 2 2 2";
        int[][] input = parseInt(array, 4, 4);
}

And I also want the user input can output as:

1 2 2 1
1 3 3 1
1 3 3 2
2 2 2 2

Appreciate for everybody's help!

Body:
Use following method to convert array String in 2D array.

int[][] parseInt(String array, int row, int col) {
    int[][] arr = new int[row][col];

    String[] rowStr = array.split(",");

    for (int i = 0; i < rowStr.length; i++) {
        String[] colStr = rowStr[i].split(" ");
        for (int j = 0; j < colStr.length; j++) {
            arr[i][j] = Integer.parseInt(colStr[j]);
        }
    }
    return arr;
}


问:
Ruby loops style/convention
I'm wondering how I would create the following psuedo-esque code's conventional equivalent in Ruby. I've read quite a bit regarding standard practices but I'm just curious what the generally accepted/cleanest approach to this specific loop structure might be. I haven't come across a direct example.

```<code>for(i = 0, j = 10; i < 10 && j > 0; i++, j--){
  //do something
}
</code>```

Side note:
The intended purpose for this loop structure is to iterate through an array of arrays diagonally, the loop will contain a number of break-ing conditions.

答:
Not an exact equivalent, but the result is the same:

```<code>10.times do |i|
  j = 10 - i
  # do something
end
</code>```

Or

```<code>10.times.lazy.map{|i| [i, 10 - i]}.each do |i, j|
  # do something
end
</code>```

Either way you have a cleaner solution than @gates' because they don't leak i and j out of the block.

Or you can try a more functional approach just for fun :)

```<code>(λ = ->(i, j) {
  # do something
  λ.(i + 1, j - 1) if i < 9 and j > 1
}).(0, 10)
</code>```

But don't do this on large matrices, because Ruby doesn't optimize tail recursion thus may lead to stack overflow.

Title: Ruby loops style/convention

Body:
I'm wondering how I would create the following psuedo-esque code's conventional equivalent in Ruby. I've read quite a bit regarding standard practices but I'm just curious what the generally accepted/cleanest approach to this specific loop structure might be. I haven't come across a direct example.

for(i = 0, j = 10; i < 10 && j > 0; i++, j--){
  //do something
}

Side note:
The intended purpose for this loop structure is to iterate through an array of arrays diagonally, the loop will contain a number of break-ing conditions.

Body:
Not an exact equivalent, but the result is the same:

10.times do |i|
  j = 10 - i
  # do something
end

Or

10.times.lazy.map{|i| [i, 10 - i]}.each do |i, j|
  # do something
end

Either way you have a cleaner solution than @gates' because they don't leak i and j out of the block.

Or you can try a more functional approach just for fun :)

(λ = ->(i, j) {
  # do something
  λ.(i + 1, j - 1) if i < 9 and j > 1
}).(0, 10)

But don't do this on large matrices, because Ruby doesn't optimize tail recursion thus may lead to stack overflow.


问:
How to use variable from a while (foreach) statement in a query?
I have this first query

```<code> <?php
       while($empsheetpanel=mysqli_fetch_array($resultempsheets)){

 ?>
</code>```

Under that I have placed this second query in order to get data from the first query

```<code> <?php
 $sql="SELECT * From my_table WHERE id="$empsheetpanel['employee_id']" ";
 $result=mysqli_query($db,$sql);
 ?>
<?php } ;?>
</code>```

I know this is improper and incorrect. What's the correct syntax to retrieve the $empsheetpanel['employee_id'] from the first query?

答:
```<code>In your first query you can get your result like this:
Your Query:
<?php
while($empsheetpanel=mysqli_fetch_array($resultempsheets)){
?>

<?php
$sql="SELECT * From my_table WHERE id="$empsheetpanel['employee_id']" ";
$result=mysqli_query($db,$sql);
?>
<?php } ;?>

Response:
<?php
   $sql = "SELECT * From `my_table`";
   $resultempsheets = mysql_query($sql);
   while($empsheetpanel = mysqli_fetch_array($resultempsheets))
   {
      // put the array index beacuse you are using "mysqli_fetch_array". I am using index "0" here.
      echo $empsheetpanel[0];
      // if you are using "mysqli_fetch_assoc". you can use the filed name to get the value.
      $empsheetpanel['employee_id'];
   }
</code>```

<p>?></p>

```<code>   In your second query you are using the wrong ";" semicolon to terminate the script. you put after the variable define.
</code>```

Body:
I have this first query

 <?php
       while($empsheetpanel=mysqli_fetch_array($resultempsheets)){

 ?>

Under that I have placed this second query in order to get data from the first query

 <?php
 $sql="SELECT * From my_table WHERE id="$empsheetpanel['employee_id']" ";
 $result=mysqli_query($db,$sql);
 ?>
<?php } ;?>

I know this is improper and incorrect. What's the correct syntax to retrieve the $empsheetpanel['employee_id'] from the first query?

Body:
In your first query you can get your result like this:
Your Query:
<?php
while($empsheetpanel=mysqli_fetch_array($resultempsheets)){
?>

<?php
$sql="SELECT * From my_table WHERE id="$empsheetpanel['employee_id']" ";
$result=mysqli_query($db,$sql);
?>
<?php } ;?>

Response:
<?php
   $sql = "SELECT * From `my_table`";
   $resultempsheets = mysql_query($sql);
   while($empsheetpanel = mysqli_fetch_array($resultempsheets))
   {
      // put the array index beacuse you are using "mysqli_fetch_array". I am using index "0" here.
      echo $empsheetpanel[0];
      // if you are using "mysqli_fetch_assoc". you can use the filed name to get the value.
      $empsheetpanel['employee_id'];
   }

?>

   In your second query you are using the wrong ";" semicolon to terminate the script. you put after the variable define.


问:
Angular JS make value lower and check condition
I have value that might be upppercase or lowercase. I want to convert that to lower and compare and if that condition satisfies that it should show.

ie

```<code><div ng-if="test = 'Xyz'">show message</div>
</code>```

In this case  test is my model variable and its Xyz is the text. it can be XYZ or xyZ.

so I want every condition should satisfy.

Xyz value is fixed . it either XYZ,xYZ or XYZ all there conditions should be satisfy.

How it is possible?

答:
call a function from ng-if and return the lower case text from that function

```<code><div ng-if="test == lower('Xyz')">show message</div>

$scope.lower = function(text){
 return text.toLowerCase()
}
</code>```

Body:
I have value that might be upppercase or lowercase. I want to convert that to lower and compare and if that condition satisfies that it should show.

ie

show message

In this case  test is my model variable and its Xyz is the text. it can be XYZ or xyZ.

so I want every condition should satisfy.

Xyz value is fixed . it either XYZ,xYZ or XYZ all there conditions should be satisfy.

How it is possible?

Body:
call a function from ng-if and return the lower case text from that function

<div ng-if="test == lower('Xyz')">show message</div>

$scope.lower = function(text){
 return text.toLowerCase()
}


问:
App is Running But Not Opening in Browser? It shows Page Not Available
In console it shows message that app/server is running but when I open app in browser it show page not available.

Here's my code for the server initialization (app.js):

```<code>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var server = require('http').Server(app);
var io = require('socket.io')(server);
var app = express();

var viewRoute = require('./routes/view'),
    apiRoute = require('./routes/api');

app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', viewRoute);
app.use('/api', apiRoute);

server.listen(9190, function(){
    var host = server.address().address,
    port = server.address().port;
console.log("Server Running @ http:%s:%s", host, port);
});
</code>```

And my file with the routes (api.js):

```<code>var express = require('express');
var api = express.Router();

module.exports = (function() {
api.get('/', function(req, res, next) {
  console.log("GET Request for Index Page");
});

api.get('/home', function(req, res, next) {
  console.log("GET Request for Home Page");
});

return api;
})();
</code>```

I've already searched google and every other resources but can't find solution.

答: I also had same issue, My server was running but i was not able to open my app on browser, Uninstalling skype worked for me.

Body:
In console it shows message that app/server is running but when I open app in browser it show page not available.

Here's my code for the server initialization (app.js):

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var server = require('http').Server(app);
var io = require('socket.io')(server);
var app = express();

var viewRoute = require('./routes/view'),
    apiRoute = require('./routes/api');

app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', viewRoute);
app.use('/api', apiRoute);

server.listen(9190, function(){
    var host = server.address().address,
    port = server.address().port;
console.log("Server Running @ http:%s:%s", host, port);
});

And my file with the routes (api.js):

var express = require('express');
var api = express.Router();

module.exports = (function() {
api.get('/', function(req, res, next) {
  console.log("GET Request for Index Page");
});

api.get('/home', function(req, res, next) {
  console.log("GET Request for Home Page");
});

return api;
})();

I've already searched google and every other resources but can't find solution.


问:
Automatically update MySQL association table that has an auto increment foreign key
I have an application where a particular event updates my database with INSERTs to two tables A and B. There is an additional association/link table AB with foreign keys id_A, id_B to A and B that maps their many-to-many relationship. My question is how to best update AB when one of the foreign keys isn't known to the application logic (in this case because it is an AUTO_INCREMENT ID).

Additional details:

Only id_B is set to AUTO_INCREMENT, so its value is not known before the insert.

B is updated with a multi-row INSERT; A is a single row INSERT.

id_B is a unique key but there are possible duplicates which are handled by an ON DUPLICATE KEY UPDATE which replaces the old values with new ones.

A and B are updated in the same transaction in response to the same event.

MySQL 5.7 using InnoDB.

My idea was to include all the insert statements in a stored procedure where the final INSERT to AB would get the values for id_B from LAST_INSERT_ID() but apparently this will only return the value for the first row in a multi-row insert: https://dev.mysql.com/doc/refman/5.7/en/information-functions.html#function_last-insert-id

I suppose a bonus would be if the logic to update AB could be separated out into a trigger or a different statement from what is being used to update the parent tables.

Edit: response to comments.

答:
Before the statement(s) used to insert your data into A and B place the following statement...

```<code>SET @before = ( SELECT MAX( id_B ) AS maxIDB
                FROM B );
</code>```

This will find the largest value of id_B in B at this moment.  All subsequent insertions into B will have a larger value than this.  We can use this fact to our advantage.

After the above mentioned insert statement place the following statement...

```<code>INSERT INTO AB ( id_A,
                 id_B )
SELECT id_A_value,
       B.id_B
FROM B
WHERE B.id_B > @maxIDB;
</code>```

Note : By your above question I am assuming that id_A is known.  I am representing this value with id_A_value.

This statement will insert into AB rows containing the known value of id_A and all of the freshly generated values of id_B.

If you have any questions or comments, then please feel free to post a Comment accordingly.

Body:
Before the statement(s) used to insert your data into A and B place the following statement...

SET @before = ( SELECT MAX( id_B ) AS maxIDB
                FROM B );

This will find the largest value of id_B in B at this moment.  All subsequent insertions into B will have a larger value than this.  We can use this fact to our advantage.

After the above mentioned insert statement place the following statement...

INSERT INTO AB ( id_A,
                 id_B )
SELECT id_A_value,
       B.id_B
FROM B
WHERE B.id_B > @maxIDB;

Note : By your above question I am assuming that id_A is known.  I am representing this value with id_A_value.

This statement will insert into AB rows containing the known value of id_A and all of the freshly generated values of id_B.

If you have any questions or comments, then please feel free to post a Comment accordingly.


问:
PowerShell Regex - word with wildcards and commas
Trying to do a replace on what I understand to be a simple operation but hitting a wall.

I can replace a word with a comma on the end:

```<code>$firstval = 'ssonp,RDPNP,LanmanWorkstation,webclient,MfeEpePcNP,PRNetworkProvider'

($firstval) -replace 'webclient+,',''
</code>```

ssonp,RDPNP,LanmanWorkstation,MfeEpePcNP,PRNetworkProvider

But haven't been able to work out how to add a wildcard in the word, or how I'd have multiple words with wildcards proceeded by a comma, e.g.:

w* client+,* fee*, etc

(spaces added to stop being interpreted as formatting within the question)

Played with a few permeations and attempted to use examples from other questions without any luck.

答:
The -replace operator takes a regular expression as its first parameter.  You seem to be confusing wildcards and regular expressions.  Your pattern w*client+,*fee*,, though a valid regular expression, seems to be intended to use wildcards.

The regular expression equivalent of the * wildcard is .*, where . means "any character" and * means "0 or more occurrences".  Thus, the regular expression equivalent of w*client, would be w.*client,, and, similarly the regular expression equivalent of *fee*, would be .*fee.*,.  Since the string to be searched has comma-separated values, however, we don't want our patterns to include "any character" (.*) but rather "any character but comma" ([^,]*).  Therefore, the patterns to use become w[^,]*client, and [^,]*fee[^,]*,, respectively.

To search for both words in a string, separate the two patterns with |.  The following builds such a pattern and tests it against strings with a match  in various locations:

```<code># Match w*client or *fee*
$wordPattern = 'w[^,]*client|[^,]*fee[^,]*';
# Match $wordPattern and at most one comma before or after
$wordWithAdjacentCommaPattern = '({0}),?|,({0})$' -f $wordPattern;

"`$wordWithAdjacentCommaPattern: $wordWithAdjacentCommaPattern";
# Replace single value
'webclient', `
# Replace first value
'webclient,middle,last', `
# Replace middle value
'first,webclient,last', `
# Replace last value
'first,middle,webclient' `
    | ForEach-Object -Process { '"{0}" => "{1}"' -f $_, ($_ -replace $wordWithAdjacentCommaPattern); };
</code>```

This outputs the following:

```<code>$wordWithAdjacentCommaPattern: (w[^,]*client|[^,]*fee[^,]*),?|,(w[^,]*client|[^,]*fee[^,]*)$
"webclient" => ""
"webclient,middle,last" => "middle,last"
"first,webclient,last" => "first,last"
"first,middle,webclient" => "first,middle"
</code>```

A non-regex alternative you might consider would be to split your input string into individual values, filter out values that match certain wildcards, and reassemble what's left into comma-separated values:

```<code>(
    'ssonp,RDPNP,LanmanWorkstation,webclient,MfeEpePcNP,PRNetworkProvider' -split ',', -1, 'SimpleMatch' `
        | Where-Object { $_ -notlike 'w*client' -and $_ -notlike '*fee*'; } `
) -join ',';
</code>```

By the way, you used the regular expression webclient+, to match and remove the text webclient, from your string (looks like the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\NetworkProvider\Order\ProviderOrder registry value).  Just a note that, with the +, that will search for the literal text webclien followed by 1 or more occurrences of t followed by the literal text ,.  Thus, that will match webclientt,, webclienttt,, webclientttttttttt,, etc. as well webclient,.  If you are only interested in matching webclient, then you can just use the pattern webclient, (no +).

Body:
Trying to do a replace on what I understand to be a simple operation but hitting a wall.

I can replace a word with a comma on the end:

$firstval = 'ssonp,RDPNP,LanmanWorkstation,webclient,MfeEpePcNP,PRNetworkProvider'

($firstval) -replace 'webclient+,',''

ssonp,RDPNP,LanmanWorkstation,MfeEpePcNP,PRNetworkProvider

But haven't been able to work out how to add a wildcard in the word, or how I'd have multiple words with wildcards proceeded by a comma, e.g.:

w* client+,* fee*, etc

(spaces added to stop being interpreted as formatting within the question)

Played with a few permeations and attempted to use examples from other questions without any luck.

Body:
The -replace operator takes a regular expression as its first parameter.  You seem to be confusing wildcards and regular expressions.  Your pattern w*client+,*fee*,, though a valid regular expression, seems to be intended to use wildcards.

The regular expression equivalent of the * wildcard is .*, where . means "any character" and * means "0 or more occurrences".  Thus, the regular expression equivalent of w*client, would be w.*client,, and, similarly the regular expression equivalent of *fee*, would be .*fee.*,.  Since the string to be searched has comma-separated values, however, we don't want our patterns to include "any character" (.*) but rather "any character but comma" ([^,]*).  Therefore, the patterns to use become w[^,]*client, and [^,]*fee[^,]*,, respectively.

To search for both words in a string, separate the two patterns with |.  The following builds such a pattern and tests it against strings with a match  in various locations:

# Match w*client or *fee*
$wordPattern = 'w[^,]*client|[^,]*fee[^,]*';
# Match $wordPattern and at most one comma before or after
$wordWithAdjacentCommaPattern = '({0}),?|,({0})$' -f $wordPattern;

"`$wordWithAdjacentCommaPattern: $wordWithAdjacentCommaPattern";
# Replace single value
'webclient', `
# Replace first value
'webclient,middle,last', `
# Replace middle value
'first,webclient,last', `
# Replace last value
'first,middle,webclient' `
    | ForEach-Object -Process { '"{0}" => "{1}"' -f $_, ($_ -replace $wordWithAdjacentCommaPattern); };

This outputs the following:

$wordWithAdjacentCommaPattern: (w[^,]*client|[^,]*fee[^,]*),?|,(w[^,]*client|[^,]*fee[^,]*)$
"webclient" => ""
"webclient,middle,last" => "middle,last"
"first,webclient,last" => "first,last"
"first,middle,webclient" => "first,middle"

A non-regex alternative you might consider would be to split your input string into individual values, filter out values that match certain wildcards, and reassemble what's left into comma-separated values:

(
    'ssonp,RDPNP,LanmanWorkstation,webclient,MfeEpePcNP,PRNetworkProvider' -split ',', -1, 'SimpleMatch' `
        | Where-Object { $_ -notlike 'w*client' -and $_ -notlike '*fee*'; } `
) -join ',';

By the way, you used the regular expression webclient+, to match and remove the text webclient, from your string (looks like the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\NetworkProvider\Order\ProviderOrder registry value).  Just a note that, with the +, that will search for the literal text webclien followed by 1 or more occurrences of t followed by the literal text ,.  Thus, that will match webclientt,, webclienttt,, webclientttttttttt,, etc. as well webclient,.  If you are only interested in matching webclient, then you can just use the pattern webclient, (no +).


问:
error browser prevent my form - click submit button in ajax's success
I have a problem about browser block my submit form (submit in new tab) when i click submit button in ajax's success.

First: i used ajax to get my text translate into chinese and put the result to text field of this form. In Ajax's success function, i put $("my submit button").click(). then my form is not submit because browser block it :

Here is my form:

```<code>  <?php
    $catnews = CatNews::model()->findAll();
    echo CHtml::beginForm(['site/timkiemtaobao'], 'post', ['target' => '_blank']) . CHtml::textField('txtkeyword', '', ['placeholder' => 'Nhập theo sản phẩm, danh mục, hay nhãn hiệu tìm kiếm', 'class' => 'xx'])
        . CHtml::link('<img src="images/source/search.png">', 'javascript:void(0)', ['class' => 'btntim', 'id' => 'btntimkiem'])
        . CHtml::dropDownList('search', '', CHtml::listData($catnews, 'id', 'name'), ['class' => 'searchdrop']) ?>
    <div class="clearfix"></div>
    <?php echo CHtml::textField('stringtimkiem', "", ['class' => 'hidden']) . CHtml::button('1', ['class' => 'hidden', 'id' => 'subbtn']) . CHtml::endForm(); ?>
</code>```

And here is my js:

```<code>$(document).on('click', '#btntimkiem', function() { // this for translate to chinese
  if ($("#txtkeyword").val() != '') {
    var c = $("#txtkeyword").val();
    $.ajax({
      url: "https://translate.yandex.net/api/v1.5/tr.json/translate?key=myapikey",
      type: 'get',
      dataType: 'json',
      async: false,
      data: {
        text: c,
        lang: "vi-zh"
      },
      beforeSend: function() {
        $("#txtkeyword").attr('disabled', 'disabled');
        $("#btntimkiem").attr('disabled', 'disabled');
      },
      success: function(data) {
        console.log(data.text[0]);
        $("#stringtimkiem").val(data.text[0]);
        $("#subbtn").attr('type', 'submit').click().removeAttr('type');

      }
    });
    $("#txtkeyword").removeAttr('disabled');
    $("#btntimkiem").removeAttr('disabled');
  }
});
</code>```

So i'm very tired, because i have tried to fix it for 2 days but nothing is fixed.
i looking forward to your help. thank so much.

答:
If it occurs in a new tab, try to place your code to $(document).ready();
I strongly recommend you not to use async false flag. Do it async, then</p>

```<code>complete: $("#txtkeyword").removeAttr('disabled');
$("#btntimkiem").removeAttr('disabled');
</code>```

Body:
I have a problem about browser block my submit form (submit in new tab) when i click submit button in ajax's success.

First: i used ajax to get my text translate into chinese and put the result to text field of this form. In Ajax's success function, i put $("my submit button").click(). then my form is not submit because browser block it :

Here is my form:

  <?php
    $catnews = CatNews::model()->findAll();
    echo CHtml::beginForm(['site/timkiemtaobao'], 'post', ['target' => '_blank']) . CHtml::textField('txtkeyword', '', ['placeholder' => 'Nhập theo sản phẩm, danh mục, hay nhãn hiệu tìm kiếm', 'class' => 'xx'])
        . CHtml::link('', 'javascript:void(0)', ['class' => 'btntim', 'id' => 'btntimkiem'])
        . CHtml::dropDownList('search', '', CHtml::listData($catnews, 'id', 'name'), ['class' => 'searchdrop']) ?>

    <?php echo CHtml::textField('stringtimkiem', "", ['class' => 'hidden']) . CHtml::button('1', ['class' => 'hidden', 'id' => 'subbtn']) . CHtml::endForm(); ?>

And here is my js:

$(document).on('click', '#btntimkiem', function() { // this for translate to chinese
  if ($("#txtkeyword").val() != '') {
    var c = $("#txtkeyword").val();
    $.ajax({
      url: "https://translate.yandex.net/api/v1.5/tr.json/translate?key=myapikey",
      type: 'get',
      dataType: 'json',
      async: false,
      data: {
        text: c,
        lang: "vi-zh"
      },
      beforeSend: function() {
        $("#txtkeyword").attr('disabled', 'disabled');
        $("#btntimkiem").attr('disabled', 'disabled');
      },
      success: function(data) {
        console.log(data.text[0]);
        $("#stringtimkiem").val(data.text[0]);
        $("#subbtn").attr('type', 'submit').click().removeAttr('type');

      }
    });
    $("#txtkeyword").removeAttr('disabled');
    $("#btntimkiem").removeAttr('disabled');
  }
});

So i'm very tired, because i have tried to fix it for 2 days but nothing is fixed.
i looking forward to your help. thank so much.

Body:
If it occurs in a new tab, try to place your code to $(document).ready();
I strongly recommend you not to use async false flag. Do it async, then

complete: $("#txtkeyword").removeAttr('disabled');
$("#btntimkiem").removeAttr('disabled');


问:
How to access specific values along with single key from Javascript associate array using for in loop
here is the associative array with multiple values for single key

```<code>var course ={170:["Introduction to Programming"," Develop algorithms forcomputers",5],
250:[" Web Development","Build web applications",3]};
</code>```

I want to display key who have one of its value ==3
that is, 250:[" Web Development","Build web applications",3]};

using for in loop.
Thanks

答:
A generic approach

    var course ={170:["Introduction to Programming"," Develop algorithms forcomputers",5],
250:[" Web Development","Build web applications",3]};

    function printKey(value, arr) {
        for(var i in arr) {
            if(arr.hasOwnProperty(i) && arr[i].indexOf(value) > -1) {
                console.log(arr[i])
            }
        }
    }

    printKey(3, course);```

Body:
here is the associative array with multiple values for single key

var course ={170:["Introduction to Programming"," Develop algorithms forcomputers",5],
250:[" Web Development","Build web applications",3]};

I want to display key who have one of its value ==3
that is, 250:[" Web Development","Build web applications",3]};

using for in loop.
Thanks


问:
SSIS Derived Column Date Formats
I have a large data file that I am running through SSIS. Very simple XML source into a SQL database. I seldom use SSIS so I am far from an expert.

I have some records that I push into an error table because the dates are incorrect.

What I want to say is, if the date is not in a date format, then update this date to NULL.

I don't know if Derived Column is the way to go, but it appears it should be given examples I have been reading online.

I want to fix this issue in the SSIS stage, not in SQL after the data has been loaded in to the error tables.

答:
It is better to use a script component instead of using a derived column to achieve this because Scripts contains more options to manipulate dates.

If you want to check for specific dates formats you can use DateTime.TryParseExact() method or you use DateTime.TryParse() to try parsing date based on CultureInfo Date Formats.

First you have to add a Script component, mark the date column as input, create a new output column of type DT_DBTIMESTAMP

I will give two examples:
Assuming that the input Column name is inDate and the output column is outDate

DateTime.TryParseExact()

```<code>Dim strFormats() As String = {"dd/MM/yyyy HH:mm:ss", "yyyy-MM-dd HH:mm:ss", "yyyyMMdd HH:mm:ss", "dd-MMM-yyyy HH:mm:ss", "MM/dd/yyyy HH:mm:ss"}

Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)

    If Not Row.inDate_IsNull AndAlso
                 Not String.IsNullOrEmpty(Row.inDate) Then

        Dim dtTemp As DateTime

        If DateTime.TryParseExact(Row.inDate, strFormats, System.Globalization.CultureInfo.InvariantCulture, Globalization.DateTimeStyles.None, dtTemp) Then

            Row.outDate = dtTemp

        Else

            Row.outDate_IsNull = True

        End If

    End If
End Sub
</code>```

DateTime.TryParse()

```<code> Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)

    If Not Row.inDate_IsNull AndAlso
                 Not String.IsNullOrEmpty(Row.inDate) Then

        Dim dtTemp As DateTime

        If DateTime.TryParse(Row.inDate, System.Globalization.CultureInfo.InvariantCulture, Globalization.DateTimeStyles.None, dtTemp) Then

            Row.outDate = dtTemp

        Else

            Row.outDate_IsNull = True

        End If

    End If
End Sub
</code>```

you can read more about Datetime conversion using SSIS script component in this posts:

SSIS Source Format Implicit Conversion for Datetime

SSIS convert string date with various formats to DateTime

Title: SSIS Derived Column Date Formats

Body:
It is better to use a script component instead of using a derived column to achieve this because Scripts contains more options to manipulate dates.

If you want to check for specific dates formats you can use DateTime.TryParseExact() method or you use DateTime.TryParse() to try parsing date based on CultureInfo Date Formats.

First you have to add a Script component, mark the date column as input, create a new output column of type DT_DBTIMESTAMP

I will give two examples:
Assuming that the input Column name is inDate and the output column is outDate

DateTime.TryParseExact()

Dim strFormats() As String = {"dd/MM/yyyy HH:mm:ss", "yyyy-MM-dd HH:mm:ss", "yyyyMMdd HH:mm:ss", "dd-MMM-yyyy HH:mm:ss", "MM/dd/yyyy HH:mm:ss"}

Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)

    If Not Row.inDate_IsNull AndAlso
                 Not String.IsNullOrEmpty(Row.inDate) Then

        Dim dtTemp As DateTime

        If DateTime.TryParseExact(Row.inDate, strFormats, System.Globalization.CultureInfo.InvariantCulture, Globalization.DateTimeStyles.None, dtTemp) Then

            Row.outDate = dtTemp

        Else

            Row.outDate_IsNull = True

        End If

    End If
End Sub

DateTime.TryParse()

 Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)

    If Not Row.inDate_IsNull AndAlso
                 Not String.IsNullOrEmpty(Row.inDate) Then

        Dim dtTemp As DateTime

        If DateTime.TryParse(Row.inDate, System.Globalization.CultureInfo.InvariantCulture, Globalization.DateTimeStyles.None, dtTemp) Then

            Row.outDate = dtTemp

        Else

            Row.outDate_IsNull = True

        End If

    End If
End Sub

you can read more about Datetime conversion using SSIS script component in this posts:

SSIS Source Format Implicit Conversion for Datetime

SSIS convert string date with various formats to DateTime


问:
How to get an image from URL and put into NSArray?
I would like to get an image from an URL and put it into a NSArray, but doesn't work in the below codes, please help:

```<code>@interface DataViewController ()

@property (readonly, strong, nonatomic) NSArray *picData;

@end

@implementation DataViewController

- (void)viewDidLoad {

    NSString *imageUrlStringAA=@"http://aaa.net/AA.png";
    NSString *imageUrlStringBB=@"http://aaa.net/BB.png";

    NSURL *urlAA=[NSURL URLWithString:imageUrlStringAA];
    NSURL *urlBB=[NSURL URLWithString:imageUrlStringBB];

    NSData *dataAA=[[NSData alloc] initWithContentsOfURL:urlAA];
    NSData *dataBB=[[NSData alloc] initWithContentsOfURL:urlBB];

    UIImage *imageAA=[UIImage imageWithData:dataAA];
    UIImage *imageBB=[UIImage imageWithData:dataBB];

    _picData = [NSArray arrayWithObjects:imageAA, imageBB, nil];
</code>```

Any ideas is appreciated, thank you.

答:
First thing for download anything from http protocol then Add following diction in info.plist

And now try this code:

```<code>@interface DataViewController ()

@property (readonly, strong, nonatomic) NSArray *picData;

@end

@implementation DataViewController

- (void)viewDidLoad {
   NSString *imageUrlStringAA=@"http://www.hdwallpapers.in/download/antelope_canyon-360x640.jpg";
   NSString *imageUrlStringBB=@"http://www.hdwallpapers.in/download/vegeta_dragon_ball_super-360x640.jpg";

   NSURL *urlAA=[NSURL URLWithString:imageUrlStringAA];
   NSURL *urlBB=[NSURL URLWithString:imageUrlStringBB];

    NSData *dataAA=[[NSData alloc] initWithContentsOfURL:urlAA];
    NSData *dataBB=[[NSData alloc] initWithContentsOfURL:urlBB];

    UIImage *imageAA=[UIImage imageWithData:dataAA];
    UIImage *imageBB=[UIImage imageWithData:dataBB];
    _picData = [NSArray arrayWithObjects:imageAA, imageBB, nil];
}
</code>```

Body:
I would like to get an image from an URL and put it into a NSArray, but doesn't work in the below codes, please help:

@interface DataViewController ()

@property (readonly, strong, nonatomic) NSArray *picData;

@end

@implementation DataViewController

- (void)viewDidLoad {

    NSString *imageUrlStringAA=@"http://aaa.net/AA.png";
    NSString *imageUrlStringBB=@"http://aaa.net/BB.png";

    NSURL *urlAA=[NSURL URLWithString:imageUrlStringAA];
    NSURL *urlBB=[NSURL URLWithString:imageUrlStringBB];

    NSData *dataAA=[[NSData alloc] initWithContentsOfURL:urlAA];
    NSData *dataBB=[[NSData alloc] initWithContentsOfURL:urlBB];

    UIImage *imageAA=[UIImage imageWithData:dataAA];
    UIImage *imageBB=[UIImage imageWithData:dataBB];

    _picData = [NSArray arrayWithObjects:imageAA, imageBB, nil];

Any ideas is appreciated, thank you.

Body:
First thing for download anything from http protocol then Add following diction in info.plist

And now try this code:

@interface DataViewController ()

@property (readonly, strong, nonatomic) NSArray *picData;

@end

@implementation DataViewController

- (void)viewDidLoad {
   NSString *imageUrlStringAA=@"http://www.hdwallpapers.in/download/antelope_canyon-360x640.jpg";
   NSString *imageUrlStringBB=@"http://www.hdwallpapers.in/download/vegeta_dragon_ball_super-360x640.jpg";

   NSURL *urlAA=[NSURL URLWithString:imageUrlStringAA];
   NSURL *urlBB=[NSURL URLWithString:imageUrlStringBB];

    NSData *dataAA=[[NSData alloc] initWithContentsOfURL:urlAA];
    NSData *dataBB=[[NSData alloc] initWithContentsOfURL:urlBB];

    UIImage *imageAA=[UIImage imageWithData:dataAA];
    UIImage *imageBB=[UIImage imageWithData:dataBB];
    _picData = [NSArray arrayWithObjects:imageAA, imageBB, nil];
}


问:
Remove specific position page from page adapter that using layout.swipe
i have a problem here. Recently i am working on a project like tinder but it is not that advance. What i do is more simple.

There is a swipe page that can slide through different page. You can press like or dislike in each page.

What i want to do here is when they click on the like button, that page will be disappear and it will automatically go to the next page.

I had created the slide page with like and dislike button, but then problem now is

How can i make the like button onclick and that page will disappear and it will automatically go to the next page.

I'll attach my pager adapter below, hopefully someone can help me out.Please do let me know if you need more information.Many thanks in advance.

PagerAdapter

```<code>package com.example.lenovo.maidfriends;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;

import com.squareup.picasso.Picasso;

import java.util.ArrayList;

import static android.widget.Toast.LENGTH_SHORT;

/**
 * Created by lenovo on 8/3/2017.
 */

public class CustomAdapter extends PagerAdapter{
    Activity activity;
    ArrayList<ImageData> images = new ArrayList<>();
    LayoutInflater inflater;

    public CustomAdapter(Activity activity, ArrayList<ImageData> images){
        this.activity = activity;
        this.images = images;
    }

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

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view==object;
    }

    @Override
    public int getItemPosition(Object object) {
        // refresh all fragments when data set changed
        return PagerAdapter.POSITION_NONE;
    }

    @Override
    public Object instantiateItem(final ViewGroup container, final int position) {
        inflater = (LayoutInflater)activity.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View itemView = inflater.inflate(R.layout.swipe,container,false);

        ImageView image;
        image = (ImageView)itemView.findViewById(R.id.imageView);
        Button like;
        like = (Button) itemView.findViewById(R.id.button6);

        DisplayMetrics dis = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dis);
        int height = dis.heightPixels;
        int width = dis.widthPixels;
        image.setMinimumHeight(height);
        image.setMinimumWidth(width);

        final String url = images.get(position).getImageUrl();

        image.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                String clickedId = images.get(position).getId();
                // Do something with the selected image Id
                Intent intent=new Intent(view.getContext(),viewPersonal.class);
                Bundle b = new Bundle();
                b.putString("myID", clickedId);
                b.putString("myImage",url);
                intent.putExtras(b);
                view.getContext().startActivity(intent);
            }
        });

        like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Remove the current possition page and make next page to current page
            }
        });

        try{
            Picasso.with(activity.getApplicationContext())
                    .load(url)
                    .placeholder(R.mipmap.ic_launcher)
                    .error(R.mipmap.ic_launcher)
                    .into(image);
        }catch (Exception ex){

        }

        container.addView(itemView);
        return itemView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        ((ViewPager) container).removeView((View)object);
    }

}
</code>```

答:
Try like this</p>

```<code>images.remove(postion); // This will remove that current page in ViewPager
notifyDataSetChanged(); // This will reload viewpager
</code>```

Body:
i have a problem here. Recently i am working on a project like tinder but it is not that advance. What i do is more simple.

There is a swipe page that can slide through different page. You can press like or dislike in each page.

What i want to do here is when they click on the like button, that page will be disappear and it will automatically go to the next page.

I had created the slide page with like and dislike button, but then problem now is

How can i make the like button onclick and that page will disappear and it will automatically go to the next page.

I'll attach my pager adapter below, hopefully someone can help me out.Please do let me know if you need more information.Many thanks in advance.

PagerAdapter

package com.example.lenovo.maidfriends;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;

import com.squareup.picasso.Picasso;

import java.util.ArrayList;

import static android.widget.Toast.LENGTH_SHORT;

/**
 * Created by lenovo on 8/3/2017.
 */

public class CustomAdapter extends PagerAdapter{
    Activity activity;
    ArrayList<ImageData> images = new ArrayList<>();
    LayoutInflater inflater;

    public CustomAdapter(Activity activity, ArrayList<ImageData> images){
        this.activity = activity;
        this.images = images;
    }

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

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view==object;
    }

    @Override
    public int getItemPosition(Object object) {
        // refresh all fragments when data set changed
        return PagerAdapter.POSITION_NONE;
    }

    @Override
    public Object instantiateItem(final ViewGroup container, final int position) {
        inflater = (LayoutInflater)activity.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View itemView = inflater.inflate(R.layout.swipe,container,false);

        ImageView image;
        image = (ImageView)itemView.findViewById(R.id.imageView);
        Button like;
        like = (Button) itemView.findViewById(R.id.button6);

        DisplayMetrics dis = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dis);
        int height = dis.heightPixels;
        int width = dis.widthPixels;
        image.setMinimumHeight(height);
        image.setMinimumWidth(width);

        final String url = images.get(position).getImageUrl();

        image.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                String clickedId = images.get(position).getId();
                // Do something with the selected image Id
                Intent intent=new Intent(view.getContext(),viewPersonal.class);
                Bundle b = new Bundle();
                b.putString("myID", clickedId);
                b.putString("myImage",url);
                intent.putExtras(b);
                view.getContext().startActivity(intent);
            }
        });

        like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Remove the current possition page and make next page to current page
            }
        });

        try{
            Picasso.with(activity.getApplicationContext())
                    .load(url)
                    .placeholder(R.mipmap.ic_launcher)
                    .error(R.mipmap.ic_launcher)
                    .into(image);
        }catch (Exception ex){

        }

        container.addView(itemView);
        return itemView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        ((ViewPager) container).removeView((View)object);
    }

}

Body:
Try like this

images.remove(postion); // This will remove that current page in ViewPager
notifyDataSetChanged(); // This will reload viewpager


问:
Volley onErrorResponse Give NullPointerException
i try volley library in my android application

this is my log

```<code>    10-31 14:30:09.277: E/AndroidRuntime(22916): java.lang.NullPointerException
10-31 14:30:09.277: E/AndroidRuntime(22916):    at com.mypackage.api.Api$2.onErrorResponse(Api.java:269)
10-31 14:30:09.277: E/AndroidRuntime(22916):    at com.android.volley.Request.deliverError(Request.java:517)
10-31 14:30:09.277: E/AndroidRuntime(22916):    at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:101)
10-31 14:30:09.277: E/AndroidRuntime(22916):    at android.os.Handler.handleCallback(Handler.java:615)
10-31 14:30:09.277: E/AndroidRuntime(22916):    at android.os.Handler.dispatchMessage(Handler.java:92)
10-31 14:30:09.277: E/AndroidRuntime(22916):    at android.os.Looper.loop(Looper.java:137)
10-31 14:30:09.277: E/AndroidRuntime(22916):    at android.app.ActivityThread.main(ActivityThread.java:4745)
10-31 14:30:09.277: E/AndroidRuntime(22916):    at java.lang.reflect.Method.invokeNative(Native Method)
10-31 14:30:09.277: E/AndroidRuntime(22916):    at java.lang.reflect.Method.invoke(Method.java:511)
10-31 14:30:09.277: E/AndroidRuntime(22916):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
10-31 14:30:09.277: E/AndroidRuntime(22916):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-31 14:30:09.277: E/AndroidRuntime(22916):    at dalvik.system.NativeStart.main(Native Method)
</code>```

this is how i use volley

```<code>    GetStringRequest req = new GetStringRequest(Request.Method.GET,URL_API,
    new Response.Listener<String>() {
    // handle success response
    }, new Response.ErrorListener() {
    //handle error response
    @Override
public void onErrorResponse(VolleyError volleyError) {

    try {
        String error = new String(volleyError.networkResponse.data, HTTP.UTF_8);
        }
        catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
        e.printStackTrace();
        }
    });
</code>```

sometimes i get error nullPointerException at this line (269)

```<code>String error = new String(volleyError.networkResponse.data, HTTP.UTF_8);
</code>```

i don't know what is wrong, anyone know?

答:
Apply this code hope that this will help

@Override
public void onErrorResponse(VolleyError volleyError) {

```<code>  Log.v("VolleyError",volleyError.getMessage);

});
</code>```

This will print error in your log

Body:
i try volley library in my android application

this is my log

    10-31 14:30:09.277: E/AndroidRuntime(22916): java.lang.NullPointerException
10-31 14:30:09.277: E/AndroidRuntime(22916):    at com.mypackage.api.Api$2.onErrorResponse(Api.java:269)
10-31 14:30:09.277: E/AndroidRuntime(22916):    at com.android.volley.Request.deliverError(Request.java:517)
10-31 14:30:09.277: E/AndroidRuntime(22916):    at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:101)
10-31 14:30:09.277: E/AndroidRuntime(22916):    at android.os.Handler.handleCallback(Handler.java:615)
10-31 14:30:09.277: E/AndroidRuntime(22916):    at android.os.Handler.dispatchMessage(Handler.java:92)
10-31 14:30:09.277: E/AndroidRuntime(22916):    at android.os.Looper.loop(Looper.java:137)
10-31 14:30:09.277: E/AndroidRuntime(22916):    at android.app.ActivityThread.main(ActivityThread.java:4745)
10-31 14:30:09.277: E/AndroidRuntime(22916):    at java.lang.reflect.Method.invokeNative(Native Method)
10-31 14:30:09.277: E/AndroidRuntime(22916):    at java.lang.reflect.Method.invoke(Method.java:511)
10-31 14:30:09.277: E/AndroidRuntime(22916):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
10-31 14:30:09.277: E/AndroidRuntime(22916):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-31 14:30:09.277: E/AndroidRuntime(22916):    at dalvik.system.NativeStart.main(Native Method)

this is how i use volley

    GetStringRequest req = new GetStringRequest(Request.Method.GET,URL_API,
    new Response.Listener<String>() {
    // handle success response
    }, new Response.ErrorListener() {
    //handle error response
    @Override
public void onErrorResponse(VolleyError volleyError) {

    try {
        String error = new String(volleyError.networkResponse.data, HTTP.UTF_8);
        }
        catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
        e.printStackTrace();
        }
    });

sometimes i get error nullPointerException at this line (269)

String error = new String(volleyError.networkResponse.data, HTTP.UTF_8);

i don't know what is wrong, anyone know?

Body:
Apply this code hope that this will help

@Override
public void onErrorResponse(VolleyError volleyError) {

  Log.v("VolleyError",volleyError.getMessage);

});

This will print error in your log


问:
How to disable front ViewController's view when RearViewController's view is active SWRevealViewController in Swift 3.0
How to disable user's interaction with front view controller - namely with class ViewController in my case, when the rear menu is shown. With the current code, when rear menu is shown, bookCleaningButton is not disabled.

```<code>import UIKit
class ViewController: UIViewController, SWRevealViewControllerDelegate {

  @IBOutlet weak var menuButton: UIBarButtonItem!
  @IBOutlet weak var bookCleaningButton: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()
      self.revealViewController().rearViewRevealWidth = self.view.frame.width - 80

 //revela the menu if it is not nil
    if self.revealViewController() != nil {
        self.revealViewController().delegate = self
         menuButton.target = self.revealViewController()
           menuButton.action = #selector(SWRevealViewController.revealToggle(_:))
         self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()
    }
  }

func revealController(revealController: SWRevealViewController!, willMoveToPosition position: FrontViewPosition) {
    if revealController.frontViewPosition == FrontViewPosition.left {
        self.view.isUserInteractionEnabled = false
    }
    else {
        self.view.isUserInteractionEnabled = true
     }
  }
}
</code>```

答:
You should handle this in your Menu view controller rather. The reveal view controller has access to the frontViewController and that property can be used to set the userInteractionEnabled as false.

So, in your Menu View Controller write this this code in the viewWillAppear method:

```<code> override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.revealViewController().view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
    self.revealViewController().frontViewController.revealViewController().tapGestureRecognizer()
    self.revealViewController().frontViewController.view.isUserInteractionEnabled = false
}
</code>```

And in the same Menu view Controller add the following code in the viewWillDisappear method:

```<code>override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    self.revealViewController().frontViewController.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
    self.revealViewController().frontViewController.view.isUserInteractionEnabled = true
}
</code>```

The above code also adds other gestures, but those can be optional. The main action happens at these two lines:

```<code>self.revealViewController().frontViewController.view.isUserInteractionEnabled = false

self.revealViewController().frontViewController.view.isUserInteractionEnabled = true
</code>```

Hope this solves your issue. Cheers.

Body:
How to disable user's interaction with front view controller - namely with class ViewController in my case, when the rear menu is shown. With the current code, when rear menu is shown, bookCleaningButton is not disabled.

import UIKit
class ViewController: UIViewController, SWRevealViewControllerDelegate {

  @IBOutlet weak var menuButton: UIBarButtonItem!
  @IBOutlet weak var bookCleaningButton: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()
      self.revealViewController().rearViewRevealWidth = self.view.frame.width - 80

 //revela the menu if it is not nil
    if self.revealViewController() != nil {
        self.revealViewController().delegate = self
         menuButton.target = self.revealViewController()
           menuButton.action = #selector(SWRevealViewController.revealToggle(_:))
         self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()
    }
  }

func revealController(revealController: SWRevealViewController!, willMoveToPosition position: FrontViewPosition) {
    if revealController.frontViewPosition == FrontViewPosition.left {
        self.view.isUserInteractionEnabled = false
    }
    else {
        self.view.isUserInteractionEnabled = true
     }
  }
}

Body:
You should handle this in your Menu view controller rather. The reveal view controller has access to the frontViewController and that property can be used to set the userInteractionEnabled as false.

So, in your Menu View Controller write this this code in the viewWillAppear method:

 override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.revealViewController().view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
    self.revealViewController().frontViewController.revealViewController().tapGestureRecognizer()
    self.revealViewController().frontViewController.view.isUserInteractionEnabled = false
}

And in the same Menu view Controller add the following code in the viewWillDisappear method:

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    self.revealViewController().frontViewController.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
    self.revealViewController().frontViewController.view.isUserInteractionEnabled = true
}

The above code also adds other gestures, but those can be optional. The main action happens at these two lines:

self.revealViewController().frontViewController.view.isUserInteractionEnabled = false

self.revealViewController().frontViewController.view.isUserInteractionEnabled = true

Hope this solves your issue. Cheers.


问:
Git - nullSha1: contains entries pointing to null sha1
I'm trying to deploy an app and I get a error. Following research pointed me here:

```<code>warning in tree f148931b374ad1aa9748b8f91bd48fcb44fb73b0: nullSha1: contains entries pointing to null sha1
Checking object directories: 100% (256/256), done.
broken link from    tree f148931b374ad1aa9748b8f91bd48fcb44fb73b0
              to    blob 0000000000000000000000000000000000000000
missing blob 0000000000000000000000000000000000000000
</code>```

Tried the solution here but the commands do nothing on terminal they just sit there.

Can somebody help me?

答:
You could try, as suggested here, to remove the commit with the null sha1, using git filter-branch

```<code>git ls-tree f148931b374ad1aa9748b8f91bd48fcb44fb73b0
<an element>
git filter-branch --index-filter 'git rm -r --cached --ignore-unmatch <an element path>'  --prune-empty --tag-name-filter cat -- --all
</code>```

Replace <an element path> by the path relative to the root folder of the repo of the element returned by git ls-tree.

Body:
I'm trying to deploy an app and I get a error. Following research pointed me here:

warning in tree f148931b374ad1aa9748b8f91bd48fcb44fb73b0: nullSha1: contains entries pointing to null sha1
Checking object directories: 100% (256/256), done.
broken link from    tree f148931b374ad1aa9748b8f91bd48fcb44fb73b0
              to    blob 0000000000000000000000000000000000000000
missing blob 0000000000000000000000000000000000000000

Tried the solution here but the commands do nothing on terminal they just sit there.

Can somebody help me?

Body:
You could try, as suggested here, to remove the commit with the null sha1, using git filter-branch

git ls-tree f148931b374ad1aa9748b8f91bd48fcb44fb73b0
<an element>
git filter-branch --index-filter 'git rm -r --cached --ignore-unmatch <an element path>'  --prune-empty --tag-name-filter cat -- --all

Replace <an element path> by the path relative to the root folder of the repo of the element returned by git ls-tree.


问:
What Java/Design Patterns can be used for Long Running Synchronous Processes?
I am encountering a situation at work similar to the thread over here. The difference is that we are not using a web service. But rather we are using a web app. We have a requirement that lets a user download 8000 records with at least 30 columns which is written to an excel file via jxl.

This is a long running process that is not being done asynchronously for reasons I don't know. It also has a huge memory footprint ~ 500 - 800 MB. To top it all of, it takes on average 2 minutes and 10 seconds to finish.

What we are currently doing is delegating this requirement out of process from the application server via jms. The app server sends the request to the broker and then a consumer gets the request from the queue, processes it and sends back the url of the excel file.

I have some qualms about this because I have read been reading about JMS and most of the usecases suggested involve asynchronous requests so that users won't have to wait for a long time like for instance sending email, sending a request for approval, invoicing. There are lot of examples in this thread and the use cases suggested can be done asynchronously. So our current solution sounds like a hack rather than a true solution.

Any suggestions, patterns that can be done to further improve this process?

EDIT:  I unfortunately can't do away with the "synchronicity" if you may call it that of the feature because it's a business requirement. So I am looking for answers/tweaks/tricks/patterns that can enhance the performance and lessen the heap memory usage of the process instead.

答:
I'm not gonna suggest what you can do with your JMS backend - its probably not used well or maybe it is - I'm not sure.

We implemented something similar and here is what we ended up with (our backend implmentation was completely different, for a different use case, but the "async user exp" matches) :

Allow user to submit a request.

Once (1) is received, submit the job to the backend (JMS etc...) and tie it to a job id

The response of (1) is a this (permanent or temporary) handle - the job id, for example

The backend implementation should end by setting the status of the job

Allow users to poll for the status of the job (via the handle you gave them)

If the job status is "in progress", tell them so (with probably an estimated time for completion  - so that they dont unnecessarily waste time polling & burdening you)

If the status is "done successfully", report that to the user, with the other data (url etc...) the user would need to access the result


问:
Autocomplete the input field(type="text")
I have totally 4 (input) fields in form namely product name, Product name, Selling price and Purchased price. when I enter the something in the  Product name field it should show the suggestions(out of  so many products from Database) like google shows and when I click any suggestions it should populate the corresponding DB values in  the all 4 fields.  Please provide the sample code if you have so that I can refer the same. I know need to user the ajax+jQuery+mySQL+php. I don't how to use this all.

help me on this requirement

答:
Try something like this:

Jquery:

```<code>$(function(){
        var arr = [];
        var availableTags = [];

        $.ajax({
            'url'   : 'getdata.php',
            'method': 'get',
            success : function(response){
                arr = JSON.parse(response);

                availableTags = Object.keys(arr).map(function (key) { return arr[key]; });
            },
            async   : false
        });

        $( "#tags" ).autocomplete({
            source: availableTags
        });
    });
</code>```

Html:

```<code><input type="text" id="tags" placeholder="Enter name like Jackson">
</code>```

Php:

```<code><?php
    require('connect.php');

    $getDetails = "SELECT id, concat(first_name,' ',last_name) as name FROM test.datatables_demo";
    $details    = mysqli_query($con, $getDetails);

    $response = array();
    if(mysqli_num_rows($details) > 0)
    {
        while($row = mysqli_fetch_assoc($details))
        {
            $response[$row['id']] = $row['name'];
        }
    }

    echo json_encode($response);
?>
</code>```

Body:
Try something like this:

Jquery:

$(function(){
        var arr = [];
        var availableTags = [];

        $.ajax({
            'url'   : 'getdata.php',
            'method': 'get',
            success : function(response){
                arr = JSON.parse(response);

                availableTags = Object.keys(arr).map(function (key) { return arr[key]; });
            },
            async   : false
        });

        $( "#tags" ).autocomplete({
            source: availableTags
        });
    });

Html:

<input type="text" id="tags" placeholder="Enter name like Jackson">

Php:

<?php
    require('connect.php');

    $getDetails = "SELECT id, concat(first_name,' ',last_name) as name FROM test.datatables_demo";
    $details    = mysqli_query($con, $getDetails);

    $response = array();
    if(mysqli_num_rows($details) > 0)
    {
        while($row = mysqli_fetch_assoc($details))
        {
            $response[$row['id']] = $row['name'];
        }
    }

    echo json_encode($response);
?>


问:
fast loading of large hash table in Perl
I have about 30 text files with the structure

```<code>wordleft1|wordright1
wordleft2|wordright2
wordleft3|wordright3
...
</code>```

The total size of the files is about 1 GB with about 32 million lines of word combinations.

I tried a few approaches to load them as fast as possible and store the combinations within a hash

```<code>$hash{$wordleft} = $wordright
</code>```

Opening file by file and reading line by line takes about 42 seconds. I then store the hash with the Storable module

```<code>store \%hash, $filename
</code>```

Loading the data again

```<code>$hashref = retrieve $filename
</code>```

reduces the time to about 28 seconds. I use a fast SSD drive and a fast CPU and have enough RAM to hold all the data (it takes about 7 GB).

I'm searching for a faster way to load this data into the RAM (I can't keep it there for a few reasons).

答:
You could try using Dan Bernstein's CDB file format using a tied hash, which will require minimal code change.  You may need to install CDB_File.  On my laptop, the cdb file is opened very quickly and I can do about 200-250k lookups per second.   Here is an example script to create/use/benchmark a cdb:

test_cdb.pl

```<code>#!/usr/bin/env perl

use warnings;
use strict;

use Benchmark qw(:all) ;
use CDB_File 'create';
use Time::HiRes qw( gettimeofday tv_interval );

scalar @ARGV or die "usage: $0 number_of_keys seconds_to_benchmark\n";
my ($size)    = $ARGV[0] || 1000;
my ($seconds) = $ARGV[1] || 10;

my $t0;
tic();

# Create CDB
my ($file, %data);

%data = map { $_ => 'something' } (1..$size);
print "Created $size element hash in memory\n";
toc();

$file = 'data.cdb';
create %data, $file, "$file.$$";
my $bytes = -s $file;
print "Created data.cdb [ $size keys and values, $bytes bytes]\n";
toc();

# Read from CDB
my $c = tie my %h, 'CDB_File', 'data.cdb' or die "tie failed: $!\n";
print "Opened data.cdb as a tied hash.\n";
toc();

timethese( -1 * $seconds, {
          'Pick Random Key'    => sub { int rand $size },
          'Fetch Random Value' => sub { $h{ int rand $size }; },
});

tic();
print "Fetching Every Value\n";
for (0..$size) {
    no warnings; # Useless use of hash element
    $h{ $_ };
}
toc();

sub tic {
    $t0 = [gettimeofday];
}

sub toc {
    my $t1 = [gettimeofday];
    my $elapsed = tv_interval ( $t0, $t1);
    $t0 = $t1;
    print "==> took $elapsed seconds\n";
}
</code>```

Output ( 1 million keys, tested over 10 seconds )

```<code>./test_cdb.pl 1000000 10

Created 1000000 element hash in memory
==> took 2.882813 seconds
Created data.cdb [ 1000000 keys and values, 38890944 bytes]
==> took 2.333624 seconds
Opened data.cdb as a tied hash.
==> took 0.00015 seconds
Benchmark: running Fetch Random Value, Pick Random Key for at least 10 CPU seconds...
Fetch Random Value: 10 wallclock secs (10.46 usr +  0.01 sys = 10.47 CPU) @ 236984.72/s (n=2481230)
Pick Random Key:  9 wallclock secs (10.11 usr +  0.02 sys = 10.13 CPU) @ 3117208.98/s (n=31577327)
Fetching Every Value
==> took 3.514183 seconds
</code>```

Output ( 10 million keys, tested over 10 seconds )

```<code>./test_cdb.pl 10000000 10

Created 10000000 element hash in memory
==> took 44.72331 seconds
Created data.cdb [ 10000000 keys and values, 398890945 bytes]
==> took 25.729652 seconds
Opened data.cdb as a tied hash.
==> took 0.000222 seconds
Benchmark: running Fetch Random Value, Pick Random Key for at least 10 CPU seconds...
Fetch Random Value: 14 wallclock secs ( 9.65 usr +  0.35 sys = 10.00 CPU) @ 209811.20/s (n=2098112)
Pick Random Key: 12 wallclock secs (10.40 usr +  0.02 sys = 10.42 CPU) @ 2865335.22/s (n=29856793)
Fetching Every Value
==> took 38.274356 seconds
</code>```

Body:
I have about 30 text files with the structure

wordleft1|wordright1
wordleft2|wordright2
wordleft3|wordright3
...

The total size of the files is about 1 GB with about 32 million lines of word combinations.

I tried a few approaches to load them as fast as possible and store the combinations within a hash

$hash{$wordleft} = $wordright

Opening file by file and reading line by line takes about 42 seconds. I then store the hash with the Storable module

store \%hash, $filename

Loading the data again

$hashref = retrieve $filename

reduces the time to about 28 seconds. I use a fast SSD drive and a fast CPU and have enough RAM to hold all the data (it takes about 7 GB).

I'm searching for a faster way to load this data into the RAM (I can't keep it there for a few reasons).

Body:
You could try using Dan Bernstein's CDB file format using a tied hash, which will require minimal code change.  You may need to install CDB_File.  On my laptop, the cdb file is opened very quickly and I can do about 200-250k lookups per second.   Here is an example script to create/use/benchmark a cdb:

test_cdb.pl

#!/usr/bin/env perl

use warnings;
use strict;

use Benchmark qw(:all) ;
use CDB_File 'create';
use Time::HiRes qw( gettimeofday tv_interval );

scalar @ARGV or die "usage: $0 number_of_keys seconds_to_benchmark\n";
my ($size)    = $ARGV[0] || 1000;
my ($seconds) = $ARGV[1] || 10;

my $t0;
tic();

# Create CDB
my ($file, %data);

%data = map { $_ => 'something' } (1..$size);
print "Created $size element hash in memory\n";
toc();

$file = 'data.cdb';
create %data, $file, "$file.$$";
my $bytes = -s $file;
print "Created data.cdb [ $size keys and values, $bytes bytes]\n";
toc();

# Read from CDB
my $c = tie my %h, 'CDB_File', 'data.cdb' or die "tie failed: $!\n";
print "Opened data.cdb as a tied hash.\n";
toc();

timethese( -1 * $seconds, {
          'Pick Random Key'    => sub { int rand $size },
          'Fetch Random Value' => sub { $h{ int rand $size }; },
});

tic();
print "Fetching Every Value\n";
for (0..$size) {
    no warnings; # Useless use of hash element
    $h{ $_ };
}
toc();

sub tic {
    $t0 = [gettimeofday];
}

sub toc {
    my $t1 = [gettimeofday];
    my $elapsed = tv_interval ( $t0, $t1);
    $t0 = $t1;
    print "==> took $elapsed seconds\n";
}

Output ( 1 million keys, tested over 10 seconds )

./test_cdb.pl 1000000 10

Created 1000000 element hash in memory
==> took 2.882813 seconds
Created data.cdb [ 1000000 keys and values, 38890944 bytes]
==> took 2.333624 seconds
Opened data.cdb as a tied hash.
==> took 0.00015 seconds
Benchmark: running Fetch Random Value, Pick Random Key for at least 10 CPU seconds...
Fetch Random Value: 10 wallclock secs (10.46 usr +  0.01 sys = 10.47 CPU) @ 236984.72/s (n=2481230)
Pick Random Key:  9 wallclock secs (10.11 usr +  0.02 sys = 10.13 CPU) @ 3117208.98/s (n=31577327)
Fetching Every Value
==> took 3.514183 seconds

Output ( 10 million keys, tested over 10 seconds )

./test_cdb.pl 10000000 10

Created 10000000 element hash in memory
==> took 44.72331 seconds
Created data.cdb [ 10000000 keys and values, 398890945 bytes]
==> took 25.729652 seconds
Opened data.cdb as a tied hash.
==> took 0.000222 seconds
Benchmark: running Fetch Random Value, Pick Random Key for at least 10 CPU seconds...
Fetch Random Value: 14 wallclock secs ( 9.65 usr +  0.35 sys = 10.00 CPU) @ 209811.20/s (n=2098112)
Pick Random Key: 12 wallclock secs (10.40 usr +  0.02 sys = 10.42 CPU) @ 2865335.22/s (n=29856793)
Fetching Every Value
==> took 38.274356 seconds


问:
Error handling on GoTo Bookmark if bookmark doesn't exist
I'm working on a macro to copy and paste bookmarked tables from one word document to another. It works fine as long as the value I put in the input box matches an existing bookmark, but if I mistype the value, it simply pulls in the top table from my source document. I understand why it does that (because it selects table 1 if it doesn't find a bookmark), but I can't figure out how to fix it. I tried putting in error handling, but since it doesn't trigger an error, what I added doesn't work. Can someone show me how to edit the code below to fix this issue? Also, is there a way to use relative pathways for the source document and target document? They will always be in the same folder, but each different user will have a copy of them in their own folder, and I don't want to rewrite the macro every time. Any other improvements or edits would be appreciated, such as how to not use the selection event so much here. Or how to not reopen the documents if they are already open. The command button (and code) is in the Target document (Product.docm)</p>

```<code>Private Sub CommandButton2_Click()

' Copy table from source document and add to table in target document

  Dim oTarDoc As Document, oSourceDoc As Document
  Dim oTable As Table
  Dim oNewRow As Row

    Set oSourceDoc = Documents.Open("H:\Test Documents\Tables.docx")
    Set oTarDoc = Documents.Open("H:\Test Documents\Product.docm")

    Application.ScreenUpdating = False

    oTarDoc.Activate
    Set oTable = oTarDoc.Tables(2)
    Set oNewRow = oTable.Rows(oTable.Rows.Count - 3)

    oSourceDoc.Activate
    Selection.GoTo What:=wdGoToBookmark, Name:="A" & InputBox("119f, 979, 981a...", "Enter Number and Letter as Shown")
    With oSourceDoc.Bookmarks
        .DefaultSorting = wdSortByName
        .ShowHidden = False
    End With
    Selection.Tables(1).Select
    Selection.Copy

    oTarDoc.Activate
    oNewRow.Select
    Selection.Paste
       Application.ScreenUpdating = True    End Sub
</code>```

答:
You didn't amend your code for adding the row as I had suggested. It was your own previous code which caused the error. The following code is tested and works as you now describe.</p>

```<code>Private Sub CommandButton2_Click()

    ' Copy table from source document and add to table in target document

    Dim TarDoc As Document, SourDoc As Document
    Dim Tbl As Table
    Dim NewRow As Row
    Dim Mark As String, MarkText As String

    Set SourDoc = Documents.Open("H:\Test Documents\Tables.docx")
    Set TarDoc = Documents.Open("H:\Test Documents\Product.docm")

    Application.ScreenUpdating = False

    Set Tbl = TarDoc.Tables(2)
    With Tbl
       Set NewRow = .Rows.Add(BeforeRow:=.Rows(.Rows.Count - 2))
    End With

    Do
        Mark = InputBox("119f, 979, 981a...", "Enter Number and Letter as Shown")
        If Len(Mark) Then              ' do nothing if user enters nothing
            Mark = "A" & Mark
            If SourDoc.Bookmarks.Exists(Mark) Then
                MarkText = SourDoc.Bookmarks(Mark).Range.Text
                NewRow.Cells(1).Range.Text = MarkText
                Mark = vbNullString    ' to enable existing the loop
            Else
                MsgBox "Bookmark """ & Mark & """ doesn't exist.", vbInformation, _
                       "Invalid entry"
            End If
        End If
    Loop While Len(Mark)               ' the user entered a wrong mark

    Application.ScreenUpdating = True
End Sub
</code>```

Body:
I'm working on a macro to copy and paste bookmarked tables from one word document to another. It works fine as long as the value I put in the input box matches an existing bookmark, but if I mistype the value, it simply pulls in the top table from my source document. I understand why it does that (because it selects table 1 if it doesn't find a bookmark), but I can't figure out how to fix it. I tried putting in error handling, but since it doesn't trigger an error, what I added doesn't work. Can someone show me how to edit the code below to fix this issue? Also, is there a way to use relative pathways for the source document and target document? They will always be in the same folder, but each different user will have a copy of them in their own folder, and I don't want to rewrite the macro every time. Any other improvements or edits would be appreciated, such as how to not use the selection event so much here. Or how to not reopen the documents if they are already open. The command button (and code) is in the Target document (Product.docm)

Private Sub CommandButton2_Click()

' Copy table from source document and add to table in target document

  Dim oTarDoc As Document, oSourceDoc As Document
  Dim oTable As Table
  Dim oNewRow As Row

    Set oSourceDoc = Documents.Open("H:\Test Documents\Tables.docx")
    Set oTarDoc = Documents.Open("H:\Test Documents\Product.docm")

    Application.ScreenUpdating = False

    oTarDoc.Activate
    Set oTable = oTarDoc.Tables(2)
    Set oNewRow = oTable.Rows(oTable.Rows.Count - 3)

    oSourceDoc.Activate
    Selection.GoTo What:=wdGoToBookmark, Name:="A" & InputBox("119f, 979, 981a...", "Enter Number and Letter as Shown")
    With oSourceDoc.Bookmarks
        .DefaultSorting = wdSortByName
        .ShowHidden = False
    End With
    Selection.Tables(1).Select
    Selection.Copy

    oTarDoc.Activate
    oNewRow.Select
    Selection.Paste
       Application.ScreenUpdating = True    End Sub

Body:
You didn't amend your code for adding the row as I had suggested. It was your own previous code which caused the error. The following code is tested and works as you now describe.

Private Sub CommandButton2_Click()

    ' Copy table from source document and add to table in target document

    Dim TarDoc As Document, SourDoc As Document
    Dim Tbl As Table
    Dim NewRow As Row
    Dim Mark As String, MarkText As String

    Set SourDoc = Documents.Open("H:\Test Documents\Tables.docx")
    Set TarDoc = Documents.Open("H:\Test Documents\Product.docm")

    Application.ScreenUpdating = False

    Set Tbl = TarDoc.Tables(2)
    With Tbl
       Set NewRow = .Rows.Add(BeforeRow:=.Rows(.Rows.Count - 2))
    End With

    Do
        Mark = InputBox("119f, 979, 981a...", "Enter Number and Letter as Shown")
        If Len(Mark) Then              ' do nothing if user enters nothing
            Mark = "A" & Mark
            If SourDoc.Bookmarks.Exists(Mark) Then
                MarkText = SourDoc.Bookmarks(Mark).Range.Text
                NewRow.Cells(1).Range.Text = MarkText
                Mark = vbNullString    ' to enable existing the loop
            Else
                MsgBox "Bookmark """ & Mark & """ doesn't exist.", vbInformation, _
                       "Invalid entry"
            End If
        End If
    Loop While Len(Mark)               ' the user entered a wrong mark

    Application.ScreenUpdating = True
End Sub


问:
Is there any way showing images in alerts in ionic2
I want to take the values from database such as name,email and photo for a particular user and when he clicks the view button the same details should be seen in popup can i achieve in ionic2..
Any help will be appreciated..</p>

答:
You cannot do it using Alert component.If you need to do that then you have to use page component.On page component where you can show your images and all other db fetched stuff.

.html

```<code><ion-content padding>
  <img src="{{imageUrl}}" alt="image">
</ion-content>
</code>```

.ts

```<code> this.imageUrl = imageUrl;
</code>```

Body:
You cannot do it using Alert component.If you need to do that then you have to use page component.On page component where you can show your images and all other db fetched stuff.

.html

<ion-content padding>
  <img src="{{imageUrl}}" alt="image">
</ion-content>

.ts

 this.imageUrl = imageUrl;


问:
Shell include space and asterisk
Defind string array in shell script below. I want show the sql nomal, what should I do?</p>

```<code>a=("select * from t1;"
"select * from t2;"
"select  from t3;")

echo ${#a[@]}"--------"

for var1 in ${a[@]};do
    echo  "${var1}"
done
</code>```

答:
This would do it for you

```<code>a=( 'select * from t1;'
    'select * from t2;'
    'select * from t3;' )

for query in "${a[@]}"; do
  echo "$query"
done
</code>```

RESULT

```<code>$ sh SO.sh
select * from t1;
select * from t2;
select * from t3;
$
</code>```

Title: Shell include space and asterisk

Body:
Defind string array in shell script below. I want show the sql nomal, what should I do?

a=("select * from t1;"
"select * from t2;"
"select  from t3;")

echo ${#a[@]}"--------"

for var1 in ${a[@]};do
    echo  "${var1}"
done

Body:
This would do it for you

a=( 'select * from t1;'
    'select * from t2;'
    'select * from t3;' )

for query in "${a[@]}"; do
  echo "$query"
done

RESULT

$ sh SO.sh
select * from t1;
select * from t2;
select * from t3;
$