问:
Using Jquery to add comma's on textbox
I'm trying to put a comma on a textbox that should only accept numbers. What I did is instead of using type="numbers", I limited the textbox to only accept number keyCodes.

```<code>    $('#salary').keydown(function (e) {
        var keyCode = e.which;
        if (keyCode != 8 && keyCode != 9 && keyCode != 13 && keyCode != 37 && keyCode != 38 && keyCode != 39 && keyCode != 40 && keyCode != 46 && keyCode != 110 && keyCode != 190) {
            if (keyCode < 48) {
                e.preventDefault();
            } else if (keyCode > 57 && keyCode < 96) {
                e.preventDefault();
            } else if (keyCode > 105) {
                e.preventDefault();
            }
        }
    });
</code>```

What I want is that after the input is edited(out of focus), the textbox automatically shows commas similar to this value:

```<code>1,000,000.00
</code>```

I am clueless on what to do or use to add comma's on the textbox.

答:
Try this solution for add comma in numbers   </p>

```<code>    $('#salary').keydown(function (){
         var x = $('#salary').val();
         $('#salary').val(addCommas(x));

         function addCommas(x) {
           var parts = x.toString().split(".");
           parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
           return parts.join(".");
        }
});
</code>```

Title: Using Jquery to add comma's on textbox

Body:
I'm trying to put a comma on a textbox that should only accept numbers. What I did is instead of using type="numbers", I limited the textbox to only accept number keyCodes.

    $('#salary').keydown(function (e) {
        var keyCode = e.which;
        if (keyCode != 8 && keyCode != 9 && keyCode != 13 && keyCode != 37 && keyCode != 38 && keyCode != 39 && keyCode != 40 && keyCode != 46 && keyCode != 110 && keyCode != 190) {
            if (keyCode < 48) {
                e.preventDefault();
            } else if (keyCode > 57 && keyCode < 96) {
                e.preventDefault();
            } else if (keyCode > 105) {
                e.preventDefault();
            }
        }
    });

What I want is that after the input is edited(out of focus), the textbox automatically shows commas similar to this value:

1,000,000.00

I am clueless on what to do or use to add comma's on the textbox.

Body:
Try this solution for add comma in numbers

    $('#salary').keydown(function (){
         var x = $('#salary').val();
         $('#salary').val(addCommas(x));

         function addCommas(x) {
           var parts = x.toString().split(".");
           parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
           return parts.join(".");
        }
});


来源: stackexchange

问:
How to use _.SortBy() with an array of Objects?
I tried a lot of algorithm to convert my Array with objects inside into an array of arrays. But each time either it doesn't work or my new create array is empty. For exemple, I can't run into it with angular.foreach()or myArray.forEach(function(element)). I really don't know why, because it is declared and initialized as an array "var myArray = [];".

Then I'm using pushto populate it, and what I obtained in the console.log is :

What I would like to have is something usable into _.SortBy(myArray, 'date'); (Underscore.js) to do it I need myArray to be like that :

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];

Following this post : Converting a JS object to an array I tried barely everything listed, but nothing worked...Can you give me a hand ?

$scope.myArray = [];

// This is into an angular.foreach

 $scope.myArray.push({'Name' : snapshot.val().name, 'Link' : snapshot.val().link, 'second' : snapshot.val().second, 'var' : snapshot.val().var, 'selfID' : 'MyID', 'date' : snapshot.val().date, 'hour' : snapshot.val().hour });

 console.log("MyArray :", $scope.myArray);```
</div>
</div>
</p>

<h3>EDIT :</h3>

<p>It seems there is a problem with my array, i tried this two function, but i couldn't see any <code>console.log()</code>... Is it possible that my array is locked ? Maybe no function (sort, _.sortBy...) can run into it ?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// One try to run into and sort
$scope.myArray.sort(function(x, y)
{
            var date1 = new Date(x.date);
            var date2 = new Date(y.date);

            console.log("My dates :", date1);
            console.log("My dates :", date2);

            return date1 - date2 ;
});

// An other try to run into my array
for(var i = 0; i < $scope.myArray.length; i++)
{
            console.log("I'm in "+i+" with : "+$scope.newCal[i]);
}

// Even is showing the complete Array in console.log is working, this below shows me "undefined"

 console.log("One element : "+$scope.newCal[1]);</code>```

答:
You can use _.SortBy(myArray, 'date') , however as your "date" property seems to be a string literal, it will be sorted as alphabetically. You need to do something like this</p>

```<code>function parseYourDateToRealDateObjectSomehow(dateString){  return new Date(); }

_.SortBy(myArray, function(item1,item2){
  var bigger = parseYourDateToRealDateObjectSomehow(item1.date)  > parseYourDateToRealDateObjectSomehow(item2.date);
   if(bigger) return 1;

var smaller = parseYourDateToRealDateObjectSomehow(item1.date) <
   parseYourDateToRealDateObjectSomehow(item2.date);
   if(smaller) return -1;

   return 0;

});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I tried a lot of algorithm to convert my Array with objects inside into an array of arrays. But each time either it doesn't work or my new create array is empty. For exemple, I can't run into it with angular.foreach()or myArray.forEach(function(element)). I really don't know why, because it is declared and initialized as an array "var myArray = [];".

Then I'm using pushto populate it, and what I obtained in the console.log is :

What I would like to have is something usable into _.SortBy(myArray, 'date'); (Underscore.js) to do it I need myArray to be like that :

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];

Following this post : Converting a JS object to an array I tried barely everything listed, but nothing worked...Can you give me a hand ?

$scope.myArray = [];

// This is into an angular.foreach

 $scope.myArray.push({'Name' : snapshot.val().name, 'Link' : snapshot.val().link, 'second' : snapshot.val().second, 'var' : snapshot.val().var, 'selfID' : 'MyID', 'date' : snapshot.val().date, 'hour' : snapshot.val().hour });

 console.log("MyArray :", $scope.myArray);

EDIT :

It seems there is a problem with my array, i tried this two function, but i couldn't see any console.log()... Is it possible that my array is locked ? Maybe no function (sort, _.sortBy...) can run into it ?

// One try to run into and sort
$scope.myArray.sort(function(x, y)
{
            var date1 = new Date(x.date);
            var date2 = new Date(y.date);

            console.log("My dates :", date1);
            console.log("My dates :", date2);

            return date1 - date2 ;
});

// An other try to run into my array
for(var i = 0; i < $scope.myArray.length; i++)
{
            console.log("I'm in "+i+" with : "+$scope.newCal[i]);
}

// Even is showing the complete Array in console.log is working, this below shows me "undefined"

 console.log("One element : "+$scope.newCal[1]);

Body:
You can use _.SortBy(myArray, 'date') , however as your "date" property seems to be a string literal, it will be sorted as alphabetically. You need to do something like this

function parseYourDateToRealDateObjectSomehow(dateString){  return new Date(); }

_.SortBy(myArray, function(item1,item2){
  var bigger = parseYourDateToRealDateObjectSomehow(item1.date)  > parseYourDateToRealDateObjectSomehow(item2.date);
   if(bigger) return 1;

var smaller = parseYourDateToRealDateObjectSomehow(item1.date) <
   parseYourDateToRealDateObjectSomehow(item2.date);
   if(smaller) return -1;

   return 0;

});


问:
Spark Dataframe validating column names for parquet writes
I'm processing events using Dataframes converted from a stream of JSON events which eventually gets written out as Parquet format.

However, some of the JSON events contains spaces in the keys which I want to log and filter/drop such events from the data frame before converting it to Parquet because ;{}()\n\t= are considered special characters in Parquet schema (CatalystSchemaConverter) as listed in [1] below and thus should not be allowed in the column names.

How can I do such validations in Dataframe on the column names and drop such an event altogether without erroring out the Spark Streaming job.

[1]
Spark's CatalystSchemaConverter

def checkFieldName(name: String): Unit = {
  // ,;{}()\n\t= and space are special characters in Parquet schema
  checkConversionRequirement(
    !name.matches(".*[ ,;{}()\n\t=].*"),
    s"""Attribute name "$name" contains invalid character(s) among " ,;{}()\\n\\t=".
             |Please use alias to rename it.
           """.stripMargin.split("\n").mkString(" ").trim
  )
}
```

答: Using alias to change your field names without those special characters.

ContentLicense: CC BY-SA 4.0


答:
Try to put the function you do want to execute once per minute inside the setTimeout function. Also if you want to execute more than once, you should replace setTimeout with setInterval</p>

```<code>setInterval( function() {
   dates.forEach(function(date, index) {
      counter ++;

      // Reset when you reach 10 counts.
      if (counter === 10) {
       counter = 0;
      }
   }
}, 120000);
</code>```

Title: Javascript - wait for 1 minute for every 10 loop?

Body:
How can I wait for 1 or 2 minute for every 10 loop?

For instance, this is my working code:

var dates = ["2016-08-31T23:00:00.000Z","2016-09-01T23:00:00.000Z","2016-09-02T23:00:00.000Z","2016-09-03T23:00:00.000Z","2016-09-04T23:00:00.000Z","2016-09-05T23:00:00.000Z","2016-09-06T23:00:00.000Z","2016-09-07T23:00:00.000Z","2016-09-08T23:00:00.000Z","2016-09-09T23:00:00.000Z","2016-09-10T23:00:00.000Z","2016-09-11T23:00:00.000Z","2016-09-12T23:00:00.000Z","2016-09-13T23:00:00.000Z","2016-09-14T23:00:00.000Z","2016-09-15T23:00:00.000Z","2016-09-16T23:00:00.000Z","2016-09-17T23:00:00.000Z","2016-09-18T23:00:00.000Z","2016-09-19T23:00:00.000Z","2016-09-20T23:00:00.000Z","2016-09-21T23:00:00.000Z","2016-09-22T23:00:00.000Z","2016-09-23T23:00:00.000Z","2016-09-24T23:00:00.000Z","2016-09-25T23:00:00.000Z","2016-09-26T23:00:00.000Z","2016-09-27T23:00:00.000Z","2016-09-28T23:00:00.000Z","2016-09-29T23:00:00.000Z","2016-09-30T23:00:00.000Z","2016-10-01T23:00:00.000Z"];

var counter = 0;

// Loop the dates and convert them to this format: yyyy-m-d
dates.forEach(function(date, index) {
    counter ++;

    console.log(date);

    // Reset when you reach 10 counts.
    if (counter === 10) {
        counter = 0;
    }

    // Wait for 2 minute before the next 10 loop.
    setTimeout( function() {
       //
    }, 120000);
});

Is it possible? Any ideas?

EDIT:

What I am after:

2016-08-31T23:00:00.000Z
2016-09-01T23:00:00.000Z
2016-09-02T23:00:00.000Z
2016-09-03T23:00:00.000Z
2016-09-04T23:00:00.000Z
2016-09-05T23:00:00.000Z
2016-09-06T23:00:00.000Z
2016-09-07T23:00:00.000Z
2016-09-08T23:00:00.000Z
2016-09-09T23:00:00.000Z

(wait for 2 minute here)

2016-09-10T23:00:00.000Z
2016-09-11T23:00:00.000Z
2016-09-12T23:00:00.000Z
2016-09-13T23:00:00.000Z
2016-09-14T23:00:00.000Z
2016-09-15T23:00:00.000Z
2016-09-16T23:00:00.000Z
2016-09-17T23:00:00.000Z
2016-09-18T23:00:00.000Z
2016-09-19T23:00:00.000Z

(wait for 2 minute here)

2016-09-20T23:00:00.000Z
2016-09-21T23:00:00.000Z
2016-09-22T23:00:00.000Z
2016-09-23T23:00:00.000Z
2016-09-24T23:00:00.000Z
2016-09-25T23:00:00.000Z
2016-09-26T23:00:00.000Z
2016-09-27T23:00:00.000Z
2016-09-28T23:00:00.000Z
2016-09-29T23:00:00.000Z

(wait for 2 minute here)

2016-09-30T23:00:00.000Z
2016-10-01T23:00:00.000Z

Body:
Try to put the function you do want to execute once per minute inside the setTimeout function. Also if you want to execute more than once, you should replace setTimeout with setInterval

setInterval( function() {
   dates.forEach(function(date, index) {
      counter ++;

      // Reset when you reach 10 counts.
      if (counter === 10) {
       counter = 0;
      }
   }
}, 120000);


问:
How can I horizontally and vertically center an  in a
?
I don't want to center a div, I want the contents of a div to be centered.  I would like horizontal and vertical alignment.

Sorry, if this is too easy or whatever, but this is kind of a hassle to get it right.

Grae

I am using IE7

答:
If you know the inner element's height beforehand,

CSS:

```<code>.container {
    text-align: center; /* Center horizontally. */

    /* For demo only */
    border: 1px solid #000;
    height: 500px;
    margin: 20px;
    width: 700px;
}

.container img {
    margin-top: -167px;
    position: relative;
    top: 50%;
}</code>```

HTML:```<code><div class="container">
    <img src="http://farm6.static.flickr.com/5004/5270561847_7223069d5e.jpg" width="500" height="334" alt="">
</div></code>```

Example

ContentLicense: CC BY-SA 2.5

Title: How can I horizontally and vertically center an <img> in a <div>?

Body:
If you know the inner element's height beforehand,

CSS:

.container {
    text-align: center; /* Center horizontally. */

    /* For demo only */
    border: 1px solid #000;
    height: 500px;
    margin: 20px;
    width: 700px;
}

.container img {
    margin-top: -167px;
    position: relative;
    top: 50%;
}

HTML:
<div class="container">
    <img src="http://farm6.static.flickr.com/5004/5270561847_7223069d5e.jpg" width="500" height="334" alt="">
</div>

Example


问:
VSTS: How to auto-delete git branches
We currently have our dev team working out of VSTS, with git.  The number of branches are getting quite large, and rather than manually deleting branches every month, I would like ability to auto-delete branches that have not been touched for, say, 60 days.  I know this is possible to do in Jenkins, but we don't have Jenkins at the moment, and was wondering if this is possible to do in VSTS via some service hook?</p>

答:
VSTS is not support server-side hooks so far. But there have other ways to auto-delete the old branches in local machine. Detail steps as below:

1. In a certain directory (such as D:\script_for_git), clone the VSTS git repo (only used for auto-delete branches).

2. Add a shell script (del.sh) in the root git repo (D:\script_for_git\repo) to delete the remote branches which were not changed 180 days (6 months) ago, the contents of the shell script as below:

```<code>git fetch origin
for reBranch in $(git branch -a)
do
{
  if [[ $reBranch == remotes/origin* ]];
  then
  {
    if [[ $reBranch ==remotes/origin/HEAD ]]; then
    echo "HEAD is not a branch"
    else
      branch=$(echo $reBranch | cut -d'/' -f 3)
      echo $branch
      sha=$(git rev-parse origin/$branch)
      dateo=$(git show -s --format=%ci $sha)
      datef=$(echo $dateo | cut -d' ' -f 1)
      Todate=$(date -d "$datef" +'%s')
      current=$(date +'%s')
      day=$(( ( $current - $Todate )/60/60/24 ))
      echo $day
      if [ "$day" -gt 180 ]; then
      git push origin :$branch
      echo "delete the old branch $branch"
      fi
    fi

  }
  fi
}
done
</code>```

3. Schedule to run this shell script. There are many ways scheduling to run a script and it's OS related. Such as if you are using windows, you can refer this post. If you are using linux, you can refer this post.

Title: VSTS: How to auto-delete git branches

Body:
VSTS is not support server-side hooks so far. But there have other ways to auto-delete the old branches in local machine. Detail steps as below:

1. In a certain directory (such as D:\script_for_git), clone the VSTS git repo (only used for auto-delete branches).

2. Add a shell script (del.sh) in the root git repo (D:\script_for_git\repo) to delete the remote branches which were not changed 180 days (6 months) ago, the contents of the shell script as below:

git fetch origin
for reBranch in $(git branch -a)
do
{
  if [[ $reBranch == remotes/origin* ]];
  then
  {
    if [[ $reBranch ==remotes/origin/HEAD ]]; then
    echo "HEAD is not a branch"
    else
      branch=$(echo $reBranch | cut -d'/' -f 3)
      echo $branch
      sha=$(git rev-parse origin/$branch)
      dateo=$(git show -s --format=%ci $sha)
      datef=$(echo $dateo | cut -d' ' -f 1)
      Todate=$(date -d "$datef" +'%s')
      current=$(date +'%s')
      day=$(( ( $current - $Todate )/60/60/24 ))
      echo $day
      if [ "$day" -gt 180 ]; then
      git push origin :$branch
      echo "delete the old branch $branch"
      fi
    fi

  }
  fi
}
done

3. Schedule to run this shell script. There are many ways scheduling to run a script and it's OS related. Such as if you are using windows, you can refer this post. If you are using linux, you can refer this post.


问:
Link CSS to HTML for nodejs server
I am trying to link styles.css file to hello.html page to show up in the localhost using nodejs. But the output is only formatted in html and css styling isn't displayed.

Here is my code!

project.js

```<code>var http = require('http');
var fs = require('fs');

http.createServer(function (req,res){
    fs.readFile('hello.html',function(err,data){
    res.writeHead(200,{'Content-Type': 'text/html'});
    res.write(data);
    res.end();
  });

}).listen(8080);
</code>```

hello.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="heading">
    <h1>FILE UPLOADING!</h1>
</div>

<form method= "POST" enctype="multipart/form-data" action="fileupload">
<input type="file" name="filetoupload">
<input type="submit" id='bt' value="Submit">
</form>

</body>
</html>
</code>```

style.css

```<code>#heading{
    color:green;
    font-family: sans-serif,serif;
}

#bt{
 background-color: #4CAF50;
color: #ffffff;
border-color: #4CAF50;
}
</code>```

答:
you can try this!

var http = require('http')
var fs = require('fs')

http.createServer(function (req, res) {
    let route = req.url.replace('/', '')

    let request_url = route === '' || route === '/' ? 'hello.html' : route

    console.log(request_url)

    fs.exists(request_url, (exist) => {
        if (Boolean(exist) === false) {
            res.writeHead(404, {'content-type': 'text/html'})
            res.end('Page Not Found')
            return null
        }

        fs.readFile(request_url, function (err, data) {
            res.writeHead(200)
            res.write(data)
            res.end()
        })
    })
}).listen(8080)```

Title: Link CSS to HTML for nodejs server

Body:
I am trying to link styles.css file to hello.html page to show up in the localhost using nodejs. But the output is only formatted in html and css styling isn't displayed.

Here is my code!

project.js

var http = require('http');
var fs = require('fs');

http.createServer(function (req,res){
    fs.readFile('hello.html',function(err,data){
    res.writeHead(200,{'Content-Type': 'text/html'});
    res.write(data);
    res.end();
  });

}).listen(8080);

hello.html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" type="text/css" href="style.css" />

FILE UPLOADING!

<form method= "POST" enctype="multipart/form-data" action="fileupload">
<input type="file" name="filetoupload">
<input type="submit" id='bt' value="Submit">
</form>

style.css

#heading{
    color:green;
    font-family: sans-serif,serif;
}

#bt{
 background-color: #4CAF50;
color: #ffffff;
border-color: #4CAF50;
}


问:
Using vuejs how to secure the admin panel
I have just started learning VueJS. I am using vuejs to call an external api that does CRUD operations for my application. The CRUD operations are made in the admin panel (http://domain.com/admin-dashboard) which requires a username and password. The external api endpoint provides an api/auth endpoint that accepts a username and a password and if the details are correct provides a JWT token. This token should be used when making the api request for the CRUD operations by passing the token in Authorization header Bearer xxx (where xxx is the token id)

Well everything works fine till here. But the problem is how do I stop someone from accessing the /admin-dashboardpage using vuejs? Earlier the traditional way of doing this in php is something like this:

```<code><?php
session_start();
if(empty($_SESSION['is_logged_in'])){
 // Redirect to login page
 header('Location login.php');
 exit();
}
</code>```

This way i can be sure that no unauthorized user can access the dashboard. But now since my entire app is based on vuejs, how do I secure the admin-dashboard page?

Any help will be appreciated.

答:
What are you using on the server? Lotsa PHP folk are sticking with PHP, it would seem. In any case, the problem stays the same. Authorization and authentication are always server responsibilities. When servers respond to ajax requests, it's effectively bad form to redirect to a login page. You should be sending a 401 Unauthorized or 403 Forbidden. Your front end will never show unauthorized data because your backend will never send it.

In vue, you need to manage the JWT. How long will it last and where will you store it. Will you be sending it in a cookie, or in a header? Then you need to manage 401/403 responses to ajax calls (show the login screen). You're taking a big bend when you switch from server-generated pages to SPA. Make sure you get your head around the new paradigm :-) I'm not sure I have.

Body:
I have just started learning VueJS. I am using vuejs to call an external api that does CRUD operations for my application. The CRUD operations are made in the admin panel (http://domain.com/admin-dashboard) which requires a username and password. The external api endpoint provides an api/auth endpoint that accepts a username and a password and if the details are correct provides a JWT token. This token should be used when making the api request for the CRUD operations by passing the token in Authorization header Bearer xxx (where xxx is the token id)

Well everything works fine till here. But the problem is how do I stop someone from accessing the /admin-dashboardpage using vuejs? Earlier the traditional way of doing this in php is something like this:

<?php
session_start();
if(empty($_SESSION['is_logged_in'])){
 // Redirect to login page
 header('Location login.php');
 exit();
}

This way i can be sure that no unauthorized user can access the dashboard. But now since my entire app is based on vuejs, how do I secure the admin-dashboard page?

Any help will be appreciated.


问:
How to test iOS app on supporting IPv6? Apple rejected app as it is not IPv6 compatible
have apps, built 2015 and 2014. How can I test them for IPv6?
If my apps doesn't support IPv6, what should I do?

My apps are using AFNetworking and Alamofire. I'm connecting mostly to domains ( Ex. api.example.com/v1/...). Only 1 app use IP: (ex: 12.12.12.12:3000/api/v1/...).

答:
This solution only works if you have an ethernet connection.

For creating an iPV6 NAT64 wifi network, follow these steps

Step 1 : Open system preferences

Step 2 : Open Sharing

Step 3 : Click on internet sharing

Step 4 : Click Wifi in the ports while pressing option(ALT) key. A Create NAT64 Network checkbox will be displayed on the bottom after that. It is important to press ALT while selecting WIFI for displaying the checkbox

Step 5 : check Create NAT64 Network checkbox.

Now test the application in the created network.


问:
SQL query to fetch rows from one table which are not present in other 3 tables
I have 4 tables,

A, B , C , D

A has column Aid,
B has column Aid,
C has column Aid,
D has column Aid

(Aid is common column in all the 4 tables)

now i want to fetch rows from A table which are not present in B or C or D
can anyone please let me know the SQL query for this.

答:
You can use the MINUS operator:

```<code>SELECT Aid FROM A
MINUS
SELECT Aid FROM B
MINUS
SELECT Aid FROM C
MINUS
SELECT Aid FROM D
</code>```

Example

```<code>CREATE TABLE A ( Aid, Value ) AS
  SELECT 1, '1' FROM DUAL UNION ALL
  SELECT 1, '2' FROM DUAL UNION ALL
  SELECT 2, '3' FROM DUAL UNION ALL
  SELECT NULL, '4' FROM DUAL UNION ALL
  SELECT 3, '5' FROM DUAL;

CREATE TABLE B ( Aid, BValue ) AS
  SELECT 1, '3' FROM DUAL;

CREATE TABLE C ( Aid, CValue ) AS
  SELECT 4, '7' FROM DUAL;

CREATE TABLE D ( Aid, DValue ) AS
  SELECT NULL, '9' FROM DUAL;
</code>```

Query:

```<code>SELECT Aid FROM A
MINUS
SELECT Aid FROM B
MINUS
SELECT Aid FROM C
MINUS
SELECT Aid FROM D
</code>```

Output:

```<code>AID
---
  2
  3
</code>```

Update to get all columns of A:

This will exclude rows where the Aid is equal or when both are NULL:

```<code>SELECT *
FROM   A
WHERE  NOT EXISTS(SELECT 1 FROM B WHERE A.Aid = B.Aid OR (A.Aid IS NULL AND B.Aid IS NULL))
AND    NOT EXISTS(SELECT 1 FROM C WHERE A.Aid = C.Aid OR (A.Aid IS NULL AND C.Aid IS NULL))
AND    NOT EXISTS(SELECT 1 FROM D WHERE A.Aid = D.Aid OR (A.Aid IS NULL AND D.Aid IS NULL));
</code>```

Body:
You can use the MINUS operator:

SELECT Aid FROM A
MINUS
SELECT Aid FROM B
MINUS
SELECT Aid FROM C
MINUS
SELECT Aid FROM D

Example

CREATE TABLE A ( Aid, Value ) AS
  SELECT 1, '1' FROM DUAL UNION ALL
  SELECT 1, '2' FROM DUAL UNION ALL
  SELECT 2, '3' FROM DUAL UNION ALL
  SELECT NULL, '4' FROM DUAL UNION ALL
  SELECT 3, '5' FROM DUAL;

CREATE TABLE B ( Aid, BValue ) AS
  SELECT 1, '3' FROM DUAL;

CREATE TABLE C ( Aid, CValue ) AS
  SELECT 4, '7' FROM DUAL;

CREATE TABLE D ( Aid, DValue ) AS
  SELECT NULL, '9' FROM DUAL;

Query:

SELECT Aid FROM A
MINUS
SELECT Aid FROM B
MINUS
SELECT Aid FROM C
MINUS
SELECT Aid FROM D

Output:

AID
---
  2
  3

Update to get all columns of A:

This will exclude rows where the Aid is equal or when both are NULL:

SELECT *
FROM   A
WHERE  NOT EXISTS(SELECT 1 FROM B WHERE A.Aid = B.Aid OR (A.Aid IS NULL AND B.Aid IS NULL))
AND    NOT EXISTS(SELECT 1 FROM C WHERE A.Aid = C.Aid OR (A.Aid IS NULL AND C.Aid IS NULL))
AND    NOT EXISTS(SELECT 1 FROM D WHERE A.Aid = D.Aid OR (A.Aid IS NULL AND D.Aid IS NULL));


问:
Python 2.7 - Raw_input and If and else
raw_input('What are you doing?     ')

a = 'nothing'
if type(a):
    print 'That seems boring'
else:
    print 'Nice'

The meaning of this code, is that if a person answers the raw_input with 'nothing'. It should print that seems boring. And if a person writes something else it should print ok.

I am new to programming so please help me :)

答:
I always like to make variables that show what they contain.
My version would look like this:</p>

```<code>print "What are you doing?"
reply = raw_input()
if reply == "nothing":
    print "That seems boring"
else:
    print "Nice"
</code>```

Title: Python 2.7 - Raw_input and If and else

Body:
I always like to make variables that show what they contain.
My version would look like this:

print "What are you doing?"
reply = raw_input()
if reply == "nothing":
    print "That seems boring"
else:
    print "Nice"


问:
Creating all possible pairs from elements in a list and then sorting them evenly
So I have 3 to 8 players, I want each one to play against all the others 1 vs 1.
The matches are done sequentially one at a time.
The ordering within a pair isn't important (a vs b == b vs a).

I'm creating the matchup pairs in a simple nested loop, in which I loop over the players and pair the current index with all the following indexes.

The problem is that player 1 will play all his matches and then have nothing to do, while player 8 will have to wait.

Is there any way to evenly distribute the pairs, so all players have equal downtime?

I'm currently randomizing the array containing the pairs, but I'm looking for a better way.

答:
Save the matchups in order in an array, then shuffle it like so

```<code>function shuffle(a) {
for (let i = a.length; i; i--) {
    let j = Math.floor(Math.random() * i);
    [a[i - 1], a[j]] = [a[j], a[i - 1]];
}
</code>```

}

And then use it like this

```<code>var myArray = ['1','2','3','4','5','6','7','8','9'];
shuffle(myArray);
</code>```

Taken from Here

Body:
Save the matchups in order in an array, then shuffle it like so

function shuffle(a) {
for (let i = a.length; i; i--) {
    let j = Math.floor(Math.random() * i);
    [a[i - 1], a[j]] = [a[j], a[i - 1]];
}

}

And then use it like this

var myArray = ['1','2','3','4','5','6','7','8','9'];
shuffle(myArray);

Taken from Here


问:
deploying f-droid server
I am trying to deploy a simple binary repo in f-droid server as per the instructions in the manual.

Being a complete newbie to python, I couldn't figure out the process. Here is what I have done so far:

Installed Ubuntu via VirtualBox in my Mac.

downloaded android SDK and kept it in ~/tools/android-sdk. same goes with NDK.

cloned fdroidserver and fdroiddata repos and added the path of fdroidserver to $PATH.

copied fdroiddata to /var/www/ (not sure whether this is right)

Edited config.py to reflect SDK n NDK path, set repo URL as localhost/fdroiddata

created repo dir inside fdroiddata, copied an APK in it and tried running fdroid update.py (which throws errors)

I couldnt get the server running. My another doubt: Will it be possible to view some data in server via localhost or the server respond properly only to the request raised from the fdroid android client?

Could someone please guide me in right directions?

Thanks

答: We've recently revamped the F-Droid docs so things should be easier to find and follow.  The instructions for setting up your own repo are now here: https://f-droid.org/docs/Setup_an_F-Droid_App_Repo</p>

Title: deploying f-droid server


问:
JavaScript [element].innerHTML = htmlcode is not working
There is a performance time delay in rendering window.navigate(strURL);. Until then I want display a wait message using mainContainer.innerHTML = HTMLwait; but it is not working. Any help is appreciated. Thanks!

```<code>var HTMLwait = "<div style='width:300px;height:300px;top:40%;left:45%;position:absolute;overflow:auto;display:inline;'><div style='width:50px;height:50px;top:20%;left:4%;position:absolute;overflow:auto;display:inline;'><img src='../../images/Developer/ajax-loader.gif'></div><div style='width:50px;height:50px;top:35%;left:0%;position:absolute;font-family:arial;font-size:12px;color:#000000;'>Loading...</div></div>";

var strURL = window.location.href;

var mainContainer = $(".mainContainer");
if (mainContainer != null) {
  mainContainer.innerHTML = HTMLwait;
}

window.navigate(strURL);
</code>```

答:
mainContainer is a jQuery object and therefore does not have a innerHTML property. To set the HTML of an element selected via jQuery, use html().

Note that a jQuery object will never be null. To check if it exists, use the length property. You should note though that checking that the element exists is redundant, as jQuery will not throw an error when calling a method on a jQuery object that holds no Elements.

Also you appear to be using window.location.href to reload the page. A much simpler method would be to just use window.location.reload().

With all that said, try this:

```<code>var HTMLwait = "<div style='width:300px;height:300px;top:40%;left:45%;position:absolute;overflow:auto;display:inline;'><div style='width:50px;height:50px;top:20%;left:4%;position:absolute;overflow:auto;display:inline;'><img src='../../images/Developer/ajax-loader.gif'></div><div style='width:50px;height:50px;top:35%;left:0%;position:absolute;font-family:arial;font-size:12px;color:#000000;'>Loading...</div></div>";
var mainContainer = $(".mainContainer").html(HTMLwait);
window.location.reload();
</code>```

Finally, there is a lot of inline styling in the HTML string you're appending to the DOM. You should really avoid inline styles. Instead place a class on the elements you append, then style them via an external stylesheet.

Body:
There is a performance time delay in rendering window.navigate(strURL);. Until then I want display a wait message using mainContainer.innerHTML = HTMLwait; but it is not working. Any help is appreciated. Thanks!

var HTMLwait = "

Loading...

";

var strURL = window.location.href;

var mainContainer = $(".mainContainer");
if (mainContainer != null) {
  mainContainer.innerHTML = HTMLwait;
}

window.navigate(strURL);

Body:
mainContainer is a jQuery object and therefore does not have a innerHTML property. To set the HTML of an element selected via jQuery, use html().

Note that a jQuery object will never be null. To check if it exists, use the length property. You should note though that checking that the element exists is redundant, as jQuery will not throw an error when calling a method on a jQuery object that holds no Elements.

Also you appear to be using window.location.href to reload the page. A much simpler method would be to just use window.location.reload().

With all that said, try this:

var HTMLwait = "<div style='width:300px;height:300px;top:40%;left:45%;position:absolute;overflow:auto;display:inline;'><div style='width:50px;height:50px;top:20%;left:4%;position:absolute;overflow:auto;display:inline;'><img src='../../images/Developer/ajax-loader.gif'></div><div style='width:50px;height:50px;top:35%;left:0%;position:absolute;font-family:arial;font-size:12px;color:#000000;'>Loading...</div></div>";
var mainContainer = $(".mainContainer").html(HTMLwait);
window.location.reload();

Finally, there is a lot of inline styling in the HTML string you're appending to the DOM. You should really avoid inline styles. Instead place a class on the elements you append, then style them via an external stylesheet.


问:
How can I put Date Mapping in Elasticsearch 5.4 using Java?
Elasticsearch version 5.4.1, Kibana 5.4.1
Date Mapping not reflected in Kibana after putting Date Mapping through Java API

client.admin().indices().preparePutMapping(indexName).
            setType(type).setSource(XContentFactory.jsonBuilder().
                      startObject().
                        startObject(type)
                        .startObject("properties")
                        .startObject(attributeFieldKeyValue.getAttributeValues())
                            .field("type", attributeFieldKeyValue.getDataType())
                            .field(attributeFieldKeyValue.getFieldName(), attributeFieldKeyValue.getFieldValue())
                        .endObject()
                  .endObject()
              .endObject()
              .endObject()).execute().actionGet();te().actionGet();

答:
please take your time to write up more details. Are you trying to change an existing field to a date field? If so, that does not work - if you want to do that you need to reindex.

Have you checked the response if there is an error message? Did an exception occur? How did the mapping look before you executed the request.


问:
two nested model properties of same complex type
I have a Customer model with two complex properties "InternalAddress" and "PublicAddress" which are both of the same model type Address.

In the view I am doing the following

```<code><h2>Internal Address</h2>
<% RenderPartial("Address", Model.InternalAddress);%>
<h2>Public Address</h2>
<% RenderPartial("Address", Model.PublicAddress);%>
</code>```

It gets rendered without exceptions but the rendered html does use the same input-names for both PartialViews...

Is there a smart way to handle this situation?

答:
It's good that you're combining functionality using partial views, since most of the time an address is only rendered one way.

One way to display the form properly is using MVC2 EditorFor and DisplayFor templates.  Move the partial view for the form into /Views/Shared/EditorTemplates/Address.ascx (and the display-only portion if you have one into /Views/Shared/DisplayTemplates/Address.ascx).

Once that's done, you can use it one of two ways.

Option 1:

You can edit your ViewModel like this:

```<code>[UIHint("Address")]
public Address InternalAddress { get; set; }

[UIHint("Address")]
public Address PublicAddress{ get; set; }
</code>```

The UIHint tells the templating engine to use a view called "Address" in the Shared/EditorTemplates folder.

Then you can use the EditorFor template in your view with no modifications:

```<code><%: Html.EditorFor(model => model.InternalAddress) %>
</code>```

Option 2:

Simply specify the template's name in the EditorFor in the view:

```<code><%: Html.EditorFor(model => model.InternalAddress, "Address") %>
</code>```

Body:
I have a Customer model with two complex properties "InternalAddress" and "PublicAddress" which are both of the same model type Address.

In the view I am doing the following

Internal Address

<% RenderPartial("Address", Model.InternalAddress);%>

Public Address

<% RenderPartial("Address", Model.PublicAddress);%>

It gets rendered without exceptions but the rendered html does use the same input-names for both PartialViews...

Is there a smart way to handle this situation?

Body:
It's good that you're combining functionality using partial views, since most of the time an address is only rendered one way.

One way to display the form properly is using MVC2 EditorFor and DisplayFor templates.  Move the partial view for the form into /Views/Shared/EditorTemplates/Address.ascx (and the display-only portion if you have one into /Views/Shared/DisplayTemplates/Address.ascx).

Once that's done, you can use it one of two ways.

Option 1:

You can edit your ViewModel like this:

[UIHint("Address")]
public Address InternalAddress { get; set; }

[UIHint("Address")]
public Address PublicAddress{ get; set; }

The UIHint tells the templating engine to use a view called "Address" in the Shared/EditorTemplates folder.

Then you can use the EditorFor template in your view with no modifications:

<%: Html.EditorFor(model => model.InternalAddress) %>

Option 2:

Simply specify the template's name in the EditorFor in the view:

<%: Html.EditorFor(model => model.InternalAddress, "Address") %>


问:
Application not installing some device Android os N android
I have samsung device s7 edge. Application not installed for live build. Please help me, what is an exactly problem. See this error throw, on Android N os in device.

答:
In your manifest file, add the  element and specify the android:xlargeScreens attribute to "true":

```<code><supports-screens android:xlargeScreens="true" />
</code>```

If your app targets API level 24 or higher, you can configure how and
  whether your app's activities support multi-window display. You can
  set attributes in your manifest to control both size and layout. A
  root activity's attribute settings apply to all activities within its
  task stack.

```<code>android:resizeableActivity="true"
</code>```

Read android:resizeableActivity

FYI

If you build a multi-orientation app that targets API level 23 or
  lower, and the user uses the app in multi-window mode, the system
  forcibly resizes the app. The system presents a dialog box warning the
  user that the app may behave unexpectedly. The system does not resize
  fixed-orientation apps; if the user attempts to open a
  fixed-orientation app under multi-window mode, the app takes over the
  whole screen.

```<code><application
....
 android:resizeableActivity="true">
</code>```

Body:
In your manifest file, add the  element and specify the android:xlargeScreens attribute to "true":

<supports-screens android:xlargeScreens="true" />

If your app targets API level 24 or higher, you can configure how and
  whether your app's activities support multi-window display. You can
  set attributes in your manifest to control both size and layout. A
  root activity's attribute settings apply to all activities within its
  task stack.

android:resizeableActivity="true"

Read android:resizeableActivity

FYI

If you build a multi-orientation app that targets API level 23 or
  lower, and the user uses the app in multi-window mode, the system
  forcibly resizes the app. The system presents a dialog box warning the
  user that the app may behave unexpectedly. The system does not resize
  fixed-orientation apps; if the user attempts to open a
  fixed-orientation app under multi-window mode, the app takes over the
  whole screen.

<application
....
 android:resizeableActivity="true">


问:
Shadow left and right of UIView
Hi i like to add an CALayer Shadow to an View where the shadow was left and right of the view the simplest way was:

```<code>someView.layer.shadowColor = [[UIColor blackColor] CGColor];
someView.layer.shadowOffset = CGSizeMake(0.0f,0.0f);
someView.layer.shadowOpacity = 1.0f;
someView.layer.shadowRadius = 10.0f;
someView.layer.shadowPath = [[UIBezierPath bezierPathWithRect:someView.bounds] CGPath];
</code>```

but i will add a bigger shadow as like a shadow when i increase the shadowRadius it do not look good. How i can make a shadow that looks good at left and right.

答:
swift 3.0 version

```<code>imageView.layer.shadowOpacity = 0.8
imageView.layer.shadowOffset = CGSize(width: 0, height: 3)
imageView.layer.shadowRadius = 4.0

let shadowRect: CGRect = imageView.bounds.insetBy(dx: 0, dy: 4)
imageView.layer.shadowPath = UIBezierPath(rect: shadowRect).cgPath
</code>```

Title: Shadow left and right of UIView

Body:
Hi i like to add an CALayer Shadow to an View where the shadow was left and right of the view the simplest way was:

someView.layer.shadowColor = [[UIColor blackColor] CGColor];
someView.layer.shadowOffset = CGSizeMake(0.0f,0.0f);
someView.layer.shadowOpacity = 1.0f;
someView.layer.shadowRadius = 10.0f;
someView.layer.shadowPath = [[UIBezierPath bezierPathWithRect:someView.bounds] CGPath];

but i will add a bigger shadow as like a shadow when i increase the shadowRadius it do not look good. How i can make a shadow that looks good at left and right.

Body:
swift 3.0 version

imageView.layer.shadowOpacity = 0.8
imageView.layer.shadowOffset = CGSize(width: 0, height: 3)
imageView.layer.shadowRadius = 4.0

let shadowRect: CGRect = imageView.bounds.insetBy(dx: 0, dy: 4)
imageView.layer.shadowPath = UIBezierPath(rect: shadowRect).cgPath


问:
React Router - Stay at the same page after refresh
I'm learning React. I have page with 4 subpages and i use React Router to go through those pages. Everything works fine except for reloading page. When i go from page "home" to "about" or other it's ok, but when i refresh page then it render again page "about" for a second and then it change page to home (home is default/first page).I want it to stay at that page which is currently rendered, not go back to home after every refresh.
There is my code in index.js file where i render whole app and use router:

```<code><Provider store={store}>
    <Router path="/" history={browserHistory}>
        <Route path="/home" component={App}>
            <Route path="/" component={Home}/>
            <Route path="/allhotels" component={AllHotels}/>
            <Route path="/addhotel" component={AddHotel} />
            <Route path="/about" component={About} />
        </Route>
        <Route path="/signin" component={SignIn} />
        <Route path="/signup" component={SignUp} />
    </Router>
</Provider>, document.getElementById('root')
</code>```

In "App" i have Navigation and there i render rest of conent from Home, AllHotels etc.

There is code from App.jsx

```<code>class App extends Component {

render() {
    return (
        <div className="app-comp">
            <Navigation />
            <div> {this.props.children}</div>
        </div>
    )
  }
}
</code>```

I also attach gif which shows my problem.

https://gifyu.com/image/boMp

In backend i use Firebase if it's important.

Thanks in advance.

答:
Route tag returns the first matching component.
I think you have interchanged the paths of home and app component.

try this.

```<code><Provider store={store}>
    <Router path="/" history={browserHistory}>
        <Route path="/" component={App}>
            <Route path="/home" component={Home}/>
            <Route path="/allhotels" component={AllHotels}/>
            <Route path="/addhotel" component={AddHotel} />
            <Route path="/about" component={About} />
        </Route>
        <Route path="/signin" component={SignIn} />
        <Route path="/signup" component={SignUp} />
    </Router>
</Provider>, document.getElementById('root')
</code>```

Body:
I'm learning React. I have page with 4 subpages and i use React Router to go through those pages. Everything works fine except for reloading page. When i go from page "home" to "about" or other it's ok, but when i refresh page then it render again page "about" for a second and then it change page to home (home is default/first page).I want it to stay at that page which is currently rendered, not go back to home after every refresh.
There is my code in index.js file where i render whole app and use router:

<Provider store={store}>
    <Router path="/" history={browserHistory}>
        <Route path="/home" component={App}>
            <Route path="/" component={Home}/>
            <Route path="/allhotels" component={AllHotels}/>
            <Route path="/addhotel" component={AddHotel} />
            <Route path="/about" component={About} />
        </Route>
        <Route path="/signin" component={SignIn} />
        <Route path="/signup" component={SignUp} />
    </Router>
</Provider>, document.getElementById('root')

In "App" i have Navigation and there i render rest of conent from Home, AllHotels etc.

There is code from App.jsx

class App extends Component {

render() {
    return (

            <Navigation />

 {this.props.children}

    )
  }
}

I also attach gif which shows my problem.

https://gifyu.com/image/boMp

In backend i use Firebase if it's important.

Thanks in advance.

Body:
Route tag returns the first matching component.
I think you have interchanged the paths of home and app component.

try this.

<Provider store={store}>
    <Router path="/" history={browserHistory}>
        <Route path="/" component={App}>
            <Route path="/home" component={Home}/>
            <Route path="/allhotels" component={AllHotels}/>
            <Route path="/addhotel" component={AddHotel} />
            <Route path="/about" component={About} />
        </Route>
        <Route path="/signin" component={SignIn} />
        <Route path="/signup" component={SignUp} />
    </Router>
</Provider>, document.getElementById('root')


问:
Truncating a byte array vs. substringing the Encoded string coming out of SHA-256
I am not familiar with Hashing algorithms and the risks associated when using them and therefore have a question on the answer below that I received on a previous question . . .

Based on the comment that the hash value must, when encoded to ASCII, fit within 16 ASCI characters, the solution is first, to choose some cryptographic hash function (the SHA-2 family includes SHA-256, SHA-384, and SHA-512)
  then, to truncate the output of the chosen hash function to 96 bits (12 bytes) - that is, keep the first 12 bytes of the hash function output and discard the remaining bytes
  then, to base-64-encode the truncated output to 16 ASCII characters (128 bits)
  yielding effectively a 96-bit-strong cryptographic hash.

If I substring the base-64-encoded string to 16 characters is that fundamentally different then keeping the first 12 bytes of the hash function and then base-64-encoding them? If so, could someone please explain (provide example code) for truncating the byte array?

I tested the substring of the full hash value against 36,000+ distinct values and had no collisions. The code below  is my current implementation.

Thanks for any help (and clarity) you can provide.

```<code>public static byte[] CreateSha256Hash(string data)
{
    byte[] dataToHash = (new UnicodeEncoding()).GetBytes(data);
    SHA256 shaM = new SHA256Managed();
    byte[] hashedData = shaM.ComputeHash(dataToHash);

    return hashedData;
}

public override void InputBuffer_ProcessInputRow(InputBufferBuffer Row)
{
    byte[] hashedData = CreateSha256Hash(Row.HashString);

    string s = Convert.ToBase64String(hashedData, Base64FormattingOptions.None);

    Row.HashValue = s.Substring(0, 16);

}
</code>```

[Original post]
(http://stackoverflow.com/questions/4340471/is-there-a-hash-algorithm-that-produces-a-hash-size-of-64-bits-in-c)

答:
No, there is no difference. However, it's easier to just get the base64 string of the first 12 bytes of the array, instead of truncating the array:

```<code>public override void InputBuffer_ProcessInputRow(InputBufferBuffer Row) {

    byte[] hashedData = CreateSha256Hash(Row.HashString);

    Row.HashValue = Convert.ToBase64String(hashedData, 0, 12);

}
</code>```

The base 64 encoding simply puts 6 bits in each character, so 3 bytes (24 bits) goes into 4 characters. As long as you are splitting the data at an even 3 byte boundary, it's the same as splitting the string at the even 4 character boundary.

If you try to split the data between these boundaries, the base64 string will be padded with filler data up to the next boundary, so the result would not be the same.

Body:
I am not familiar with Hashing algorithms and the risks associated when using them and therefore have a question on the answer below that I received on a previous question . . .

Based on the comment that the hash value must, when encoded to ASCII, fit within 16 ASCI characters, the solution is first, to choose some cryptographic hash function (the SHA-2 family includes SHA-256, SHA-384, and SHA-512)
  then, to truncate the output of the chosen hash function to 96 bits (12 bytes) - that is, keep the first 12 bytes of the hash function output and discard the remaining bytes
  then, to base-64-encode the truncated output to 16 ASCII characters (128 bits)
  yielding effectively a 96-bit-strong cryptographic hash.

If I substring the base-64-encoded string to 16 characters is that fundamentally different then keeping the first 12 bytes of the hash function and then base-64-encoding them? If so, could someone please explain (provide example code) for truncating the byte array?

I tested the substring of the full hash value against 36,000+ distinct values and had no collisions. The code below  is my current implementation.

Thanks for any help (and clarity) you can provide.

public static byte[] CreateSha256Hash(string data)
{
    byte[] dataToHash = (new UnicodeEncoding()).GetBytes(data);
    SHA256 shaM = new SHA256Managed();
    byte[] hashedData = shaM.ComputeHash(dataToHash);

    return hashedData;
}

public override void InputBuffer_ProcessInputRow(InputBufferBuffer Row)
{
    byte[] hashedData = CreateSha256Hash(Row.HashString);

    string s = Convert.ToBase64String(hashedData, Base64FormattingOptions.None);

    Row.HashValue = s.Substring(0, 16);

}

[Original post]
(http://stackoverflow.com/questions/4340471/is-there-a-hash-algorithm-that-produces-a-hash-size-of-64-bits-in-c)

Body:
No, there is no difference. However, it's easier to just get the base64 string of the first 12 bytes of the array, instead of truncating the array:

public override void InputBuffer_ProcessInputRow(InputBufferBuffer Row) {

    byte[] hashedData = CreateSha256Hash(Row.HashString);

    Row.HashValue = Convert.ToBase64String(hashedData, 0, 12);

}

The base 64 encoding simply puts 6 bits in each character, so 3 bytes (24 bits) goes into 4 characters. As long as you are splitting the data at an even 3 byte boundary, it's the same as splitting the string at the even 4 character boundary.

If you try to split the data between these boundaries, the base64 string will be padded with filler data up to the next boundary, so the result would not be the same.


问:
General questions about JHipster
I am thinking about starting a project using jhipster but I still have a question remaining about the approach.
Jhipster is generating code, ok.
- Is it better to generate a project and then never use jhipster again ?
- or using the approach coding, using jhipster to edit entities, code again, jhipster, coding etc... ?

What is the best thing to do and what is your experience about it?

答:
I'm at the early stage of a JHipster generated monolith Angular2/Spring/DB application.  I'm trying to understand what parts of the code should i leave to jhipster and what parts I should customize.

Ideally, I'd like to be able to regenerate all the entities again and rebuild my project without overwriting any logic.  But I'm not sure if that is possible or I haven't figure out yet how to achieve that.

What I'm saying is that I'd be building on the generated code, rather than replacing it.

For the client side, the generate code is being kept and restricted to the admin We are building a separate UI.

We are just now adding logic to the server and only now giving proper consideration to the the following:

use of DTO

where to put the business logic

is it possible to add business logic as described above - seperate from JHipster code.. if that is desireable.

There are my thoughts.
Be very happy to hear comments back on this.

Kind regards,
Fergal.

Title: General questions about JHipster


问:
Jenkins disable tag every build in dsl
I have job dsl as below

```<code>pipelineJob('demo/Development') {
     definition {
    cpsScm {
        scm {
                 git('https://github.com/demo/demo.git','development')
        }
        scriptPath('Jenkinsfile')
    }
}
}
</code>```

When the job is created it has addtional behavior added by default for create a tag for every build. How can I disable this on the job dsl ?

答:
Managed to resolve the problem

```<code> git('https://github.com/demo/demo.git','development',{node -> node / 'extensions' << '' })
</code>```

just needed to add the configure block to get rid of the extensions block, if required it can be used to modify xml directly.

Title: Jenkins disable tag every build in dsl

Body:
I have job dsl as below

pipelineJob('demo/Development') {
     definition {
    cpsScm {
        scm {
                 git('https://github.com/demo/demo.git','development')
        }
        scriptPath('Jenkinsfile')
    }
}
}

When the job is created it has addtional behavior added by default for create a tag for every build. How can I disable this on the job dsl ?

Body:
Managed to resolve the problem

 git('https://github.com/demo/demo.git','development',{node -> node / 'extensions' << '' })

just needed to add the configure block to get rid of the extensions block, if required it can be used to modify xml directly.


问:
Microsoft SQL - "Invalid column name" after deleting column
I am using Azure SQL in Microsoft SQL Management studio. I firstly renamed a column called ssma$rowid to ssmarowid, then I deleted this column using

ALTER TABLE "myCoolTable" DROP COLUMN "ssmarowid";

SQL management studio prompted me that the deletion was successful, but now that I try to run any UPDATE commands on my table in different columns, I get this error message:

Invalid column name 'ssma$rowid'.

If I try to edit a cell without scripting, by right-clicking my table, then Edit top 200, I get this error message:

The data in row xxx was not committed.
Error Source: .Net SqlClient Data Provider.
Error Message: Invalid column name 'ssma$rowid'
Invalid column name 'ssma$rowid'
Invalid column name 'ssma$rowid'

Correct the errors and retry or press ESC to cancel the change(s)

The column ssma$rowid does not appear in my table at all when I run a SELECT statement, and if I explicitly try to pull the column ssma$rowid or ssmarowid SQL tells me that they don't exist.

It appears that my column has been lost in the ether somewhere, where can I start searching to find my rogue column?

答:
Ensure the ALTER TABLE states the column between brackets like this :

```<code>ALTER TABLE [myCoolTable] DROP COLUMN [ssmarowid];
</code>```

Body:
Ensure the ALTER TABLE states the column between brackets like this :

ALTER TABLE [myCoolTable] DROP COLUMN [ssmarowid];


问:
get_terms() orderby name is not working - wordpress
I'm using wordpress, want first-level taxonomy terms to be ordered by name but below code is not giving me desired result. Here is my code:

```<code>$args = array(
    'taxonomy' => 'tax-category',
    'hide_empty' => 0,
    'hierarchical' => 1,
    'parent' => 0,
    'orderby'=>'name',
    'order' => 'DESC',
    'fields' => 'all',
);
$rs_terms = get_terms('tax-category', $args);
</code>```

When I'm adding below php sorting, it works perfectly. But want to know why wordpress's default sorting is not working properly:

```<code>usort($rs_terms, function($a, $b){
    return strcmp($a->name, $b->name);
});
</code>```

答:
I just tested your code on my localhost and it works.</p>

```<code>                    'orderby'           => 'name',
                    'order'             => 'ASC',
                    'hide_empty'        => false,
                    'fields'            => 'all',
                    'parent'            => 0,
                    'hierarchical'      => true,
                    'child_of'          => 0,
                    'childless'         => false,
                    'pad_counts'        => false,
                    'cache_domain'      => 'core'
</code>```

Body:
I'm using wordpress, want first-level taxonomy terms to be ordered by name but below code is not giving me desired result. Here is my code:

$args = array(
    'taxonomy' => 'tax-category',
    'hide_empty' => 0,
    'hierarchical' => 1,
    'parent' => 0,
    'orderby'=>'name',
    'order' => 'DESC',
    'fields' => 'all',
);
$rs_terms = get_terms('tax-category', $args);

When I'm adding below php sorting, it works perfectly. But want to know why wordpress's default sorting is not working properly:

usort($rs_terms, function($a, $b){
    return strcmp($a->name, $b->name);
});

Body:
I just tested your code on my localhost and it works.

                    'orderby'           => 'name',
                    'order'             => 'ASC',
                    'hide_empty'        => false,
                    'fields'            => 'all',
                    'parent'            => 0,
                    'hierarchical'      => true,
                    'child_of'          => 0,
                    'childless'         => false,
                    'pad_counts'        => false,
                    'cache_domain'      => 'core'


问:
How to loop an analysis in R while iteratively removing/replacing rows from the original dataset?
I have an excel csv file with mixed data that looks similar to the sample dataframe provided below.

Given the following sample data and analysis:

```<code>#Installing packages
library(cluster)
library(vegan)

size = c(5,300,500,4000,60000,2000)
diet = c('A','A','C','D','C','D')
area = c('Ae','Te','Fo','Ae','Te','Ae')
time = c('Di','No','Di','Cr','Ca','Ca')
distance = c(50,800,60,12000,150000,4200)

DF = data.frame(size,diet,area,time,distance)
row.names(DF) = c('Bird','Rat','Cobra','Dog','Human','Fish')

#Calculate Gower distance dissimilarity matrix for species in "DF"
DF.diss = daisy(DF, metric = "gower", type = list(logratio = c("size", "distance")))
attributes(DF.diss)

#Performing hierarchical cluster analysis on dissimilarity matrix
DF.Hclust = hclust(DF.diss, method = "average")

#Calculating metric for species community based on hclust tree
treeheight(DF.Hclust)
</code>```

Starting with the all the rows as the example does, how would I go about rerunning the analysis while iteratively removing a row, rerunning the analysis, putting the row back, removing the next row, rerunning the analysis, and so on, until the analysis has been done once for every species removed/replaced.

I am interested in calculating the treeheight metric for the entire community while removing and replacing single species to gauge each of their contributions to overall treeheight.

Since my actual data set has well over 200 species it would be great if there was a way to do this in R without having to prepare over 200 separate csv files where I've removed single species and then running each through the provided analysis. Also is it possible to output each treeheight output/result to a table?

答:
You can create a loop for this:

```<code>treeheights <- matrix(-9999, nrow(DF), 1) # make matrix to store answers.
# I set -9999 as standard value so I can check if everything went alright afterwards.

for ( i in 1:nrow(DF)) {
DF.LOO <- DF[-i,] # leave one (row) out
DF.diss.LOO <- daisy(DF.LOO, metric = "gower", type = list(logratio =
c("size", "distance")))
DF.HC.LOO <- hclust(DF.diss.LOO, method = "average")
treeheights[i,] <- treeheight(DF.HC.LOO)
}
</code>```

This goes through all the rows and always leaves one row out. Hope this helps!

Body:
I have an excel csv file with mixed data that looks similar to the sample dataframe provided below.

Given the following sample data and analysis:

#Installing packages
library(cluster)
library(vegan)

size = c(5,300,500,4000,60000,2000)
diet = c('A','A','C','D','C','D')
area = c('Ae','Te','Fo','Ae','Te','Ae')
time = c('Di','No','Di','Cr','Ca','Ca')
distance = c(50,800,60,12000,150000,4200)

DF = data.frame(size,diet,area,time,distance)
row.names(DF) = c('Bird','Rat','Cobra','Dog','Human','Fish')

#Calculate Gower distance dissimilarity matrix for species in "DF"
DF.diss = daisy(DF, metric = "gower", type = list(logratio = c("size", "distance")))
attributes(DF.diss)

#Performing hierarchical cluster analysis on dissimilarity matrix
DF.Hclust = hclust(DF.diss, method = "average")

#Calculating metric for species community based on hclust tree
treeheight(DF.Hclust)

Starting with the all the rows as the example does, how would I go about rerunning the analysis while iteratively removing a row, rerunning the analysis, putting the row back, removing the next row, rerunning the analysis, and so on, until the analysis has been done once for every species removed/replaced.

I am interested in calculating the treeheight metric for the entire community while removing and replacing single species to gauge each of their contributions to overall treeheight.

Since my actual data set has well over 200 species it would be great if there was a way to do this in R without having to prepare over 200 separate csv files where I've removed single species and then running each through the provided analysis. Also is it possible to output each treeheight output/result to a table?

Body:
You can create a loop for this:

treeheights <- matrix(-9999, nrow(DF), 1) # make matrix to store answers.
# I set -9999 as standard value so I can check if everything went alright afterwards.

for ( i in 1:nrow(DF)) {
DF.LOO <- DF[-i,] # leave one (row) out
DF.diss.LOO <- daisy(DF.LOO, metric = "gower", type = list(logratio =
c("size", "distance")))
DF.HC.LOO <- hclust(DF.diss.LOO, method = "average")
treeheights[i,] <- treeheight(DF.HC.LOO)
}

This goes through all the rows and always leaves one row out. Hope this helps!


问:
Logging In: Background Details
What happens when you log into a website?

I know cookies are stored and some info (what info?) gets sent to the server...but maybe some more detail?

答:
This completely depends on the implementation of the website. Even the usage of cookies is not mandatory, but very common.

In most cases however, something like this happens:

You send in your username and password using an HTML form.

The server looks up the relevant user (using a database)

The server checks if the password matches the password that is stored in the database alongside the user.

If the password is correct, the server will store what user currently is active in the session. The identifier of this session is stored in a cookie, the actual data of this session (the current user) is stored on the server under this identifier.

Now you are logged in. You will remain logged in during the remainder of the session:

When you request another page from the server, you will send the cookie with the sesison identifier.

The server loads the session using this identifier. In this session, the current user is stored, so the server knows what user is logged in.

OwnerDisplayName: koldfyre

Title: Logging In: Background Details

LastEditorDisplayName: Jens Roland

OwnerDisplayName: wvanbergen


问:
Hbase quickly count number of rows
Right now I implement row count over ResultScanner like this

```<code>for (Result rs = scanner.next(); rs != null; rs = scanner.next()) {
    number++;
}
</code>```

If data reaching millions time computing is large.I want to compute in real time that i don't want to use Mapreduce

How to quickly count number of rows.

答:
Go to Hbase home directory and run this command,

./bin/hbase org.apache.hadoop.hbase.mapreduce.RowCounter 'namespace:tablename'

This will launch a mapreduce job and the output will show the number of records existing in  the hbase table.

Title: Hbase quickly count number of rows

Body:
Right now I implement row count over ResultScanner like this

for (Result rs = scanner.next(); rs != null; rs = scanner.next()) {
    number++;
}

If data reaching millions time computing is large.I want to compute in real time that i don't want to use Mapreduce

How to quickly count number of rows.


答:
try this it may work for you

In your manifest file, add the <supports-screens> element and specify the
android:xlargeScreens attribute to "true":

```<code><supports-screens android:xlargeScreens="true" />
</code>```

In your manifest's <uses-sdk> element, set android:targetSdkVersion to "11" or higher:

```<code><uses-sdk android:minSdkVersion="4" android:targetSdkVersion="11" />
</code>```

for more assistance please look into this page HERE

Title: Application not installing some device Android os N android

Body: I have samsung device s7 edge. Application not installed for live build. Please help me, what is an exactly problem. See this error throw, on Android N os in device.

Body:
try this it may work for you

In your manifest file, add the <supports-screens> element and specify the
android:xlargeScreens attribute to "true":

<supports-screens android:xlargeScreens="true" />

In your manifest's <uses-sdk> element, set android:targetSdkVersion to "11" or higher:

<uses-sdk android:minSdkVersion="4" android:targetSdkVersion="11" />

for more assistance please look into this page HERE


问:
how to save listbox item as .config file and read it back to listbox?
In my WPF project, I have a listbox that I can add some items to it in this way:

```<code>//item is a class type of Product
var item = GetProductByID(ProductID);
lb_Configuration.Items.Add(item);
</code>```

Now I want to save the listbox items when I close this application as a config file and when I reopen it, I can reload this config file to application thus to add the corresponding items to the listbox, how should I suppose to do this? Thanks in advance!

Edit:

```<code>    private void OpenFile_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        OpenFileDialog openFile = new OpenFileDialog();
        openFile.Multiselect = true;
        openFile.Title = "Please Choose Your File";
        openFile.Filter = "All Files(*,*)|*.*";
        if (openFile.ShowDialog() == true)
        {
            /* What to do after open file */
            StreamReader sr = File.OpenText(openFile.FileName);
            while (sr.EndOfStream != true) ;
        }
    }

    private void SaveFile_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        SaveFileDialog saveFile = new SaveFileDialog();
        saveFile.Filter = "Text File|*.txt";
        if (saveFile.ShowDialog() == true)
        {
            StreamWriter sw = File.AppendText(saveFile.FileName);
            sw.Flush();
            sw.Close();
        }
    }
</code>```

答:
Use txt file in the application directory:</p>

```<code>    public partial class MainWindow : Window
{
    private string fileName = "lst.txt";
    private List<string> lst;
    public MainWindow()
    {
        InitializeComponent();
        this.Closing += (s, e) =>
          {
              File.WriteAllLines(fileName, this.lst);
          };
    }
    //in other events, button click, initialize or change the lst

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        try
        {
            this.lst = File.ReadAllLines(fileName).ToList();
        }
        catch (Exception)
        {

        }
    }

    //simulate your other changes to the lst
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        if (lst == null)
            lst = new List<string>();
        lst.Add(new Random().Next().ToString());
    }
}
</code>```

Body:
In my WPF project, I have a listbox that I can add some items to it in this way:

//item is a class type of Product
var item = GetProductByID(ProductID);
lb_Configuration.Items.Add(item);

Now I want to save the listbox items when I close this application as a config file and when I reopen it, I can reload this config file to application thus to add the corresponding items to the listbox, how should I suppose to do this? Thanks in advance!

Edit:

    private void OpenFile_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        OpenFileDialog openFile = new OpenFileDialog();
        openFile.Multiselect = true;
        openFile.Title = "Please Choose Your File";
        openFile.Filter = "All Files(*,*)|*.*";
        if (openFile.ShowDialog() == true)
        {
            /* What to do after open file */
            StreamReader sr = File.OpenText(openFile.FileName);
            while (sr.EndOfStream != true) ;
        }
    }

    private void SaveFile_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        SaveFileDialog saveFile = new SaveFileDialog();
        saveFile.Filter = "Text File|*.txt";
        if (saveFile.ShowDialog() == true)
        {
            StreamWriter sw = File.AppendText(saveFile.FileName);
            sw.Flush();
            sw.Close();
        }
    }

Body:
Use txt file in the application directory:

    public partial class MainWindow : Window
{
    private string fileName = "lst.txt";
    private List<string> lst;
    public MainWindow()
    {
        InitializeComponent();
        this.Closing += (s, e) =>
          {
              File.WriteAllLines(fileName, this.lst);
          };
    }
    //in other events, button click, initialize or change the lst

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        try
        {
            this.lst = File.ReadAllLines(fileName).ToList();
        }
        catch (Exception)
        {

        }
    }

    //simulate your other changes to the lst
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        if (lst == null)
            lst = new List<string>();
        lst.Add(new Random().Next().ToString());
    }
}


问:
pypi see older versions of package
This is the package I'm interested in:

Django filebrowser no Grappelli

However, the latest version no longer supports Django 1.3. I need to find a version that does.
How do I see a list of older versions?

答:
Using pip you can find out all the available versions of that package:

pip install django-filebrowser-no-grappelli==randomwords
```
<p>This will produce an output of all the available packages:</p>
<pre class="lang-none prettyprint-override"><code>Could not find a version that satisfies the requirement
  django-filebrowser-no-grappelli==randomwords
(from versions: 3.1.1, 3.5.6, 3.5.7, 3.5.8, 3.6.1, 3.6.2, 3.7.0, 3.7.1, 3.7.2)
   No matching distribution found for
   django-filebrowser-no-grappelli==randomwords

</code>```

Title: pypi see older versions of package

Body:
Using pip you can find out all the available versions of that package:

pip install django-filebrowser-no-grappelli==randomwords

This will produce an output of all the available packages:

Could not find a version that satisfies the requirement
  django-filebrowser-no-grappelli==randomwords
(from versions: 3.1.1, 3.5.6, 3.5.7, 3.5.8, 3.6.1, 3.6.2, 3.7.0, 3.7.1, 3.7.2)
   No matching distribution found for
   django-filebrowser-no-grappelli==randomwords


问:
Can the jquery dataTables plugin respect alternate row colors after sorting/filtering?
I am using jquery datatables plugin which seems like a useful plugin to take a regular html table and add sorting, filtering, paging, etc

One issue i see is that when i search it doesn't seem to update the "odd" / "even" row classes so if my table has 100 rows but when i filter it has 10 it might be that all 10 are the same backcolor or 8 are the same backcolor

I see the same issue after i sort by a column as well where it might "bunch up" a bunch of rows with teh same backcolor after I sort by a column.

Is there anyway that the datatables plugin can reapply even/odd styling after the filter so no matter what you are filtering, there is always alternate row backcolor?

答:
My this comment is applicable for how to REMOVE or MODIFY Jquery Datatable Row classes

Datatables now provide an optional json parameter named as defined for its 1.10+ documentation.

so if you want to completely remove odd even classes then use the following parameter during tables initialization.

```<code>$('#example').dataTable( {
  "stripeClasses": [] //Empty Array.
} );
</code>```

so if you want to apply custom css class on every row of Datatables then.

```<code>$('#example').dataTable( {
  "stripeClasses": ['yourRowClass']
} );
</code>```

If you want to apply more than 1 css class (in odd even or sequential manner) such that these classes will repeat them-self on after every nth row is completed then use this

```<code>$('#example').dataTable( {
  "stripeClasses": [ 'strip1', 'strip2', 'strip3' ] //This combination will repeat always 3rd row
} );
</code>```

DataTables will apply each class sequentially, looping when required.

Body:
My this comment is applicable for how to REMOVE or MODIFY Jquery Datatable Row classes

Datatables now provide an optional json parameter named as defined for its 1.10+ documentation.

so if you want to completely remove odd even classes then use the following parameter during tables initialization.

$('#example').dataTable( {
  "stripeClasses": [] //Empty Array.
} );

so if you want to apply custom css class on every row of Datatables then.

$('#example').dataTable( {
  "stripeClasses": ['yourRowClass']
} );

If you want to apply more than 1 css class (in odd even or sequential manner) such that these classes will repeat them-self on after every nth row is completed then use this

$('#example').dataTable( {
  "stripeClasses": [ 'strip1', 'strip2', 'strip3' ] //This combination will repeat always 3rd row
} );

DataTables will apply each class sequentially, looping when required.


问:
MYSQL - Subquery on same table in WHERE clause of UPDATE statement
I got an "error '#1093 - You can't specify target table 't1' for update in FROM clause" with this code:

```<code>UPDATE `table1` t1 SET t1.name = 'abc'
WHERE t1.id = 165 AND NOT EXISTS (
    SELECT t2.id FROM `table1` t2 WHERE t2.id != 165 AND t2.name = 'abc'
)
</code>```

But there is no problem with the code:

```<code>UPDATE `table1` t1 SET t1.name = 'abc'
WHERE t1.id = 165 AND NOT EXISTS (
    SELECT t2.id FROM `table2` t2 WHERE t2.id != 165 AND t2.name = 'abc'
)
</code>```

What did I go wrong?

答:
You can achieve same, without using inner query:</p>

```<code>UPDATE `table1` t1 SET t1.name = 'abc'
WHERE t1.id = 165 AND t1.name != 'abc'
</code>```

Body:
I got an "error '#1093 - You can't specify target table 't1' for update in FROM clause" with this code:

UPDATE `table1` t1 SET t1.name = 'abc'
WHERE t1.id = 165 AND NOT EXISTS (
    SELECT t2.id FROM `table1` t2 WHERE t2.id != 165 AND t2.name = 'abc'
)

But there is no problem with the code:

UPDATE `table1` t1 SET t1.name = 'abc'
WHERE t1.id = 165 AND NOT EXISTS (
    SELECT t2.id FROM `table2` t2 WHERE t2.id != 165 AND t2.name = 'abc'
)

What did I go wrong?

Body:
You can achieve same, without using inner query:

UPDATE `table1` t1 SET t1.name = 'abc'
WHERE t1.id = 165 AND t1.name != 'abc'


问:
JavaScript [element].innerHTML = htmlcode is not working
There is a performance time delay in rendering window.navigate(strURL);. Until then I want display a wait message using mainContainer.innerHTML = HTMLwait; but it is not working. Any help is appreciated. Thanks!

```<code>var HTMLwait = "<div style='width:300px;height:300px;top:40%;left:45%;position:absolute;overflow:auto;display:inline;'><div style='width:50px;height:50px;top:20%;left:4%;position:absolute;overflow:auto;display:inline;'><img src='../../images/Developer/ajax-loader.gif'></div><div style='width:50px;height:50px;top:35%;left:0%;position:absolute;font-family:arial;font-size:12px;color:#000000;'>Loading...</div></div>";

var strURL = window.location.href;

var mainContainer = $(".mainContainer");
if (mainContainer != null) {
  mainContainer.innerHTML = HTMLwait;
}

window.navigate(strURL);
</code>```

答:
For jQuery objects use .html(),

```<code>$('.mainContainer').html(HTMLwait);
</code>```

If you would like to use .innerHTML property:

```<code>document.querySelector('.mainContainer').innerHTML = HTMLwait;
</code>```

var HTMLwait = "

Loading...

";

showMessage(HTMLwait);

function showMessage(message) {

  $('.mainContainer').html(HTMLwait);

  setTimeout(function() {
    console.log('time to reload the page');
    // uncomment line below
    // window.location.reload();
  }, 1000); // executed after one second
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mainContainer"></div></code>```

Body:
There is a performance time delay in rendering window.navigate(strURL);. Until then I want display a wait message using mainContainer.innerHTML = HTMLwait; but it is not working. Any help is appreciated. Thanks!

var HTMLwait = "

Loading...

";

var strURL = window.location.href;

var mainContainer = $(".mainContainer");
if (mainContainer != null) {
  mainContainer.innerHTML = HTMLwait;
}

window.navigate(strURL);

Body:
For jQuery objects use .html(),

$('.mainContainer').html(HTMLwait);

If you would like to use .innerHTML property:

document.querySelector('.mainContainer').innerHTML = HTMLwait;

var HTMLwait = "<div style='width:300px;height:300px;top:40%;left:45%;position:absolute;overflow:auto;display:inline;'><div style='width:50px;height:50px;top:20%;left:4%;position:absolute;overflow:auto;display:inline;'><img src='../../images/Developer/ajax-loader.gif'></div><div style='width:50px;height:50px;top:35%;left:0%;position:absolute;font-family:arial;font-size:12px;color:#000000;'>Loading...</div></div>";

showMessage(HTMLwait);

function showMessage(message) {

  $('.mainContainer').html(HTMLwait);

  setTimeout(function() {
    console.log('time to reload the page');
    // uncomment line below
    // window.location.reload();
  }, 1000); // executed after one second
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mainContainer"></div>


问:
Convert ArrayBuffer response to JSON
Here I am calling a GetFile , getting response as ArrayBuffer{} object, In network Tab response is {"errors":["photoProof Image is not available in the system"]}, if I do response.errors=undefined.

```<code>$scope.getDocuments = function(){
  Myservice.downLoadDocument('photo', $scope.user.mobileNo).
    then(function(response){
     })
}
</code>```

If I Do this, getting below this value in Network Tab.

```<code> response.byteLength = 64
</code>```

how do I convert  this ArrayBuffer  into proper JSON format?

答: Maby you can use json-bufferify. It's a module to help you convert between JSON and ArrayBuffer, and you can run it in both Node.js and browser.</p>

Title: Convert ArrayBuffer response to JSON

Body:
Here I am calling a GetFile , getting response as ArrayBuffer{} object, In network Tab response is {"errors":["photoProof Image is not available in the system"]}, if I do response.errors=undefined.

$scope.getDocuments = function(){
  Myservice.downLoadDocument('photo', $scope.user.mobileNo).
    then(function(response){
     })
}

If I Do this, getting below this value in Network Tab.

 response.byteLength = 64

how do I convert  this ArrayBuffer  into proper JSON format?


问:
How do I force evaluation of a cfif stored in a string?
I am trying to store coldfusion code in a database to be used for the subject of a cfmail. The code stored is as follows:

```<code>"RE: <cfif myData.general.legalName NEQ """">  {{dotlegalname}}<cfelse>{{docketLegalName}}</cfif>,
DOT## {{dot}}, Docket ##(s)   {{docketString}}"
</code>```

When I retrieve string from the database, I use cfsavecontent to attempt to evaluate it.

```<code><cfsavecontent variable="subject">
 <cfoutput>#myData.email.subject#</cfoutput>
</cfsavecontent>
</code>```

I also tried

```<code><cfsavecontent variable="subject">
     <cfoutput>#evaluate(myData.email.subject)#</cfoutput>
</cfsavecontent>
</code>```

And then I replace all the {{ }} with the appropriate values.

However, the subject of the email is stubbornly refusing to contain an evaluated cfif, and is instead showing the cfif as if it were a string.

Any ideas?

答:
To give an example: Assume code.txt is a text file that contains the following (just to facilitate simulating CFML stored in a db): <cfoutput>#now()#</cfoutput>

The following code would work:

```<code><cfset q = queryNew("code") />
<cfset queryAddRow(q,1) />
<cfset querySetCell(q, "code", fileRead(expandPath('code.txt')), 1) />
<cfdump var="#q#">
<cfset newCodeFile = expandPath('dynamic.cfm') />
<cfset fileWrite(newCodeFile, q.code[1]) />
<cfinclude template="dynamic.cfm" />
</code>```

Body:
I am trying to store coldfusion code in a database to be used for the subject of a cfmail. The code stored is as follows:

"RE: <cfif myData.general.legalName NEQ """">  {{dotlegalname}}<cfelse>{{docketLegalName}}</cfif>,
DOT## {{dot}}, Docket ##(s)   {{docketString}}"

When I retrieve string from the database, I use cfsavecontent to attempt to evaluate it.

<cfsavecontent variable="subject">
 <cfoutput>#myData.email.subject#</cfoutput>
</cfsavecontent>

I also tried

<cfsavecontent variable="subject">
     <cfoutput>#evaluate(myData.email.subject)#</cfoutput>
</cfsavecontent>

And then I replace all the {{ }} with the appropriate values.

However, the subject of the email is stubbornly refusing to contain an evaluated cfif, and is instead showing the cfif as if it were a string.

Any ideas?

Body:
To give an example: Assume code.txt is a text file that contains the following (just to facilitate simulating CFML stored in a db): <cfoutput>#now()#</cfoutput>

The following code would work:

<cfset q = queryNew("code") />
<cfset queryAddRow(q,1) />
<cfset querySetCell(q, "code", fileRead(expandPath('code.txt')), 1) />
<cfdump var="#q#">
<cfset newCodeFile = expandPath('dynamic.cfm') />
<cfset fileWrite(newCodeFile, q.code[1]) />
<cfinclude template="dynamic.cfm" />


问:
syntax error near behavioral
I'm trying to write a code for multiplying two 100x100 matrices in vhdl

```<code>    library IEEE;
    use IEEE.STD_LOGIC_1164.ALL;
    use ieee.numeric_std.all;
    library work;
    use work.mult_100x100_pack.all;

    entity multiplier_main_code is
        Port ( in_matrix1 : in  t_2d_array;
               in_matrix2 : in  t_2d_array;
               out_matrix : inout  t_2d_array);
    end multiplier_main_code;

    architecture Behavioral of multiplier_main_code is

    begin

        process(in_matrix1, in_matrix2)
        begin
             for i in 0 to 99 loop
                  for j in 0 to 99 loop
                      for k in 0 to 99 loop
                       out_matrix(i)(j) <= std_logic_vector(signed(out_matrix(i)(j)) + (signed(in_matrix1(i)(k)) * signed(in_matrix2(k)(j))));

                      end loop;
                 end loop;
          end loop;

    end Behavioral;
</code>```

Its again and again showing an error saying:
          expecting type void for "behavioral"

          syntax error near "Behavioral"

The code for mult_100X100_pack package is:

```<code>library IEEE;
use IEEE.STD_LOGIC_1164.all;
use ieee.numeric_std.all;

package mult_100x100_pack is

    type t_1d_array is array(integer range 0 to 99)of std_logic_vector(7 downto 0);
    type t_2d_array is array(integer range 0 to 99)of t_1d_array;

end mult_100x100_pack;
</code>```

Please, can anybody help me to get around this error?

答:
After fixing your indentation, it should be quite obvious what you are missing:</p>

```<code>process(in_matrix1, in_matrix2)
begin
  for i in 0 to 99 loop
    for j in 0 to 99 loop
      for k in 0 to 99 loop
        -- Do things
      end loop;
    end loop;
  end loop;
-- Perhaps `end process;` might be appropriate here...
</code>```

Title: syntax error near behavioral

Body:
I'm trying to write a code for multiplying two 100x100 matrices in vhdl

    library IEEE;
    use IEEE.STD_LOGIC_1164.ALL;
    use ieee.numeric_std.all;
    library work;
    use work.mult_100x100_pack.all;

    entity multiplier_main_code is
        Port ( in_matrix1 : in  t_2d_array;
               in_matrix2 : in  t_2d_array;
               out_matrix : inout  t_2d_array);
    end multiplier_main_code;

    architecture Behavioral of multiplier_main_code is

    begin

        process(in_matrix1, in_matrix2)
        begin
             for i in 0 to 99 loop
                  for j in 0 to 99 loop
                      for k in 0 to 99 loop
                       out_matrix(i)(j) <= std_logic_vector(signed(out_matrix(i)(j)) + (signed(in_matrix1(i)(k)) * signed(in_matrix2(k)(j))));

                      end loop;
                 end loop;
          end loop;

    end Behavioral;

Its again and again showing an error saying:
          expecting type void for "behavioral"

          syntax error near "Behavioral"

The code for mult_100X100_pack package is:

library IEEE;
use IEEE.STD_LOGIC_1164.all;
use ieee.numeric_std.all;

package mult_100x100_pack is

    type t_1d_array is array(integer range 0 to 99)of std_logic_vector(7 downto 0);
    type t_2d_array is array(integer range 0 to 99)of t_1d_array;

end mult_100x100_pack;

Please, can anybody help me to get around this error?

Body:
After fixing your indentation, it should be quite obvious what you are missing:

process(in_matrix1, in_matrix2)
begin
  for i in 0 to 99 loop
    for j in 0 to 99 loop
      for k in 0 to 99 loop
        -- Do things
      end loop;
    end loop;
  end loop;
-- Perhaps `end process;` might be appropriate here...


问:
multiple check box selection and print the checked row title alone
I have one table view with showing button, title. now i need to  check / uncheck the cell with image on cell.And at last what are the checked image cell title i need to print.How to do that?

my code:

```<code>var selectedIndexPathArray = Array<NSIndexPath>()

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! BlockedTableViewCell

        let pending = allnames?[indexPath.row]

        cell.NameLabel.text = pending?.name

        return cell
    }
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selectedIndexPathArray.append(indexPath as NSIndexPath)
        tableView.reloadData()
    }
</code>```

My cell check box image name : 'checked.png'   'unchecked.png'

答:
Update Image :

```<code> func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

            let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! BlockedTableViewCell

            let pending = allnames?[indexPath.row]

            cell.NameLabel.text = pending?.name
           if selectedIndexPathArray.contains(indexPath) {
             cell.checkboxBtn.setImage( UIImage(named:"checked.png"), for: .normal)
           } else {
             cell.checkboxBtn.setImage( UIImage(named:"unchecked.png"), for: .normal)
           }

            return cell
        }
</code>```

Printing Title :

```<code>func printSelectedItems(){

   for indexPath in selectedIndexPathArray {
      let item = allnames?[indexPath.row]
      print(item.name)
   }
}
</code>```

Body:
I have one table view with showing button, title. now i need to  check / uncheck the cell with image on cell.And at last what are the checked image cell title i need to print.How to do that?

my code:

var selectedIndexPathArray = Array<NSIndexPath>()

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! BlockedTableViewCell

        let pending = allnames?[indexPath.row]

        cell.NameLabel.text = pending?.name

        return cell
    }
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selectedIndexPathArray.append(indexPath as NSIndexPath)
        tableView.reloadData()
    }

My cell check box image name : 'checked.png'   'unchecked.png'

Body:
Update Image :

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

            let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! BlockedTableViewCell

            let pending = allnames?[indexPath.row]

            cell.NameLabel.text = pending?.name
           if selectedIndexPathArray.contains(indexPath) {
             cell.checkboxBtn.setImage( UIImage(named:"checked.png"), for: .normal)
           } else {
             cell.checkboxBtn.setImage( UIImage(named:"unchecked.png"), for: .normal)
           }

            return cell
        }

Printing Title :

func printSelectedItems(){

   for indexPath in selectedIndexPathArray {
      let item = allnames?[indexPath.row]
      print(item.name)
   }
}


问:
WebView with custom HTTP client
My task is to load web site in WebView over HTTPS with unsupported by vanilla Android TLS cipher.
Right now as proof of concept I have implemented apache http client capable of doing http requests to such resources.

What is the best approach to make WebView use my custom client implementation to do all network requests?

答:
Actually, the accepted answer is wrong. You do not get full information; what's missing are request bodies.

So you can implement GET or HEAD requests just fine, but POST requests are trickier.

I haven't seen a good solution for that yet. One I've come across uses JavaScript inserted into the page to collect the POST data, hand it to Java via a binding https://developer.android.com/guide/webapps/webview.html#BindingJavaScript and then performs the request in Java.

Unfortunately, the WebView will try to perform the same request again, so you need to add more hackery to make it work.

Title: WebView with custom HTTP client


问:
Moving average ignoring NaN
I am trying to compute a moving average on multiple columns of a matrix. After reading some answers on stackoverflow, namely this one, it seemed that the filter function was the way to go. However, it does not ignore NaN elements, and I would like to do this ignoring NaN elements in the spirit of the function nanmean. Below a sample code:

```<code>X = rand(100,100); %generate sample matrix
X(sort(randi([1 100],1,10)),sort(randi([1 100],1,10))) = NaN; %put some random NaNs
windowlenght = 7;
MeanMA = filter(ones(1, windowlenght) / windowlenght, 1, X);
</code>```

答: If you have R2016a or beyond, you can use the movmean function with the 'omitnan' option.

Title: Moving average ignoring NaN

Body:
I am trying to compute a moving average on multiple columns of a matrix. After reading some answers on stackoverflow, namely this one, it seemed that the filter function was the way to go. However, it does not ignore NaN elements, and I would like to do this ignoring NaN elements in the spirit of the function nanmean. Below a sample code:

X = rand(100,100); %generate sample matrix
X(sort(randi([1 100],1,10)),sort(randi([1 100],1,10))) = NaN; %put some random NaNs
windowlenght = 7;
MeanMA = filter(ones(1, windowlenght) / windowlenght, 1, X);


问:
What is Main Thread Checker in Xcode
I checked what's new in Xcode 9 documentation and I found this

But i didn't understand what is that how I can use this with new Xcode 9.

答:
From Apple documentation:

The Main Thread Checker is a standalone tool for Swift and C languages
  that detects invalid usage of AppKit, UIKit, and other APIs on a
  background thread. Updating UI on a thread other than the main thread
  is a common mistake that can result in missed UI updates, visual
  defects, data corruptions, and crashes.

So for example trying to change the text property of a UILabel on a background
thread will not work. Apple says that this can result in missed UI updates, visual defects, data corruptions, and crashes. In practice, 99% of the time this will result in random missed UI updates and visual defects (and not crashes).

Crashes would actually be good because we could detect easily such improper use of UIKit, but random visual defects are much harder to detect during development. And that's where the Main Thread Checker comes in.

The Main Thread Checker will help dectect uses of UIKit on a background thread, it will not solve them. Once you've detected a use of UIKit on a background thread, you can solve it using DispatchQueue.

Again, from Apple documentation:

The documentation of URLSession says that the completion closure will be called on a background thread, so this is bad, the Main Thread Checker will help you detect the use of UIKit on a background thread.

```<code>let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
   if let data = data {
      self.label.text = "\(data.count) bytes downloaded"
      // Error: label updated on background thread
   }
}
task.resume()
</code>```

Solution: Use DispatchQueue.main to perform UI updates on the main thread.

```<code>let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
   if let data = data {
      DispatchQueue.main.async { // Correct
         self.label.text = "\(data.count) bytes downloaded"
      }
   }
}
task.resume()
</code>```

The solution itself has nothing to do with Xcode, it's a feature of the language. So obviously it was possible in previous versions of Xcode, but before Xcode 9 you didn't have the Main Thread Checker to help you detect the problem.

As @hamish points out, you can also watch the WWDC video for a more detailed explanation.

Title: What is Main Thread Checker in Xcode

Body:
From Apple documentation:

The Main Thread Checker is a standalone tool for Swift and C languages
  that detects invalid usage of AppKit, UIKit, and other APIs on a
  background thread. Updating UI on a thread other than the main thread
  is a common mistake that can result in missed UI updates, visual
  defects, data corruptions, and crashes.

So for example trying to change the text property of a UILabel on a background
thread will not work. Apple says that this can result in missed UI updates, visual defects, data corruptions, and crashes. In practice, 99% of the time this will result in random missed UI updates and visual defects (and not crashes).

Crashes would actually be good because we could detect easily such improper use of UIKit, but random visual defects are much harder to detect during development. And that's where the Main Thread Checker comes in.

The Main Thread Checker will help dectect uses of UIKit on a background thread, it will not solve them. Once you've detected a use of UIKit on a background thread, you can solve it using DispatchQueue.

Again, from Apple documentation:

The documentation of URLSession says that the completion closure will be called on a background thread, so this is bad, the Main Thread Checker will help you detect the use of UIKit on a background thread.

let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
   if let data = data {
      self.label.text = "\(data.count) bytes downloaded"
      // Error: label updated on background thread
   }
}
task.resume()

Solution: Use DispatchQueue.main to perform UI updates on the main thread.

let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
   if let data = data {
      DispatchQueue.main.async { // Correct
         self.label.text = "\(data.count) bytes downloaded"
      }
   }
}
task.resume()

The solution itself has nothing to do with Xcode, it's a feature of the language. So obviously it was possible in previous versions of Xcode, but before Xcode 9 you didn't have the Main Thread Checker to help you detect the problem.

As @hamish points out, you can also watch the WWDC video for a more detailed explanation.


答:
Your process needs an end process; :

```<code>     end loop;

  end process;

end Behavioral;
</code>```

This illustrates the advantage of taking care to indent code correctly. If all your end fors lined up with their corresponding fors, this would have been obvious.

Title: syntax error near behavioral

Body:
Your process needs an end process; :

     end loop;

  end process;

end Behavioral;

This illustrates the advantage of taking care to indent code correctly. If all your end fors lined up with their corresponding fors, this would have been obvious.


问:
Android Studio wrong breakpoints
I try to debug some code, but Android Studio debugger behaves strange today.

It accepts breakpoints like randomly. Where there is no executable code preview sometimes shows there is. And for executable lines preview says that the code is not executable.

I tried to sync, clean, rebuild, invalidate cashes/restart, but notheng had effect.

Has someone faced this problem before and whta is the solution?

答: rebuild project might solve the issue.</p>

Title: Android Studio wrong breakpoints

Body: rebuild project might solve the issue.