问:
Store the multiple result sets from stored procedures to different tables
I have around 30 to 40 stored procedures which have multiple result sets as output. My actual requirement is to count the number of rows from each of the result sets from respective procedures in SQL Server.

I can alter the procedures and use count() for each of the result sets. However, practically it's a tedious job to alter 30 to 40 procedures. Rather doing the same I was trying to use openquery process and store the output of procedures into some temp table.

However, in that way I'm only able to store the first result set, not any other later result sets. Even I was trying to achieve the same using cursors but doesn't work. Can you please help me some way?

Here is the code:

```<code>  create table Orders
   (
      Slno int,
      OrderID Char(20),
      NumberOfItem int,
      CustomerID int
    )

   Create table Customer
                 (
                   CustomerID int,
           CustomerName Char(30),
                   Address nChar(50)
                  )

   Insert into Customer values (1,'Piyu','Bhubaneswar'),
                         (2,'Ranu','Bhubaneswar'),
                         (3,'Tiku','Cuttack'),
                         (4,'Lui','Bhadrak'),
                         (5,'Wasim','Bhadrak'),
                         (6,'Vivek','Dhekanal'),
                         (7,'Romeo','Puri')

    Insert into Orders Values (1,'O1',2,1),
                              (2,'O2',7,1),
              (3,'O3',20,4),
              (4,'O4',2,3),
              (5,'O5',3,3),
                  (6,'O6',1,7),
              (7,'O7',1,5),
                      (8,'O8',3,1),
              (9,'O9',2,6)

    Select * from Orders
    Select * from Customer

    Alter Procedure OrderDetails
    @Var_TotalItems Int

    As
    Begin

        Select C.CustomerName,C.[Address ],O.NumberOfItem,O.OrderID   From
        Customer C
        Join
        Orders O
        On C.CustomerID=O.CustomerID

        Select C.CustomerName,Sum(O.NumberOfItem)
        [TotalNumberOfItem],Count(O.OrderID) [TotalNumberOfOrders]   From
        Customer C
        Join
        Orders O
        On C.CustomerID=O.CustomerID
        Group by C.CustomerName
        Having Sum(O.NumberOfItem) >= @Var_TotalItems
    End

      EXEC OrderDetails 4
</code>```

Here the procedures returns multiple outputs. My objective is to count the number of rows in each of the outputs without altering the stored procedure.

答:
You can use the system variable @@ROWCOUNT to get the number of rows affected by your query.

The value of @@ROWCOUNT is updated with the number of rows affected by your last statement ( select / insert / update / delete ). so after the execution of your stored procedure, you can check the value in @@ROWCOUNT to get the number of rows returned by the procedure. Like this

```<code>declare @c int
exec OrderDetails
select @c =@@Rowcount

select @c
</code>```

Here the no of rows returned by the procedure OrderDetails will be stored in a user-defined variable @c and you can use the same for any other operations.

Please refer this Link for more details on @@ROWCOUNT

Body:
I have around 30 to 40 stored procedures which have multiple result sets as output. My actual requirement is to count the number of rows from each of the result sets from respective procedures in SQL Server.

I can alter the procedures and use count() for each of the result sets. However, practically it's a tedious job to alter 30 to 40 procedures. Rather doing the same I was trying to use openquery process and store the output of procedures into some temp table.

However, in that way I'm only able to store the first result set, not any other later result sets. Even I was trying to achieve the same using cursors but doesn't work. Can you please help me some way?

Here is the code:

  create table Orders
   (
      Slno int,
      OrderID Char(20),
      NumberOfItem int,
      CustomerID int
    )

   Create table Customer
                 (
                   CustomerID int,
           CustomerName Char(30),
                   Address nChar(50)
                  )

   Insert into Customer values (1,'Piyu','Bhubaneswar'),
                         (2,'Ranu','Bhubaneswar'),
                         (3,'Tiku','Cuttack'),
                         (4,'Lui','Bhadrak'),
                         (5,'Wasim','Bhadrak'),
                         (6,'Vivek','Dhekanal'),
                         (7,'Romeo','Puri')

    Insert into Orders Values (1,'O1',2,1),
                              (2,'O2',7,1),
              (3,'O3',20,4),
              (4,'O4',2,3),
              (5,'O5',3,3),
                  (6,'O6',1,7),
              (7,'O7',1,5),
                      (8,'O8',3,1),
              (9,'O9',2,6)

    Select * from Orders
    Select * from Customer

    Alter Procedure OrderDetails
    @Var_TotalItems Int

    As
    Begin

        Select C.CustomerName,C.[Address ],O.NumberOfItem,O.OrderID   From
        Customer C
        Join
        Orders O
        On C.CustomerID=O.CustomerID

        Select C.CustomerName,Sum(O.NumberOfItem)
        [TotalNumberOfItem],Count(O.OrderID) [TotalNumberOfOrders]   From
        Customer C
        Join
        Orders O
        On C.CustomerID=O.CustomerID
        Group by C.CustomerName
        Having Sum(O.NumberOfItem) >= @Var_TotalItems
    End

      EXEC OrderDetails 4

Here the procedures returns multiple outputs. My objective is to count the number of rows in each of the outputs without altering the stored procedure.

Body:
You can use the system variable @@ROWCOUNT to get the number of rows affected by your query.

The value of @@ROWCOUNT is updated with the number of rows affected by your last statement ( select / insert / update / delete ). so after the execution of your stored procedure, you can check the value in @@ROWCOUNT to get the number of rows returned by the procedure. Like this

declare @c int
exec OrderDetails
select @c =@@Rowcount

select @c

Here the no of rows returned by the procedure OrderDetails will be stored in a user-defined variable @c and you can use the same for any other operations.

Please refer this Link for more details on @@ROWCOUNT


来源: stackexchange

问:
Form does not read javascript before redirect to another page
I have a form, before submit the data to another page it needs to validate the input first. But the problem is the form redirect to another page without reading the javascript first.</p>

```<code><html>
<script>
    function fnValidate(){
     with document.frmAdd{
    var x;
    x = txtEmail.value;

    if( x.indexof("@")== -1)
    {   alert("A valid email address must contains @");
    return false; }
    if( isNaN(txtAge.value)== 1- )
    {   alert("Age must be filled out by number");
    return false; }
    if( txtPwd.value <> txtPwd2.value )
    {   alert("Password not matched!");
    return false; }

     } //end_with
    } //end_fnValidate()

</script>
<body>
    <form name="frmAdd" method="post" action="SaveNewUser.php" onSubmit="return fnValidate()">
        IC No    : <input type=text name="txtIc" size=20 required> <br>
        Name     : <input type=text name="txtName" size=50 required> <br>
        Email    : <input type=text name="txtEmail" size=50 required> <br>
        D.O.B    : <input type=date name="txtDOB" size=20 required> <br>
        Age      : <input type=text name="txtAge" size=5 maxlength=2 required>
        <br><br>
        Username         : <input type=text name="txtUserName" size=20
            required> <br>
        Password         : <input type=password name="txtPwd" size=20
            required> <br>
        Re-Enter Password: <input type=password name="txtPwd2" size=20
            required> <br><br>
        <input type=submit name=btnSubmit value=SAVE>
    </form>
</body>
</html>
</code>```

答:
Javascript functions should be placed inside script tags :</p>

```<code><!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script type="text/javascript">
    function fnValidate()
    {
        with document.frmAdd{

        var x;
        x = txtEmail.value;

        if( x.indexof("@")== -1)
        {   alert("A valid email address must contains @");
            return false; }
        if( isNaN(txtAge.value)== 1- )
        {   alert("Age must be filled out by number");
            return false; }
        if( txtPwd.value <> txtPwd2.value )
        {   alert("Password not matched!");
            return false; }

        } //end_with
    } //end_fnValidate()

    </script>
    </head>
    <body>
    .
    .
    .
    </body>
    </html>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a form, before submit the data to another page it needs to validate the input first. But the problem is the form redirect to another page without reading the javascript first.

    <form name="frmAdd" method="post" action="SaveNewUser.php" onSubmit="return fnValidate()">
        IC No    : <input type=text name="txtIc" size=20 required>

        Name     : <input type=text name="txtName" size=50 required>

        Email    : <input type=text name="txtEmail" size=50 required>

        D.O.B    : <input type=date name="txtDOB" size=20 required>

        Age      : <input type=text name="txtAge" size=5 maxlength=2 required>

        Username         : <input type=text name="txtUserName" size=20
            required>

        Password         : <input type=password name="txtPwd" size=20
            required>

        Re-Enter Password: <input type=password name="txtPwd2" size=20
            required>

        <input type=submit name=btnSubmit value=SAVE>
    </form>

Body:
Javascript functions should be placed inside script tags :

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script type="text/javascript">
    function fnValidate()
    {
        with document.frmAdd{

        var x;
        x = txtEmail.value;

        if( x.indexof("@")== -1)
        {   alert("A valid email address must contains @");
            return false; }
        if( isNaN(txtAge.value)== 1- )
        {   alert("Age must be filled out by number");
            return false; }
        if( txtPwd.value <> txtPwd2.value )
        {   alert("Password not matched!");
            return false; }

        } //end_with
    } //end_fnValidate()

    </script>
    </head>
    <body>
    .
    .
    .
    </body>
    </html>


问:
How to make segue wait for function to complete on button press?
I have a swift application that grabs some gps data on one view controller and then passes that data to another view controller.

My current approach involves a button, where a user will enter some data, hit this button, and then the button should perform two actions, calculate the gps routes, AND perform a segue to the next view controller.

However, I can't seem to get the segue to wait for my calculations to complete before going to the next screen. If I land on the second view and then press back, and then press the button again, the data will show up on the second screen, but I can't seem to get it to work right away.

I followed this question: Separate Button action and segue action and still am having trouble

I am a complete noob to swift so I apologize if this question is trivial

FirstViewController.swift:

```<code>....
@IBOutlet weak var calculateButton: UIButton!
var routeArray = Array<Array<MKRoute>>()
var distanceArray: [CLLocationDistance] = []

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "segue_to_table"{
        if let destination = segue.destination as? SecondTableViewController{
            destination.routeArray = self.routeArray
            destination.distanceArray = self.distanceArray
        }
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    ....
    calculateButton.addTarget(self, action: #selector(getRoutes(button:)), for: .touchUpInside)
}

func getRoutes(button: UIButton){
   locationArray = set of calculated MKMapItems
   calculateRoute(index: 0, distance: 0, routes: [], color: UIColor.green)

    locationArray = []
    locationArray = set of other MKMapItems (different route essentially)
    calculateRoute(index: 0, distance: 0, routes: [], color: UIColor.red)
}

func calculateRoute(index:Int, distance: CLLocationDistance, routes: [MKRoute], color: UIColor){
    let request: MKDirectionsRequest = MKDirectionsRequest()
    request.source = locationArray[index]

    request.destination = locationArray[index+1]

    request.requestsAlternateRoutes = true
    request.transportType = .walking

    let directions = MKDirections(request: request)
    directions.calculate(completionHandler: {(response:MKDirectionsResponse?, error: Error?) in
        if let routeResponse = response?.routes{
            var distVar = distance
            var routeVar = routes

            routeVar.append(routeResponse[0])
            distVar += routeResponse[0].distance

            if index + 2 < self.locationArray.count{
                self.calculateRoute(index: index+1, distance: distVar, routes: routeVar, color: color)

            }
            else{
                self.routeArray.append(routeVar)
                self.distanceArray.append(distVar)
            }

        }else if let _ = error{
            //alert
        }

        })

      }
</code>```

答:
It's really simple, just prevent the segue with should perform segue,

Return false if you function is not ready yet.
Once your function is ready, call the perform segue again and return true

```<code>func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
    if (identifier == "mySegueIdentifier") {
        return isComplete
    }
    return true
}
</code>```

Body:
I have a swift application that grabs some gps data on one view controller and then passes that data to another view controller.

My current approach involves a button, where a user will enter some data, hit this button, and then the button should perform two actions, calculate the gps routes, AND perform a segue to the next view controller.

However, I can't seem to get the segue to wait for my calculations to complete before going to the next screen. If I land on the second view and then press back, and then press the button again, the data will show up on the second screen, but I can't seem to get it to work right away.

I followed this question: Separate Button action and segue action and still am having trouble

I am a complete noob to swift so I apologize if this question is trivial

FirstViewController.swift:

....
@IBOutlet weak var calculateButton: UIButton!
var routeArray = Array<Array<MKRoute>>()
var distanceArray: [CLLocationDistance] = []

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "segue_to_table"{
        if let destination = segue.destination as? SecondTableViewController{
            destination.routeArray = self.routeArray
            destination.distanceArray = self.distanceArray
        }
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    ....
    calculateButton.addTarget(self, action: #selector(getRoutes(button:)), for: .touchUpInside)
}

func getRoutes(button: UIButton){
   locationArray = set of calculated MKMapItems
   calculateRoute(index: 0, distance: 0, routes: [], color: UIColor.green)

    locationArray = []
    locationArray = set of other MKMapItems (different route essentially)
    calculateRoute(index: 0, distance: 0, routes: [], color: UIColor.red)
}

func calculateRoute(index:Int, distance: CLLocationDistance, routes: [MKRoute], color: UIColor){
    let request: MKDirectionsRequest = MKDirectionsRequest()
    request.source = locationArray[index]

    request.destination = locationArray[index+1]

    request.requestsAlternateRoutes = true
    request.transportType = .walking

    let directions = MKDirections(request: request)
    directions.calculate(completionHandler: {(response:MKDirectionsResponse?, error: Error?) in
        if let routeResponse = response?.routes{
            var distVar = distance
            var routeVar = routes

            routeVar.append(routeResponse[0])
            distVar += routeResponse[0].distance

            if index + 2 < self.locationArray.count{
                self.calculateRoute(index: index+1, distance: distVar, routes: routeVar, color: color)

            }
            else{
                self.routeArray.append(routeVar)
                self.distanceArray.append(distVar)
            }

        }else if let _ = error{
            //alert
        }

        })

      }

Body:
It's really simple, just prevent the segue with should perform segue,

Return false if you function is not ready yet.
Once your function is ready, call the perform segue again and return true

func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
    if (identifier == "mySegueIdentifier") {
        return isComplete
    }
    return true
}


问:
Pako not able to deflate gzip files generated in python
I'm generating gzip files from python using the following code: (using python 3)

```<code>    file = gzip.open('output.json.gzip', 'wb')
    dataToWrite = json.dumps(data).encode('utf-8')
    file.write(dataToWrite)
    file.close()
</code>```

However, I'm trying to read this file now in Javascript using the Pako library (I'm using Angular 2):

```<code>this.http.get("output.json.gzip")
      .map((res:Response) => {
        var resText:any = new Uint8Array(res.arrayBuffer());
        var result = "";
        try {
          result = pako.inflate(resText, {"to": "string"});
        } catch (err) {
          console.log("Error " + err);
        }
        return result;

      });
</code>```

But I'm getting this error in the console: unknown compression method. Should I be doing something else to properly inflate gzip files?

答:
Turns out that I needed to use the res.blob() function to get the true binary data, not res.arrayBuffer(); and then convert the blob to the array buffer:</p>

```<code>return this.http.get("output.json.gzip", new RequestOptions({ responseType: ResponseContentType.Blob }))
      .map((res:Response) => {
        var blob = res.blob();
        var arrayBuffer;
        var fileReader = new FileReader();
        fileReader.onload = function() {
            arrayBuffer = this.result;
            try {
              let result:any = pako.ungzip(new Uint8Array(arrayBuffer), {"to": "string"});
              let obj = JSON.parse(result);
              console.log(obj);
            } catch (err) {
              console.log("Error " + err);
            }
        };
        fileReader.readAsArrayBuffer(blob);
        return "abc";
      });
</code>```

Body:
I'm generating gzip files from python using the following code: (using python 3)

    file = gzip.open('output.json.gzip', 'wb')
    dataToWrite = json.dumps(data).encode('utf-8')
    file.write(dataToWrite)
    file.close()

However, I'm trying to read this file now in Javascript using the Pako library (I'm using Angular 2):

this.http.get("output.json.gzip")
      .map((res:Response) => {
        var resText:any = new Uint8Array(res.arrayBuffer());
        var result = "";
        try {
          result = pako.inflate(resText, {"to": "string"});
        } catch (err) {
          console.log("Error " + err);
        }
        return result;

      });

But I'm getting this error in the console: unknown compression method. Should I be doing something else to properly inflate gzip files?

Body:
Turns out that I needed to use the res.blob() function to get the true binary data, not res.arrayBuffer(); and then convert the blob to the array buffer:

return this.http.get("output.json.gzip", new RequestOptions({ responseType: ResponseContentType.Blob }))
      .map((res:Response) => {
        var blob = res.blob();
        var arrayBuffer;
        var fileReader = new FileReader();
        fileReader.onload = function() {
            arrayBuffer = this.result;
            try {
              let result:any = pako.ungzip(new Uint8Array(arrayBuffer), {"to": "string"});
              let obj = JSON.parse(result);
              console.log(obj);
            } catch (err) {
              console.log("Error " + err);
            }
        };
        fileReader.readAsArrayBuffer(blob);
        return "abc";
      });


问:
jQuery masonry not working with Safari
I'm using jQuery Masonry with a WordPress installation and it works fine in every browser but Safari (both Win and OSX). Could this be related to some jQuery/WebKit issues with .load() firing too early? I'm quite new to jQuery/JavaScript, so any help is greatly appreciated.

This page doesn't work in Safari: http://tangomitstil.de/news/

While this page (for some reason) does: http://tangomitstil.de/info/unterricht/

The problem is not related to the number of items (I'm experiencing the same problem with my dev version with a rather large set of test posts), @font-face embedding, use of images, or the Infinite Scroll plugin.

Here is the code called in the header section:

```<code>jQuery(window).load(function($) {
    // We can only load masonry on window.load because of embedded swfobjects
    jQuery('.content').masonry({
        singleMode: true,
        resizable: true,
        animate: false
    }); // initiate masonry
    jQuery('.content').infinitescroll({
        navSelector: "div.navigation",
        // selector for the paged navigation (it will be hidden)
        nextSelector: "div.navigation div.nav-previous a",
        // selector for the NEXT link (to page 2)
        itemSelector: ".content div.post",
        // selector for all items you'll retrieve
        loadingText: "Lädt weitere Beiträge..."
    }, function(newElements) {
        jQuery(this).masonry({
            appendedContent: jQuery(newElements)
        });
    })
});
</code>```

答:
Try to use the "DOM ready" event, which fires after the "load" event (when images have finished loading etc.).

jQuery has a nice shortcut for that. Instead of

```<code>jQuery(window).load(function() {
  // ...
});
</code>```

do

```<code>jQuery(function() {
  // ...
});
</code>```

Or, simply:

```<code>$(function() {
  // ...
});
</code>```

When you do not use any other JS framework in parallel, it's safe and convenient to use $ in place of jQuery.

ContentLicense: CC BY-SA 2.5

Title: jQuery masonry not working with Safari

Body:
I'm using jQuery Masonry with a WordPress installation and it works fine in every browser but Safari (both Win and OSX). Could this be related to some jQuery/WebKit issues with .load() firing too early? I'm quite new to jQuery/JavaScript, so any help is greatly appreciated.

This page doesn't work in Safari: http://tangomitstil.de/news/

While this page (for some reason) does: http://tangomitstil.de/info/unterricht/

The problem is not related to the number of items (I'm experiencing the same problem with my dev version with a rather large set of test posts), @font-face embedding, use of images, or the Infinite Scroll plugin.

Here is the code called in the header section:

jQuery(window).load(function($) {
    // We can only load masonry on window.load because of embedded swfobjects
    jQuery('.content').masonry({
        singleMode: true,
        resizable: true,
        animate: false
    }); // initiate masonry
    jQuery('.content').infinitescroll({
        navSelector: "div.navigation",
        // selector for the paged navigation (it will be hidden)
        nextSelector: "div.navigation div.nav-previous a",
        // selector for the NEXT link (to page 2)
        itemSelector: ".content div.post",
        // selector for all items you'll retrieve
        loadingText: "Lädt weitere Beiträge..."
    }, function(newElements) {
        jQuery(this).masonry({
            appendedContent: jQuery(newElements)
        });
    })
});

Body:
Try to use the "DOM ready" event, which fires after the "load" event (when images have finished loading etc.).

jQuery has a nice shortcut for that. Instead of

jQuery(window).load(function() {
  // ...
});

do

jQuery(function() {
  // ...
});

Or, simply:

$(function() {
  // ...
});

When you do not use any other JS framework in parallel, it's safe and convenient to use $ in place of jQuery.


问:
Replace string ${stringKey} on file before war task on gradle
I 've a multi-project gradle configuration. So I've got a build.gradle for each subproject and another one where I define general tasks.

Basicly, in the general build.gradle file I set out performing environtments, each one for production, pre-production, development, and so on purposes.

I set several containers defining a class:

```<code>class RemoteContainer {
    String name
    String container
    String hostname
    Integer port
    String username
    String password
    String purpose
}
</code>```

So, I set the purpose of the container setting purpose field to 'production', 'pre-production' or 'development'.

Then, I'm able to create several containers:

```<code>def developmentRemoteContainers = [
    new RemoteContainer(
        name: 'wildfly8',
        container: 'wildfly8x',
        hostname: '----',
        port: ----,
        username: '----',
        password: '----'
        purpose: 'development'
    ),
    new RemoteContainer(
        name: 'glassfish4',
        container: 'glassfish4x',
        hostname: '----',
        port: ----,
        username: '----',
        password: '----'
        purpose: 'development'
    )
]

def preproductionRemoteContainers = [
    new RemoteContainer(
        name: 'wildfly8',
        container: 'wildfly8x',
        hostname: '----',
        port: ----,
        username: '----',
        password: '----'
        purpose: 'pro-production'
    ),
    new RemoteContainer(
        name: 'glassfish4',
        container: 'glassfish4x',
        hostname: '----',
        port: ----,
        username: '----',
        password: '----'
        purpose: 'pre-production'
    )
]

def productionUserRemoteContainers = [
    new RemoteContainer(
        name: 'wildfly8',
        container: 'wildfly8x',
        hostname: '---',
        port: ----,
        username: '----',
        password: '----'
        purpose: 'production'
    ),
    new RemoteContainer(
        name: 'glassfish4',
        container: 'glassfish4x',
        hostname: '----',
        port: ----,
        username: '----',
        password: '----'
        purpose: 'production'
    )
]
</code>```

After that, I create tasks according the content of each remote container:

Example tasks:

```<code>remoteContainers.each { config ->
    task "deployRemote${config.name.capitalize()}"(type: com.bmuschko.gradle.cargo.tasks.remote.CargoDeployRemote) {
        description = "Deploys WAR to remote Web Application Server: '${config.name}'."
        containerId = config.container
        hostname = config.hostname
        port = config.port
        username = config.username
        password = config.password
        dependsOn war
    }

    task "undeployRemote${config.name.capitalize()}"(type: com.bmuschko.gradle.cargo.tasks.remote.CargoUndeployRemote) {
        description = "Deploys WAR to remote Web Application Server: '${config.name}'."
        containerId = config.container
        hostname = config.hostname
        port = config.port
        username = config.username
        password = config.password
    }
}
</code>```

So, it's the way how I'm creating my deploy and undeploy tasks for each container and performing context.

As you're able to figure out each task depends of the war task. So, my projects have a file containing a string like ${stringKey} which I need to replace it according of each container purpose.

So, ${stringKey} must be replaced by config.purpose.

EDIT

There are basicly two files:

Under /src/main/resources/META-INF/persistence.xml: This file contains database server location information. According to the server environtment, the database location is at an IP/PORT/DATABASE... For example:

<property name="hibernate.ogm.datastore.host" value="${ip}"/>
<property name="hibernate.ogm.datastore.port" value="${port}"/>

Under /src/main/resources/configuration.settings.environtment: This file contains only this line scope = ${scope}.

The replacement must be made at war generation.

I've absolutly no idea how to do that.
Any ideas?

答:
I faced a somewhat similar issue. I found it easier to keep separate environment (e.g. dev, qa, staging, prod etc.) specific properties/settings/config and then loaded/applied a specific one at suitable time in the build life-cycle. Following links were helpful:

https://blog.gradle.org/maven-pom-profiles

Gradle : Copy different properties file depending on the environment and create jar

PS: I'm responding to a bit older question, but hopefully these pointer may be of help to someone facing a similar issue.

Body:
I 've a multi-project gradle configuration. So I've got a build.gradle for each subproject and another one where I define general tasks.

Basicly, in the general build.gradle file I set out performing environtments, each one for production, pre-production, development, and so on purposes.

I set several containers defining a class:

class RemoteContainer {
    String name
    String container
    String hostname
    Integer port
    String username
    String password
    String purpose
}

So, I set the purpose of the container setting purpose field to 'production', 'pre-production' or 'development'.

Then, I'm able to create several containers:

def developmentRemoteContainers = [
    new RemoteContainer(
        name: 'wildfly8',
        container: 'wildfly8x',
        hostname: '----',
        port: ----,
        username: '----',
        password: '----'
        purpose: 'development'
    ),
    new RemoteContainer(
        name: 'glassfish4',
        container: 'glassfish4x',
        hostname: '----',
        port: ----,
        username: '----',
        password: '----'
        purpose: 'development'
    )
]

def preproductionRemoteContainers = [
    new RemoteContainer(
        name: 'wildfly8',
        container: 'wildfly8x',
        hostname: '----',
        port: ----,
        username: '----',
        password: '----'
        purpose: 'pro-production'
    ),
    new RemoteContainer(
        name: 'glassfish4',
        container: 'glassfish4x',
        hostname: '----',
        port: ----,
        username: '----',
        password: '----'
        purpose: 'pre-production'
    )
]

def productionUserRemoteContainers = [
    new RemoteContainer(
        name: 'wildfly8',
        container: 'wildfly8x',
        hostname: '---',
        port: ----,
        username: '----',
        password: '----'
        purpose: 'production'
    ),
    new RemoteContainer(
        name: 'glassfish4',
        container: 'glassfish4x',
        hostname: '----',
        port: ----,
        username: '----',
        password: '----'
        purpose: 'production'
    )
]

After that, I create tasks according the content of each remote container:

Example tasks:

remoteContainers.each { config ->
    task "deployRemote${config.name.capitalize()}"(type: com.bmuschko.gradle.cargo.tasks.remote.CargoDeployRemote) {
        description = "Deploys WAR to remote Web Application Server: '${config.name}'."
        containerId = config.container
        hostname = config.hostname
        port = config.port
        username = config.username
        password = config.password
        dependsOn war
    }

    task "undeployRemote${config.name.capitalize()}"(type: com.bmuschko.gradle.cargo.tasks.remote.CargoUndeployRemote) {
        description = "Deploys WAR to remote Web Application Server: '${config.name}'."
        containerId = config.container
        hostname = config.hostname
        port = config.port
        username = config.username
        password = config.password
    }
}

So, it's the way how I'm creating my deploy and undeploy tasks for each container and performing context.

As you're able to figure out each task depends of the war task. So, my projects have a file containing a string like ${stringKey} which I need to replace it according of each container purpose.

So, ${stringKey} must be replaced by config.purpose.

EDIT

There are basicly two files:

Under /src/main/resources/META-INF/persistence.xml: This file contains database server location information. According to the server environtment, the database location is at an IP/PORT/DATABASE... For example:

<property name="hibernate.ogm.datastore.host" value="${ip}"/>
<property name="hibernate.ogm.datastore.port" value="${port}"/>

Under /src/main/resources/configuration.settings.environtment: This file contains only this line scope = ${scope}.

The replacement must be made at war generation.

I've absolutly no idea how to do that.
Any ideas?


问:
ms excel turn columns into rows
I am looking for a way to take an excel spread sheet and change the columns to rows. The sheet is currently designed like this.

```<code>Employee Name   Expiration 1     Expiration 2    Expiration  3  Expiration 4
John Doe
Jane Doe
</code>```

What I need to do is convert it to this

```<code>Employee Name    Expiration     Date
John Doe             1           12-12-12
John Doe             2           12-12-12
John Doe             3           12-12-12
John Doe             4           12-12-12
Jane Doe             1           12-1-12
Jane Doe             2           12-1-12
Jane Doe             3           12-1-12
Jane Doe             4           12-1-12
</code>```

I am not even sure if this is possible.

答:
You can do this very simply with an INDEX(MATCH(),MATCH()) formula.

This screenshot should be enough to get you started:

Screenshot(1)

Let me know if you need any more info.

ContentLicense: CC BY-SA 4.0

Title: ms excel turn columns into rows

Body:
I am looking for a way to take an excel spread sheet and change the columns to rows. The sheet is currently designed like this.

Employee Name   Expiration 1     Expiration 2    Expiration  3  Expiration 4
John Doe
Jane Doe

What I need to do is convert it to this

Employee Name    Expiration     Date
John Doe             1           12-12-12
John Doe             2           12-12-12
John Doe             3           12-12-12
John Doe             4           12-12-12
Jane Doe             1           12-1-12
Jane Doe             2           12-1-12
Jane Doe             3           12-1-12
Jane Doe             4           12-1-12

I am not even sure if this is possible.


问:
Spark error: Initial job has not accepted any resources; check your cluster UI to ensure that workers are registered and have sufficient resources
I have a virtual machine in which a spark-2.0.0-bin-hadoop2.7 in standalone mode is installed.

I ran ./sbin/start-all.sh to run the master and the slave.

When I do ./bin/spark-shell --master spark://192.168.43.27:7077 --driver-memory 600m --executor-memory 600m --executor-cores 1 in the machine itself the task's status is RUNNING and I am able to compute code in spark shell.

When I do exactly the same command from another machine in the network, the status is "RUNNING" again, but the spark-shell throws WARN TaskSchedulerImpl: Initial job has not accepted any resources; check your cluster UI to ensure that workers are registered and have sufficient resources. I guess the problem is not directly related to resources because the same command works in the virtual machine itself, but not when it comes from other machines.

I checked most of the topics related to this error and none of them solved my problem. I even disabled firewall with sudo ufw disable just to make sure but no success (based on this link) which suggests:

Disable Firewall on the client : This was the solution that worked for me. Since I was working on a prototype in-house code, I disabled the firewall on the client node. For some reason the worker nodes, were not able to talk back to the client for me. For production purposes, you would want to open-up certain number of ports required.

答:
There are two known reasons for this:

Your application requires more resources (cores, memory) than allocated. Increasing worker cores and memory should solve it. Most other answers focus on this.

Where less known, the firewall is blocking the communication between master and workers. This could happen especially you are using cloud service. According to Spark Security, besides the standard 8080, 8081, 7077, 4040 ports, you also need to make sure the master and worker can communicate via the SPARK_WORKER_PORT, spark.driver.port and spark.blockManager.port; the latter three are used by submitting jobs and are randomly assigned by the program (if left unconfigured). You may try to open all ports to run a quick test.


问:
Hadoop 2.9.0 - hadoop namenode -format and hdfs-site.xml dfs.namenode.name.dir
My 1st question, I'll try not to screw up too bad :)

I am installing Hadoop 2.9.0 on a 4 nodes cluster, for learning purpose.
I have started with namenode installation/configuration following the official Apache Hadoop 2.9.0 documentation and some google pages.

I edited my hdfs-site.xml located under $HADOOP_HOME/etc/hadoop directory like so :

```<code>  <property>
    <name>dfs.namenode.name.dir</name>
    <value>file:///apps/hdfs/namenode/data</value>
  </property>
  <property>
    <name>dfs.datanode.data.dir</name>
    <value>file:///apps/hdfs/datanode/data</value>
  </property>
  <property>
    <name>dfs.namenode.checkpoint.dir</name>
    <value>file:///apps/hdfs/namesecondary/data</value>
  </property>
</code>```

When I run the "hadoop namenode -format" it format the default $hadoop.tmp.dir under /tmp/hadoop-hadoop/...

Found some pages that said to set the HADOOP_CONF_DIR to where the XML configurations files are (ie : $HADOOP_HOME/etc/hadoop) but also some that said the opposite, to not set it.

In my case, it did fix my problem but not sure if it's the right modification?

If anyone could help me out to understand this, it would be great :)

Thank alot!

答:
It's not really clear what problem you were having, but there's a default setting for HADOOP_CONF_DIR which is set in a hadoop-env.sh file that's loaded prior to all hadoop commands.

I believe this might be simply /etc/hadoop. At least, that's where most clusters store the configs

Since your files are elsewhere, you needed to export that value to something else, which is fine.

Personally, I suggest use Apache Ambari instead of manual managing and installing more than 2 nodes. It'll ensure your configs are matching and additionally monitor the services

Body:
My 1st question, I'll try not to screw up too bad :)

I am installing Hadoop 2.9.0 on a 4 nodes cluster, for learning purpose.
I have started with namenode installation/configuration following the official Apache Hadoop 2.9.0 documentation and some google pages.

I edited my hdfs-site.xml located under $HADOOP_HOME/etc/hadoop directory like so :

  <property>
    <name>dfs.namenode.name.dir</name>
    <value>file:///apps/hdfs/namenode/data</value>
  </property>
  <property>
    <name>dfs.datanode.data.dir</name>
    <value>file:///apps/hdfs/datanode/data</value>
  </property>
  <property>
    <name>dfs.namenode.checkpoint.dir</name>
    <value>file:///apps/hdfs/namesecondary/data</value>
  </property>

When I run the "hadoop namenode -format" it format the default $hadoop.tmp.dir under /tmp/hadoop-hadoop/...

Found some pages that said to set the HADOOP_CONF_DIR to where the XML configurations files are (ie : $HADOOP_HOME/etc/hadoop) but also some that said the opposite, to not set it.

In my case, it did fix my problem but not sure if it's the right modification?

If anyone could help me out to understand this, it would be great :)

Thank alot!


问:
Using gulp-image or Gulp-imagemin with multiple subdirectories
I am using Gulp-image plugin atm (Also tried gulp-imagemin).

My gulpfile.js markup:

```<code>// Include gulp
const gulp = require('gulp')

// Include gulp plugins
const images = require('gulp-image')

// Image optimalization
gulp.task('images', () => {
  gulp.src('uploads/**/*')
  .pipe(images())
  .pipe(gulp.dest('./Compressed-images/'));
})

gulp.task('default', ['images'])
</code>```

Now this is where it goes wrong:

```<code>gulp.src('uploads/**/*')
</code>```

It only takes all images from the subdirectories in the directory:

```<code>uploads/
</code>```

Is there any way to access the images for multiple levels of directories without having to type them all out?

For example:

Accesing images in the directory:

```<code>uploads/sub-dir-1/sub-dir-3/sub-dir-3/
</code>```

Without having to typ something like this?

```<code>uploads/sub-dir-1/sub-dir-2/sub-dir-3/*.jpg
uploads/**/**/**/*.jpg
</code>```

I read the following posts

Gulp rename all images based on other directory

gulp-imagemin - how to disregard directory structures?

Replicating directory structure in Gulp dest

But couldn't find an answer there.

答:
What you are doing should work. I did a couple of tests and it works fine for me, I added 3 levels and it worked. Here's the output

```<code>[23:08:34] ✔ test.png -> before=69.25 KB after=20.1 KB reduced=49.15 KB(71%)
[23:08:34] ✔ sub1/sub2/ub3/test.png -> before=69.25 KB after=20.1 KB reduced=49.15 KB(71%)
[23:08:34] ✔ sub1/sub2/test.png -> before=69.25 KB after=20.1 KB reduced=49.15 KB(71%)
[23:08:34] ✔ sub1/test.png -> before=69.25 KB after=20.1 KB reduced=49.15 KB(71%)
</code>```

You can also try to use gulp-debug to see what files you're grabbing.

I'm more inclined to think that something is failing silently when the images are compressing, maybe an image is corrupt.

Body:
I am using Gulp-image plugin atm (Also tried gulp-imagemin).

My gulpfile.js markup:

// Include gulp
const gulp = require('gulp')

// Include gulp plugins
const images = require('gulp-image')

// Image optimalization
gulp.task('images', () => {
  gulp.src('uploads/**/*')
  .pipe(images())
  .pipe(gulp.dest('./Compressed-images/'));
})

gulp.task('default', ['images'])

Now this is where it goes wrong:

gulp.src('uploads/**/*')

It only takes all images from the subdirectories in the directory:

uploads/

Is there any way to access the images for multiple levels of directories without having to type them all out?

For example:

Accesing images in the directory:

uploads/sub-dir-1/sub-dir-3/sub-dir-3/

Without having to typ something like this?

uploads/sub-dir-1/sub-dir-2/sub-dir-3/*.jpg
uploads/**/**/**/*.jpg

I read the following posts

Gulp rename all images based on other directory

gulp-imagemin - how to disregard directory structures?

Replicating directory structure in Gulp dest

But couldn't find an answer there.

Body:
What you are doing should work. I did a couple of tests and it works fine for me, I added 3 levels and it worked. Here's the output

[23:08:34] ✔ test.png -> before=69.25 KB after=20.1 KB reduced=49.15 KB(71%)
[23:08:34] ✔ sub1/sub2/ub3/test.png -> before=69.25 KB after=20.1 KB reduced=49.15 KB(71%)
[23:08:34] ✔ sub1/sub2/test.png -> before=69.25 KB after=20.1 KB reduced=49.15 KB(71%)
[23:08:34] ✔ sub1/test.png -> before=69.25 KB after=20.1 KB reduced=49.15 KB(71%)

You can also try to use gulp-debug to see what files you're grabbing.

I'm more inclined to think that something is failing silently when the images are compressing, maybe an image is corrupt.


问:
Trouble with comparing 2 dimensional arrays
I keep getting a false boolean value from the following comparison:

```<code>public boolean getHz1() {
    return board[0][0] == board[0][1]
           && board[0][1] == board[0][2]
           && board[0][0] != null
           && board[0][1] != null
           && board[0][2] != null;
 }
</code>```

The relevant call in the driver class is:

```<code>do {
        System.out.println("Your turn: ");
        g1.play(s.nextInt(), s.nextInt(), s.next());
        System.out.println(g1.getHz1());
} while (g1.getHz1() == false)
</code>```

The "play" method takes 2 integers and a string value to put in the array, in this case "x".  When I print out the board[0][0], board[0][1] and board[0][2], all contain the string "x", but getHz1 still returns false.

答:
As others have mentioned, you need to use .equals for objects (e.g., String, HashMap, anything that is created with new), and the == operator for native datatypes (e.g., int, long, char, etc.).  The warning, however, is that .equals is a function on an object, so you first need to make sure the object is not null.  Hence this pattern:

```<code>if ( obj != null && obj.someFunction() )
</code>```

When comparing objects, you can also let the .equals function do the null check for you:

```<code>SomeObject goodObj = new SomeObject();
SomeObject badObj = null;

if ( goodObj.equals( badObj ) )  // should work properly, no matter the state of badObj
</code>```

In your case, you need to check that your objects are not null first, and then compare the objects appropriately with .equals:

```<code>public boolean getHz1() {
    return (
        (null == board[0][0] == board[0][1] == board[0][2])
     || (null != board[0][0] && board[0][0].equals(board[0][1]) && board[0][0].equals(board[0][2]))
    );
}
</code>```

Presumably, if they're all null, they're also all equivalent, hence the first line.  The next line checks the only other way they could be equal (they're all not null, but arbitrarily check the first cell for nullness).

Body:
I keep getting a false boolean value from the following comparison:

public boolean getHz1() {
    return board[0][0] == board[0][1]
           && board[0][1] == board[0][2]
           && board[0][0] != null
           && board[0][1] != null
           && board[0][2] != null;
 }

The relevant call in the driver class is:

do {
        System.out.println("Your turn: ");
        g1.play(s.nextInt(), s.nextInt(), s.next());
        System.out.println(g1.getHz1());
} while (g1.getHz1() == false)

The "play" method takes 2 integers and a string value to put in the array, in this case "x".  When I print out the board[0][0], board[0][1] and board[0][2], all contain the string "x", but getHz1 still returns false.

Body:
As others have mentioned, you need to use .equals for objects (e.g., String, HashMap, anything that is created with new), and the == operator for native datatypes (e.g., int, long, char, etc.).  The warning, however, is that .equals is a function on an object, so you first need to make sure the object is not null.  Hence this pattern:

if ( obj != null && obj.someFunction() )

When comparing objects, you can also let the .equals function do the null check for you:

SomeObject goodObj = new SomeObject();
SomeObject badObj = null;

if ( goodObj.equals( badObj ) )  // should work properly, no matter the state of badObj

In your case, you need to check that your objects are not null first, and then compare the objects appropriately with .equals:

public boolean getHz1() {
    return (
        (null == board[0][0] == board[0][1] == board[0][2])
     || (null != board[0][0] && board[0][0].equals(board[0][1]) && board[0][0].equals(board[0][2]))
    );
}

Presumably, if they're all null, they're also all equivalent, hence the first line.  The next line checks the only other way they could be equal (they're all not null, but arbitrarily check the first cell for nullness).


问:
statement exposure in poisson regression using R
I am trying to fit the model from Frome(1983) in R using poisson Regression, but i dont know how add the exposure: ln(person-years), the model is:

ln E(Y|X)= ln(person-years)+ B0+ B1X1+ B2X2.

Do you know how fit that ?

答:
You can perform poisson regression analysis using the below R code.

m1<- glm(y  ~  offset(log(person-years))+X1+X2, family="poisson",  data=dat)
summary(m1)

Because you use an offset of 'log(person-years)', the coefficient of 'log(person-years)' is forced to be 1.


问:
Preserve Order for Cross Validation in Weka
I am using the Weka GUI for classifying sensor data.

I have measures of 10 people, the data is sorted. So the first 10% correspond to participant 1, the second 10% to participant 2 etc.

I would like to use 10 fold cross validation to build a model on 9 participants and test it on the remaining participant. In my case I believe I could accomplish this by simply not randomizing the data splits.

How would I best go about doing this?

答:
I don't know how to do this in the Explorer.

In the KnowledgeFlow GUI, there is a CrossValidationFoldMaker used to create cross-validation folds.  This has an option to Preserve instances order, which says it preserves the order of instances rather than randomly shuffling.

There's a video describing the KnowledgeFlow interface here:
https://www.youtube.com/watch?v=sHSgoVX9z-8&t=7s


问:
How to add different colours to front and back of shape with material side double in a-frame
Working with a-frame - Lets say I have a 2d shape such as a triangle or plane. If I set the material to side: double - is it possible to have different colours/materials on the 2 sides?
Here is an example of what I'm working with

```<code> <a-triangle
            vertex-a="11.25 0 -18.75"
            vertex-b="15 0 -20"
            vertex-c="10 0 -20"
            color="red"
            material="side: double"
            shadow>
          </a-triangle>
</code>```

And I would like for example, for the triangle to have a red front and a black back.

Is this currently possible? Thank you

答: Material side double is to make a geometry visible on both sides. You can simulate a single plane or triangle with two different sides with two planes or triangles oriented in oposite directions and different colors. </p>

Body:
Working with a-frame - Lets say I have a 2d shape such as a triangle or plane. If I set the material to side: double - is it possible to have different colours/materials on the 2 sides?
Here is an example of what I'm working with

And I would like for example, for the triangle to have a red front and a black back.

Is this currently possible? Thank you


问:
v-for not displaying content
I am having an issue with v-for inside my component..

code:

```<code>  <modal v-if="showModal" @close="showModal = false">
    <h1 slot="header">
      {{modalData.title}}
    </h1>
    <p slot="body">
      {{modalData.assignee}} <!-- works -->
      <div v-for="a in modalData.assignee">
        <p>Testing v-for iterate</p> <!-- does not display -->
      </div>
    </p>
  </modal>
</code>```

The value of modalData.assignee is

```<code>[ { "id": 4, "username": "testUser" } ]
</code>```

This is exactly what displays where {{modalData.assignee}} is, however I do not see the message Testing v-for iterate.

modalData.title also displays correctly.

Am I doing something obviously wrong?

I noticed that directly assigning the username also fixes the problem.

```<code>this.$root.$on('modalEvent', function(event) {
  this.showModal = true;
  this.modalData = event;
  this.modalData.assignee = this.modalData.assignee[0].username //works
}),
</code>```

答:
The issue appears to be due to invalid markup.

A
 tag should not have other block-level children. Change

```<code><p slot="body">
</code>```

to

```<code><div slot="body">
</code>```

or any other valid element and it all works fine.

Demo ~ https://jsfiddle.net/efa0u103/

Title: v-for not displaying content

Body:
I am having an issue with v-for inside my component..

code:

  <modal v-if="showModal" @close="showModal = false">

      {{modalData.title}}

      {{modalData.assignee}}

Testing v-for iterate

  </modal>

The value of modalData.assignee is

[ { "id": 4, "username": "testUser" } ]

This is exactly what displays where {{modalData.assignee}} is, however I do not see the message Testing v-for iterate.

modalData.title also displays correctly.

Am I doing something obviously wrong?

I noticed that directly assigning the username also fixes the problem.

this.$root.$on('modalEvent', function(event) {
  this.showModal = true;
  this.modalData = event;
  this.modalData.assignee = this.modalData.assignee[0].username //works
}),

Body:
The issue appears to be due to invalid markup.

A <p> tag should not have other block-level children. Change

<p slot="body">

to

<div slot="body">

or any other valid element and it all works fine.

Demo ~ https://jsfiddle.net/efa0u103/


问:
Php error in code while updating the data in sql
I get an error Undefined variable name, address, and id though I have defined it. I have used isset function but it is not working. Also, some HTML code appears in the name and address field.

```<code> <?php
$link=mysqli_connect("localhost","root","");
$select=mysqli_select_db($link,'first_db');

if(isset($_POST['update'])){
     $id=$_POST['id'];
     $query="SELECT * FROM list WHERE id='$id'";
     $run=mysqli_query($link,$query);
     $row=mysqli_fetch_array($run);
 }
if(isset($_POST['name'])&& isset($_POST['address'])){
    $name=$_POST['name'];
    $address=$_POST['address'];
    $id = $_POST['id'];
    $query="UPDATE list SET name='$name',address='$address' WHERE id='$id'";
    $result=mysqli_query($link,$query);
}
else{
    echo"The fields cannot be empty";
}

?>
</code>```

The HTML code is:

```<code>  <html>
    <head>
        <title>Edit Data</title>
    </head>

    <body>
        <a href="index.php">Home</a>
        <br/><br/>

        <form name="form1" method="post" action="update.php">
            <table border="0">
                <tr>
                    <td>Name</td>
                    <td><input type="text" name="name" value="<?php echo $name;?>"></td>
                </tr>
                <tr>
                    <td>address</td>
                    <td><input type="text" name="address" value="<?php echo $address;?>"></td>
                </tr>

                <tr>
                   <td><input type="hidden" name="id" value="<?php echo $_GET['id'];?>"></td>
                    <td><input type="submit" name="update" value="Update"></td>
                </tr>
            </table>
        </form>
    </body>
    </html>
</code>```

答:
```<code><?php
$link=mysqli_connect("localhost","root","");
$select=mysqli_select_db($link,'first_db');

if(isset($_POST['update'])){
     $id=$_POST['id'];
     $query="SELECT * FROM list WHERE id='$id'";
     $run=mysqli_query($link,$query);
     $row=mysqli_fetch_array($run);
 }
if(isset($_POST['name'])&& isset($_POST['address'])){
    $name=$_POST['name'];
    $address=$_POST['address'];
    $id = $_POST['id'];
    $query="UPDATE list SET name='$name',address='$address' WHERE id='$id'";
    $result=mysqli_query($link,$query);
}
else{
    echo"The fields cannot be empty";
}

?>
</code>```

The html code is:

```<code><html>
<head>
    <title>Edit Data</title>
</head>

<body>
    <a href="index.php">Home</a>
    <br/><br/>

    <form name="form1" method="post" action="update.php">
        <table border="0">
            <tr>
                <td>Name</td>
                <td><input type="text" name="name" value="<?php echo $name;?>"></td>
            </tr>
            <tr>
                <td>address</td>
                <td><input type="text" name="address" value="<?php echo $address;?>"></td>
            </tr>

            <tr>
               <td><input type="hidden" name="id" value="<?php echo $_GET['id'];?>"></td>
                <td><input type="submit" name="update" value="Update"></td>
            </tr>
        </table>
    </form>
</body>
</html>
</code>```

Body:
I get an error Undefined variable name, address, and id though I have defined it. I have used isset function but it is not working. Also, some HTML code appears in the name and address field.

 <?php
$link=mysqli_connect("localhost","root","");
$select=mysqli_select_db($link,'first_db');

if(isset($_POST['update'])){
     $id=$_POST['id'];
     $query="SELECT * FROM list WHERE id='$id'";
     $run=mysqli_query($link,$query);
     $row=mysqli_fetch_array($run);
 }
if(isset($_POST['name'])&& isset($_POST['address'])){
    $name=$_POST['name'];
    $address=$_POST['address'];
    $id = $_POST['id'];
    $query="UPDATE list SET name='$name',address='$address' WHERE id='$id'";
    $result=mysqli_query($link,$query);
}
else{
    echo"The fields cannot be empty";
}

?>

The HTML code is:

        <title>Edit Data</title>

        Home

        <form name="form1" method="post" action="update.php">

                    Name
                    <input type="text" name="name" value="<?php echo $name;?>">

                    address
                    <input type="text" name="address" value="<?php echo $address;?>">

                   <input type="hidden" name="id" value="<?php echo $_GET['id'];?>">
                    <input type="submit" name="update" value="Update">

        </form>

Body:
<?php
$link=mysqli_connect("localhost","root","");
$select=mysqli_select_db($link,'first_db');

if(isset($_POST['update'])){
     $id=$_POST['id'];
     $query="SELECT * FROM list WHERE id='$id'";
     $run=mysqli_query($link,$query);
     $row=mysqli_fetch_array($run);
 }
if(isset($_POST['name'])&& isset($_POST['address'])){
    $name=$_POST['name'];
    $address=$_POST['address'];
    $id = $_POST['id'];
    $query="UPDATE list SET name='$name',address='$address' WHERE id='$id'";
    $result=mysqli_query($link,$query);
}
else{
    echo"The fields cannot be empty";
}

?>

The html code is:

<html>
<head>
    <title>Edit Data</title>
</head>

<body>
    <a href="index.php">Home</a>
    <br/><br/>

    <form name="form1" method="post" action="update.php">
        <table border="0">
            <tr>
                <td>Name</td>
                <td><input type="text" name="name" value="<?php echo $name;?>"></td>
            </tr>
            <tr>
                <td>address</td>
                <td><input type="text" name="address" value="<?php echo $address;?>"></td>
            </tr>

            <tr>
               <td><input type="hidden" name="id" value="<?php echo $_GET['id'];?>"></td>
                <td><input type="submit" name="update" value="Update"></td>
            </tr>
        </table>
    </form>
</body>
</html>


问:
Python-OpenCV cv2 OpenCV Error: Assertion failed
I'm trying to create an image in python using openCV. I make a list of lists, each list having 16 numbers, from 0 to 255 (16 lists). Then I convert the big list in a numpy ndarray, and try to write that into an image using cv2.imwrite(). This is my code:

```<code>import cv2
import numpy as np

colours = []
numbers = []
a=0
for i in range(256):
    numbers.append(a)
    a+=1

for x in range(16):
    new_list = [numbers[16*x:16*x+16]]
    colours.append(new_list)

col = np.asarray(colours)
new_image = cv2.imwrite("rainbow.png",col)
</code>```

It runs well until the last line. Then it gives me this error:

```<code>OpenCV Error: Assertion failed (image.channels() == 1 || image.channels() == 3 || image.channels() == 4) in cv::imwrite_, file C:\projects\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp, line 600
Traceback (most recent call last):
  File "kormou.py", line 16, in <module>
    new_image = cv2.imwrite("rainbow.png",col)
cv2.error: C:\projects\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp:600: error: (-215) image.channels() == 1 || image.channels() == 3 || image.channels() == 4 in function cv::imwrite_
</code>```

In generally I'm a beginner so it may be something very obvious which I'm missing but I haven't been able to find similar error question here.

答:
There is this very minute mistake you are doing. Figure out from the following working code -

```<code>import cv2
import numpy as np

colours = []
numbers = []
a=0
for i in range(256):
    numbers.append(a)
    a+=1

for x in range(16):
    new_list = numbers[16*x:16*x+16]
    colours.append(new_list)

print colours
col = np.asarray(colours)
new_image_flag = cv2.imwrite("rain.png",col)
</code>```

Check edit for hint.

Body:
I'm trying to create an image in python using openCV. I make a list of lists, each list having 16 numbers, from 0 to 255 (16 lists). Then I convert the big list in a numpy ndarray, and try to write that into an image using cv2.imwrite(). This is my code:

import cv2
import numpy as np

colours = []
numbers = []
a=0
for i in range(256):
    numbers.append(a)
    a+=1

for x in range(16):
    new_list = [numbers[16*x:16*x+16]]
    colours.append(new_list)

col = np.asarray(colours)
new_image = cv2.imwrite("rainbow.png",col)

It runs well until the last line. Then it gives me this error:

OpenCV Error: Assertion failed (image.channels() == 1 || image.channels() == 3 || image.channels() == 4) in cv::imwrite_, file C:\projects\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp, line 600
Traceback (most recent call last):
  File "kormou.py", line 16, in <module>
    new_image = cv2.imwrite("rainbow.png",col)
cv2.error: C:\projects\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp:600: error: (-215) image.channels() == 1 || image.channels() == 3 || image.channels() == 4 in function cv::imwrite_

In generally I'm a beginner so it may be something very obvious which I'm missing but I haven't been able to find similar error question here.

Body:
There is this very minute mistake you are doing. Figure out from the following working code -

import cv2
import numpy as np

colours = []
numbers = []
a=0
for i in range(256):
    numbers.append(a)
    a+=1

for x in range(16):
    new_list = numbers[16*x:16*x+16]
    colours.append(new_list)

print colours
col = np.asarray(colours)
new_image_flag = cv2.imwrite("rain.png",col)

Check edit for hint.


问:
When analyzing the time complexity of an algorithm why do we drop the constant of the term with the largest degree
Suppose I have the following : T(n) = 5n^2 +2n
The asymtotic tight bound of this is theta n^2. I want to understand the reason behind dropping the 5. I understand why we ignore the lower order terms.</p>

答:
wEverything comes back to the concept of "Order of Magnitute". Given something like

5n^2 +2n

You think that the 5 is significant, however when you break it down and think about the numbers, the constant really doesn't matter (graph it and you will see why). For example .. say n is 50.

5 * 50^2 + 2 * 50 --> 5 * 2500 + 2 * 50 --> 12,600

As you mentioned, the 2*n is insignificant when compared to n^2. This same concept applies when viewing the constant as well... you might think that 2500 vs 125,000 is a big difference; however consider if the algorithm was n^3... you are now looking at 12,600 vs 625,100

So  the factor that will have the most significant difference on the cost of an algorithm is just n^2.


问:
Changing url on loading another html file in a div using only javascript
I am trying to load another html file into a div.I successfuly got that.
Now I also need my url to change accordingly.
how to change the url on loading another html file in a div??
I need this only using javascript

```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <input id="tab1" type="radio" name="tabs" checked >
          <label for="tab1" onclick="load_tab1()">
            <span>
              <img src="image/idea.svg">
            </span>TAB1</label>

          <input id="tab2" type="radio" name="tabs">
          <label for="tab2" onclick="load_tab2()">
            <span>
              <img src="image/idea.svg">
            </span>TAB2</label>

  <div class="master_content" id="scroll_bar">
          <div class="page_head">Page 1</div>
          <div class="page">
          <section id="content1" id="scroll_bar">

          </section>

          <section id="content2">

          </section>

          <section id="content3">

          </section>

          <section id="content4">

          </section>

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

答:
Use history.pushState
Check https://developer.mozilla.org/en-US/docs/Web/API/History_API for more details</p>

Body:
I am trying to load another html file into a div.I successfuly got that.
Now I also need my url to change accordingly.
how to change the url on loading another html file in a div??
I need this only using javascript

  <input id="tab1" type="radio" name="tabs" checked >

            TAB1

          <input id="tab2" type="radio" name="tabs">

            TAB2

Page 1


问:
How do I host my Mvc web app using plesk panel?
I have registerd my own domain name and web hosting space too on parallels

thay are having there plesk control panel.

I know that for html pages I need to copy my all pages into httpdoc folder

```<code>But what about by MVC WEBSITE?

HOW DO I HOST IT?
</code>```

CAN ANYONE HELP ME?

答:
Select the following assemblies:

System.Web.Mvc

System.Web.Routing

System.Web.Abstractions

In the Properties window, set Copy Local to True.

then upload bin folder in mvc to the server. this may fix the issue

Body:
I have registerd my own domain name and web hosting space too on parallels

thay are having there plesk control panel.

I know that for html pages I need to copy my all pages into httpdoc folder

But what about by MVC WEBSITE?

HOW DO I HOST IT?

CAN ANYONE HELP ME?


问:
How to modify URL for Wordpress in config files, not through the Admin Console
My Wordpress site has an incorrect URL so when I access the domain "phoenixadultsoccerleague.com" it doesn't work.  You'll see "Home" and "About" links.  When you hover over those links you'll see a different URL.

How can I go into the configuration files and update the URL so the Wordpress site will come up?  It should be pointing to "phoenixadultsoccerleague.com"  Is it in the DB files or the PHP files in the file structure?

Thank you in advance.

答:
You may do this through the WordPress database.
Open the database and look for wp_optio ns and then " home URL" and "Site URL".</p>


问:
Create a 12 Character Secret
I need to create some secret 12 character string in C#. It can only have regular latin characters plus digits.

Any ideas of best practices?

Thanks

答:
For this task I'm using mainly the code described here.

```<code>public class PasswordGenerator
{
    private const string AlphaUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private const string AlphaLower = "abcdefghijklmnopqrstuvwxyz";
    private const string Numeric = "1234567890";
    private const string Special = "@#$?!";
    private const string AllChars = AlphaUpper + AlphaLower + Numeric + Special;

    private readonly MersenneTwister _random = new MersenneTwister();

    /// <summary>
    /// Generates a strong password out of upper case, lower case, numeric and special characters.
    /// </summary>
    /// <param name="length">The length of the password to generate. Must be at least 4.</param>
    /// <returns>A random strong password.</returns>
    public string Generate(int length)
    {
        string password = string.Empty;

        // generate four repeating random numbers for lower, upper, numeric and special characters
        // by filling these positions with corresponding characters, we can ensure the password has
        // at least one character of each type
        string posArray = "0123456789";

        if (length < posArray.Length)
            posArray = posArray.Substring(0, length);

        int pLower = GetRandomPosition(ref posArray);
        int pUpper = GetRandomPosition(ref posArray);
        int pNumber = GetRandomPosition(ref posArray);
        int pSpecial = GetRandomPosition(ref posArray);

        for (int i = 0; i < length; i++)
        {
            if (i == pLower)
            {
                password += GetRandomChar(AlphaUpper);
            }
            else if (i == pUpper)
            {
                password += GetRandomChar(AlphaLower);
            }
            else if (i == pNumber)
            {
                password += GetRandomChar(Numeric);
            }
            else if (i == pSpecial)
            {
                password += GetRandomChar(Special);
            }
            else
            {
                password += GetRandomChar(AllChars);
            }
        }

        return password;
    }

    private string GetRandomChar(string fullString)
    {
        return fullString.ToCharArray()[(int)Math.Floor(_random.NextDouble() * fullString.Length)].ToString();
    }

    private int GetRandomPosition(ref string posArray)
    {
        string randomChar = posArray.ToCharArray()[(int)Math.Floor(_random.NextDouble() * posArray.Length)].ToString();
        int pos = int.Parse(randomChar);
        posArray = posArray.Replace(randomChar, string.Empty);

        return pos;
    }
}
</code>```

You just want't to get rid of the special character set.

Instead of using the .NET Random class described in the article, I'm using the Mersenne Twister algorithm to generate pseudorandom numbers.

Title: Create a 12 Character Secret

Body:
For this task I'm using mainly the code described here.

public class PasswordGenerator
{
    private const string AlphaUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private const string AlphaLower = "abcdefghijklmnopqrstuvwxyz";
    private const string Numeric = "1234567890";
    private const string Special = "@#$?!";
    private const string AllChars = AlphaUpper + AlphaLower + Numeric + Special;

    private readonly MersenneTwister _random = new MersenneTwister();

    /// <summary>
    /// Generates a strong password out of upper case, lower case, numeric and special characters.
    /// </summary>
    /// <param name="length">The length of the password to generate. Must be at least 4.</param>
    /// <returns>A random strong password.</returns>
    public string Generate(int length)
    {
        string password = string.Empty;

        // generate four repeating random numbers for lower, upper, numeric and special characters
        // by filling these positions with corresponding characters, we can ensure the password has
        // at least one character of each type
        string posArray = "0123456789";

        if (length < posArray.Length)
            posArray = posArray.Substring(0, length);

        int pLower = GetRandomPosition(ref posArray);
        int pUpper = GetRandomPosition(ref posArray);
        int pNumber = GetRandomPosition(ref posArray);
        int pSpecial = GetRandomPosition(ref posArray);

        for (int i = 0; i < length; i++)
        {
            if (i == pLower)
            {
                password += GetRandomChar(AlphaUpper);
            }
            else if (i == pUpper)
            {
                password += GetRandomChar(AlphaLower);
            }
            else if (i == pNumber)
            {
                password += GetRandomChar(Numeric);
            }
            else if (i == pSpecial)
            {
                password += GetRandomChar(Special);
            }
            else
            {
                password += GetRandomChar(AllChars);
            }
        }

        return password;
    }

    private string GetRandomChar(string fullString)
    {
        return fullString.ToCharArray()[(int)Math.Floor(_random.NextDouble() * fullString.Length)].ToString();
    }

    private int GetRandomPosition(ref string posArray)
    {
        string randomChar = posArray.ToCharArray()[(int)Math.Floor(_random.NextDouble() * posArray.Length)].ToString();
        int pos = int.Parse(randomChar);
        posArray = posArray.Replace(randomChar, string.Empty);

        return pos;
    }
}

You just want't to get rid of the special character set.

Instead of using the .NET Random class described in the article, I'm using the Mersenne Twister algorithm to generate pseudorandom numbers.


问:
ggplot2 density plotting different size of data in R
I have two data sets, their size is 500 and 1000. I want to plot density for these two data sets in one plot.

I have done some search in google.

r-geom-density-values-in-y-axis

ggplot2-plotting-two-or-more-overlapping-density-plots-on-the-same-graph/

the data sets in above threads are the same

```<code>df <- data.frame(x = rnorm(1000, 0, 1), y = rnorm(1000, 0, 2), z = rnorm(1000, 2, 1.5))
</code>```

But if I have different data size, I should normalize the data first in order to compare the density between data sets.

Is it possible to make density plot with different data size in ggplot2?

答:
By default, all densities are scaled to unit area. If you have two datasets with different amounts of data, you can plot them together like so:

```<code>df1 <- data.frame(x = rnorm(1000, 0, 2))
df2 <- data.frame(y = rnorm(500, 1, 1))

ggplot() +
  geom_density(data = df1, aes(x = x),
               fill = "#E69F00", color = "black", alpha = 0.7) +
  geom_density(data = df2, aes(x = y),
               fill = "#56B4E9", color = "black", alpha = 0.7)
</code>```

However, from your latest comment, I take that that's not what you want. Instead, you want the areas under the density curves to be scaled relative to the amount of data in each group. You can do that with the ..count.. aesthetics:

```<code>df1 <- data.frame(x = rnorm(1000, 0, 2), label=rep('df1', 1000))
df2 <- data.frame(x = rnorm(500, 1, 1), label=rep('df2', 500))
df=rbind(df1, df2)

ggplot(df, aes(x, y=..count.., fill=label)) +
  geom_density(color = "black", alpha = 0.7) +
  scale_fill_manual(values = c("#E69F00", "#56B4E9"))
</code>```

Body:
I have two data sets, their size is 500 and 1000. I want to plot density for these two data sets in one plot.

I have done some search in google.

r-geom-density-values-in-y-axis

ggplot2-plotting-two-or-more-overlapping-density-plots-on-the-same-graph/

the data sets in above threads are the same

df <- data.frame(x = rnorm(1000, 0, 1), y = rnorm(1000, 0, 2), z = rnorm(1000, 2, 1.5))

But if I have different data size, I should normalize the data first in order to compare the density between data sets.

Is it possible to make density plot with different data size in ggplot2?

Body:
By default, all densities are scaled to unit area. If you have two datasets with different amounts of data, you can plot them together like so:

df1 <- data.frame(x = rnorm(1000, 0, 2))
df2 <- data.frame(y = rnorm(500, 1, 1))

ggplot() +
  geom_density(data = df1, aes(x = x),
               fill = "#E69F00", color = "black", alpha = 0.7) +
  geom_density(data = df2, aes(x = y),
               fill = "#56B4E9", color = "black", alpha = 0.7)

However, from your latest comment, I take that that's not what you want. Instead, you want the areas under the density curves to be scaled relative to the amount of data in each group. You can do that with the ..count.. aesthetics:

df1 <- data.frame(x = rnorm(1000, 0, 2), label=rep('df1', 1000))
df2 <- data.frame(x = rnorm(500, 1, 1), label=rep('df2', 500))
df=rbind(df1, df2)

ggplot(df, aes(x, y=..count.., fill=label)) +
  geom_density(color = "black", alpha = 0.7) +
  scale_fill_manual(values = c("#E69F00", "#56B4E9"))


问:
The font-awesome icon does not show up on Chrome
I meet problem that fontawesome Icon does not show up on Chrome. ( Safari and Moz both works fine ). Does anyone have a clew why this happened. Thanks All.

Here is the Snapshot:

I know that the default font path that fontawesome.min.css directs ../font/......, but I have changed path name to " ../fonts/ " for my project, still doesn't work. The icon never shows up.

答:
I had a similar issue, and I resolved it with these steps:

Open your font-awesome.min.css file

Search for webfonts, which is the default parent folder name of the fonts. If you found a bunch, then replace each of them with the name of your fonts folder in your project.

...This way, the font references inside your ..min.css  points to the correct directory path where your fonts are :)

I found out this out by opening chrome dev tools in incognito mode, and looking at the console errors.


问:
ngIf to find substr
```<code>       <ul class="list-group" *ngFor="let head of channelDisplayHeads">
        <li class="list-group-item" *ngFor="let channel of channelList" ngIf="channel.channel.indexOf('head') === 1">
          <strong>{{ head }}</strong>
        </li>
      </ul>
</code>```

<p>Here the ngFor loop displays group heads like "A", "B", "C" etc. For each group head I am trying to list the channels starting with that letter in which the for loop is in. I am trying to accomplish this behavior using ngIf, but it doesn't seem to work as expected. Please advise! </p>

答:
Finally this code worked as expected   </p>

```<code> <ul class="list-group" *ngFor="let head of channelDisplayHeads">
                <h1>{{ head }}</h1>
                <ng-container *ngFor="let channel of channelList">
                  <li class="list-group-item" *ngIf="channel.channel.substr(0, 1) === head">
                    <strong></strong>
                    <strong>{{ channel.channel }} </strong>
                  </li>
                </ng-container>
              </ul>
</code>```

Title: ngIf to find substr

Body:
          {{ head }}

Here the ngFor loop displays group heads like "A", "B", "C" etc. For each group head I am trying to list the channels starting with that letter in which the for loop is in. I am trying to accomplish this behavior using ngIf, but it doesn't seem to work as expected. Please advise!

Body:
Finally this code worked as expected

 <ul class="list-group" *ngFor="let head of channelDisplayHeads">
                <h1>{{ head }}</h1>
                <ng-container *ngFor="let channel of channelList">
                  <li class="list-group-item" *ngIf="channel.channel.substr(0, 1) === head">
                    <strong></strong>
                    <strong>{{ channel.channel }} </strong>
                  </li>
                </ng-container>
              </ul>


问:
Ionic 2 / Ionic 3 : How to get current location of a device
None of the answers on stackoverflow  worked for me. A lot of them are for Ionic 1 or those answers are deprecated or they are not working for android device.

I have seen a lot of solutions on stackoverflow about getting current location of device but non of them seems to be working for Android .

what i have tried:-

using geolocation.getCurrentPosition() , which is working for IOS and browser but not for Android.

using this.geolocation.watchPosition()  , which is working for IOS and browser but not for Android.

using navigator.geolocation.getCurrentPosition(),which is working for IOS and browser but not for Android.

using fiddle solution provided by this question getCurrentPosition() and watchPosition() are deprecated on insecure origins

Anyway , all of these are deprecated by google due to :-

getCurrentPosition() and watchPosition() are deprecated on insecure
  origins, and support will be removed in the future. You should
  consider switching your application to a secure origin, such as HTTPS.
  See goo.gl/rStTGz for more details.

what worked for me is (https://ionicframework.com/docs/native/background-geolocation/ ) & (https://www.joshmorony.com/adding-background-geolocation-to-an-ionic-2-application/ ) both  of these are based on background-geolocation plugin but,it's  taking almost 50-55 sec on Android device, again it's working fine for ios

The problem with joshmorony(https://www.joshmorony.com/adding-background-geolocation-to-an-ionic-2-application/ ) solution is foreground is not working for Android physical devices but working fine for browser and ios. Background tracking is working fine , which is taking almost 50 sec to give lat & lng for the first time.

Please help me with this. I want a way to get current location in minimum time. For your info, I am using google javascript map sdk / api .

答:
I tried every solution provided by all of you and others also on internet. Finally i found a solution.You can try this plugin cordova-plugin-advanced-geolocation (https://github.com/Esri/cordova-plugin-advanced-geolocation ) from ESRI . But this plugin will work for Android not IOS. For ios you can go with same old approach . i.e - using this.geolocation.getCurrentPosition(...) or this.geolocation.watchPosition(..).

Add cordova-plugin-advanced-geolocation Plugin Like this :-

```<code>cordova plugin add https://github.com/esri/cordova-plugin-advanced-geolocation.git
</code>```

then Add below line at the top of Class / Component

declare var AdvancedGeolocation:any; //at the top of class

Now add these lines inside relevant function of component ( P.S. - I have included code for both Android & IOS)

```<code>//**For Android**

    if (this.platform.is('android')) {
          this.platform.ready().then(() => {
            AdvancedGeolocation.start((success) => {
              //loading.dismiss();
              // this.refreshCurrentUserLocation();
              try {
                var jsonObject = JSON.parse(success);
                console.log("Provider " + JSON.stringify(jsonObject));
                switch (jsonObject.provider) {
                  case "gps":
                    console.log("setting gps ====<<>>" + jsonObject.latitude);

                    this.currentLat = jsonObject.latitude;
                    this.currentLng = jsonObject.longitude;
                    break;

                  case "network":
                    console.log("setting network ====<<>>" + jsonObject.latitude);

                    this.currentLat = jsonObject.latitude;
                    this.currentLng = jsonObject.longitude;

                    break;

                  case "satellite":
                    //TODO
                    break;

                  case "cell_info":
                    //TODO
                    break;

                  case "cell_location":
                    //TODO
                    break;

                  case "signal_strength":
                    //TODO
                    break;
                }
              }
              catch (exc) {
                console.log("Invalid JSON: " + exc);
              }
            },
              function (error) {
                console.log("ERROR! " + JSON.stringify(error));
              },
              {
                "minTime": 500,         // Min time interval between updates (ms)
                "minDistance": 1,       // Min distance between updates (meters)
                "noWarn": true,         // Native location provider warnings
                "providers": "all",     // Return GPS, NETWORK and CELL locations
                "useCache": true,       // Return GPS and NETWORK cached locations
                "satelliteData": false, // Return of GPS satellite info
                "buffer": false,        // Buffer location data
                "bufferSize": 0,         // Max elements in buffer
                "signalStrength": false // Return cell signal strength data
              });

          });
        } else {

          // **For IOS**

          let options = {
            frequency: 1000,
            enableHighAccuracy: false
          };

          this.watch = this.geolocation.watchPosition(options).filter((p: any) => p.code === undefined).subscribe((position: Geoposition) => {
            // loading.dismiss();
            console.log("current location at login" + JSON.stringify(position));

            // Run update inside of Angular's zone
            this.zone.run(() => {
              this.currentLat = position.coords.latitude;
              this.currentLng = position.coords.longitude;
            });

          });
        }
</code>```

EDIT : First installation is always going fine. But Sometimes you might get errors for no reason in subsequent installations. To make this error (any error with this plugin ) go away.Follow these steps :

1. Remove this plugin from your project (including config.xml and package.json).

2. Delete/Remove android platform.

3. Delete plugins folder.

4. Now reinstall this plugin again, following the steps above.

Body:
I tried every solution provided by all of you and others also on internet. Finally i found a solution.You can try this plugin cordova-plugin-advanced-geolocation (https://github.com/Esri/cordova-plugin-advanced-geolocation ) from ESRI . But this plugin will work for Android not IOS. For ios you can go with same old approach . i.e - using this.geolocation.getCurrentPosition(...) or this.geolocation.watchPosition(..).

Add cordova-plugin-advanced-geolocation Plugin Like this :-

cordova plugin add https://github.com/esri/cordova-plugin-advanced-geolocation.git

then Add below line at the top of Class / Component

declare var AdvancedGeolocation:any; //at the top of class

Now add these lines inside relevant function of component ( P.S. - I have included code for both Android & IOS)

//**For Android**

    if (this.platform.is('android')) {
          this.platform.ready().then(() => {
            AdvancedGeolocation.start((success) => {
              //loading.dismiss();
              // this.refreshCurrentUserLocation();
              try {
                var jsonObject = JSON.parse(success);
                console.log("Provider " + JSON.stringify(jsonObject));
                switch (jsonObject.provider) {
                  case "gps":
                    console.log("setting gps ====<<>>" + jsonObject.latitude);

                    this.currentLat = jsonObject.latitude;
                    this.currentLng = jsonObject.longitude;
                    break;

                  case "network":
                    console.log("setting network ====<<>>" + jsonObject.latitude);

                    this.currentLat = jsonObject.latitude;
                    this.currentLng = jsonObject.longitude;

                    break;

                  case "satellite":
                    //TODO
                    break;

                  case "cell_info":
                    //TODO
                    break;

                  case "cell_location":
                    //TODO
                    break;

                  case "signal_strength":
                    //TODO
                    break;
                }
              }
              catch (exc) {
                console.log("Invalid JSON: " + exc);
              }
            },
              function (error) {
                console.log("ERROR! " + JSON.stringify(error));
              },
              {
                "minTime": 500,         // Min time interval between updates (ms)
                "minDistance": 1,       // Min distance between updates (meters)
                "noWarn": true,         // Native location provider warnings
                "providers": "all",     // Return GPS, NETWORK and CELL locations
                "useCache": true,       // Return GPS and NETWORK cached locations
                "satelliteData": false, // Return of GPS satellite info
                "buffer": false,        // Buffer location data
                "bufferSize": 0,         // Max elements in buffer
                "signalStrength": false // Return cell signal strength data
              });

          });
        } else {

          // **For IOS**

          let options = {
            frequency: 1000,
            enableHighAccuracy: false
          };

          this.watch = this.geolocation.watchPosition(options).filter((p: any) => p.code === undefined).subscribe((position: Geoposition) => {
            // loading.dismiss();
            console.log("current location at login" + JSON.stringify(position));

            // Run update inside of Angular's zone
            this.zone.run(() => {
              this.currentLat = position.coords.latitude;
              this.currentLng = position.coords.longitude;
            });

          });
        }

EDIT : First installation is always going fine. But Sometimes you might get errors for no reason in subsequent installations. To make this error (any error with this plugin ) go away.Follow these steps :

1. Remove this plugin from your project (including config.xml and package.json).

2. Delete/Remove android platform.

3. Delete plugins folder.

4. Now reinstall this plugin again, following the steps above.


问:
SQL Casting Assistance
```<code>INSERT INTO PRODUCTDIM (PROD_SKU, PROD_DESCRIPTION, PROD_TYPE, LGPRODUCT.BRAND_ID, BRAND_NAME, BRAND_TYPE)
    SELECT PROD_SKU, PROD_DESCRIPT, PROD_TYPE, lgproduct.BRAND_ID, BRAND_NAME, BRAND_TYPE
    FROM LGPRODUCT INNER JOIN LGBRAND ON lgproduct.brand_id = lgbrand.brand_id
</code>```

I am getting this error:

Conversion failed when converting the varchar value '1010-MIW' to data type int.

Need help

答:
```<code>INSERT INTO PRODUCTDIM (
                        PROD_SKU,
                        PROD_DESCRIPTION,
                        PROD_TYPE,
                        BRAND_ID,
                        BRAND_NAME,
                        BRAND_TYPE
                        )

                            SELECT PROD_SKU,
                                   PROD_DESCRIPT,
                                   PROD_TYPE,
                                   lgproduct.BRAND_ID,
                                   BRAND_NAME,
                                   BRAND_TYPE

                            FROM LGPRODUCT INNER JOIN LGBRAND ON LGPRODUCT .brand_id =  LGBRAND .brand_id;
</code>```

Title: SQL Casting Assistance

Body:
INSERT INTO PRODUCTDIM (PROD_SKU, PROD_DESCRIPTION, PROD_TYPE, LGPRODUCT.BRAND_ID, BRAND_NAME, BRAND_TYPE)
    SELECT PROD_SKU, PROD_DESCRIPT, PROD_TYPE, lgproduct.BRAND_ID, BRAND_NAME, BRAND_TYPE
    FROM LGPRODUCT INNER JOIN LGBRAND ON lgproduct.brand_id = lgbrand.brand_id

I am getting this error:

Conversion failed when converting the varchar value '1010-MIW' to data type int.

Need help


问:
How do I stack bootstrap grid columns one below the other instead of one beside another?
I am just beginning to learn Bootstrap and I came across the grid system. I was playing around and noticed that the grid columns always start from the left and go towards the right, placing the divs one beside another. How do I make them appear one below the other?
Here's some sample code:

```<code><body>

<div class="container-fluid">
  <h2>Three Equal Columns</h2>
  <div class="row">
    <div class="col-4 bg-success">.col-1</div>
    <div class="col-4 bg-warning">.col-2</div>
    <div class="col-4 bg-success">.col-3</div>
  </div>
</div>

</body>
</code>```

Here's a fiddle.
https://jsfiddle.net/txdqjf8b/2/

How do I make col-1, col-2 and col-3 appear one below the other, so that later if I have a col-4, col-5 and col-6, I want them like this:

```<code>col-1    col-4    col-7
col-2    col-5    col-8
col-3    col-6    col-9
</code>```

答:
There is a feature in CSS3 when you can define an element with multiple columns. But, I don't think that all the browser supports this feature.

Or it may conflict with the bootstrap css.

```<code>-webkit-column-count: 3; /* Chrome, Safari, Opera */
-moz-column-count: 3; /* Firefox */
column-count: 3;
</code>```

.row {
    -webkit-column-count: 3; /* Chrome, Safari, Opera */
    -moz-column-count: 3; /* Firefox */
    column-count: 3;
}
.col{
 width: 200px;
    height: 50px;
    border: 1px solid black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
 <div class="col">col 1</div>
    <div class="col">col 2</div>
    <div class="col">col 3</div>
    <div class="col">col 4</div>
    <div class="col">col 5</div>
    <div class="col">col 6</div>
</div></code>```

https://www.w3.org/TR/css-multicol-1/

https://www.w3schools.com/css/tryit.asp?filename=trycss3_column-count

Body:
I am just beginning to learn Bootstrap and I came across the grid system. I was playing around and noticed that the grid columns always start from the left and go towards the right, placing the divs one beside another. How do I make them appear one below the other?
Here's some sample code:

Three Equal Columns

.col-1

.col-2

.col-3

Here's a fiddle.
https://jsfiddle.net/txdqjf8b/2/

How do I make col-1, col-2 and col-3 appear one below the other, so that later if I have a col-4, col-5 and col-6, I want them like this:

col-1    col-4    col-7
col-2    col-5    col-8
col-3    col-6    col-9

Body:
There is a feature in CSS3 when you can define an element with multiple columns. But, I don't think that all the browser supports this feature.

Or it may conflict with the bootstrap css.

-webkit-column-count: 3; /* Chrome, Safari, Opera */
-moz-column-count: 3; /* Firefox */
column-count: 3;

.row {
    -webkit-column-count: 3; /* Chrome, Safari, Opera */
    -moz-column-count: 3; /* Firefox */
    column-count: 3;
}
.col{
 width: 200px;
    height: 50px;
    border: 1px solid black;
}

<div class="row">
 <div class="col">col 1</div>
    <div class="col">col 2</div>
    <div class="col">col 3</div>
    <div class="col">col 4</div>
    <div class="col">col 5</div>
    <div class="col">col 6</div>
</div>

https://www.w3.org/TR/css-multicol-1/

https://www.w3schools.com/css/tryit.asp?filename=trycss3_column-count