问:
Problems with SQLite database, error when creating
i got this error when i start my app:

12-20 22:27:01.447: ERROR/Database(716): Failure 1 (near ":00": syntax error) on 0x1a4338 when preparing 'CREATE TABLE permission ( fk_email1 varchar(100) NOT NULL, fk_email2 varchar(100) NOT NULL, validated tinyint(4) default 0, hour1 time default 08:00:00, hour2 time default 20:00:00, date1 date default NULL, date2 date default NULL, weekend tinyint(4) default 0, fk_type varchar(45) default NULL, PRIMARY KEY  (fk_email1,fk_email2))'.

here is the code where i am creating the database:

```<code>private static final String PERMISSION_TABLE_CREATE =
"CREATE TABLE permission ("
"fk_email1 varchar(100) NOT NULL, fk_email2 varchar(100) NOT NULL, "
"validated tinyint(4) default 0, hour1 time default 08:00:00, "
"hour2 time default 20:00:00, date1 date default NULL, "
"date2 date default NULL, weekend tinyint(4) default 0, "
"fk_type varchar(45) default NULL, PRIMARY KEY  (fk_email1,fk_email2))";

private static final String USER_TABLE_CREATE = "CREATE TABLE user ( "
"email varchar(100) NOT NULL, password varchar(45) default NULL, "
"fullName varchar(80) default NULL, "
"mobilePhone varchar(14) default NULL, "
"mobileOperatingSystem varchar(20) default NULL, PRIMARY KEY  (email))";
</code>```

what i am doing bad?

答:
http://www.sqlite.org/faq.html#q2

(2) What datatypes does SQLite
  support?

SQLite uses dynamic typing. Content can be stored as INTEGER,
  REAL, TEXT, BLOB, or as NULL.

Use INTEGER, for instance, it can store Java's long.

Body:
i got this error when i start my app:

12-20 22:27:01.447: ERROR/Database(716): Failure 1 (near ":00": syntax error) on 0x1a4338 when preparing 'CREATE TABLE permission ( fk_email1 varchar(100) NOT NULL, fk_email2 varchar(100) NOT NULL, validated tinyint(4) default 0, hour1 time default 08:00:00, hour2 time default 20:00:00, date1 date default NULL, date2 date default NULL, weekend tinyint(4) default 0, fk_type varchar(45) default NULL, PRIMARY KEY  (fk_email1,fk_email2))'.

here is the code where i am creating the database:

private static final String PERMISSION_TABLE_CREATE =
"CREATE TABLE permission ("
"fk_email1 varchar(100) NOT NULL, fk_email2 varchar(100) NOT NULL, "
"validated tinyint(4) default 0, hour1 time default 08:00:00, "
"hour2 time default 20:00:00, date1 date default NULL, "
"date2 date default NULL, weekend tinyint(4) default 0, "
"fk_type varchar(45) default NULL, PRIMARY KEY  (fk_email1,fk_email2))";

private static final String USER_TABLE_CREATE = "CREATE TABLE user ( "
"email varchar(100) NOT NULL, password varchar(45) default NULL, "
"fullName varchar(80) default NULL, "
"mobilePhone varchar(14) default NULL, "
"mobileOperatingSystem varchar(20) default NULL, PRIMARY KEY  (email))";

what i am doing bad?


来源: stackexchange

问:
pouchdb delete allDocs javascript
I am new in pouchdb and I can't understand the API.

I want to know what is the best way to delete all documents with a javascript code. I try many things but nothing seams to work.

Do I have to use some options in the allDocs method like:

```<code>db.allDocs({include_docs: true, deleted: true})
</code>```

答:
Based on nlawson's Answer you can also use bulkDocs, so you don't have to run a Pouch operation for every document:</p>

```<code>db.allDocs({include_docs: true}).then(allDocs => {
  return allDocs.rows.map(row => {
    return {_id: row.id, _rev: row.doc._rev, _deleted: true};
  });
}).then(deleteDocs => {
  return db.bulkDocs(deleteDocs);
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: pouchdb delete allDocs javascript

Body:
I am new in pouchdb and I can't understand the API.

I want to know what is the best way to delete all documents with a javascript code. I try many things but nothing seams to work.

Do I have to use some options in the allDocs method like:

db.allDocs({include_docs: true, deleted: true})

Body:
Based on nlawson's Answer you can also use bulkDocs, so you don't have to run a Pouch operation for every document:

db.allDocs({include_docs: true}).then(allDocs => {
  return allDocs.rows.map(row => {
    return {_id: row.id, _rev: row.doc._rev, _deleted: true};
  });
}).then(deleteDocs => {
  return db.bulkDocs(deleteDocs);
});


问:
Calling method Design in Java
I have one interface named HasDescription

```<code>public interface HasDescription {

    String getDescription();

    void setDescription(String description);
}
</code>```

It has getter and setter method declarations.

I have another abstract class called ResidentialProperty that implements this interface.

```<code>public abstract class ResidentialProperty
        extends AbstractProperty
        implements HasDescription {
    .....
    private String description;

    @Override
    public String getDescription() {
        return description;
    }

    @Override
    public void setDescription(String description) {
        this.description = description;
    }

}
</code>```

I have another class called Flat. In this class, i have delegated one descriptionSupportinstance. My thought is that, using this instance, i want to call ResidentialProperty's getter and setter method. I am coding this DescriptionSupport. Please assist me how i can do this?

```<code>public class Flat
extends ResidentialProperty {
 private final DescriptionSupport descriptionSupport = new DescriptionSupport();
 @Override
 public String getDescription() {
  return descriptionSupport.getDescription(this);
 }

 @Override
 public void setDescription(String description) {
  descriptionSupport.setDescription(this, description);
 }
}

public class DescriptionSupport {
 public < T extends HasDescription > String getDescription(T property) {
  //i want to call ResidentialProperty's getDescription method

 }

 public < T extends HasDescription > void setDescription(T property, String description) {
  //i want to call ResidentialProperty's setDescription method
 }
}
</code>```

答:
If you really want to use DescriptionSupport, I propose some modification:

```<code>public class Flat extends ResidentialProperty {
    private final DescriptionSupport descriptionSupport = new DescriptionSupport();
    @Override
    public String getDescription() {
        return descriptionSupport.getDescription(super::getDescription);
    }

    @Override
    public void setDescription(String description) {
        descriptionSupport.setDescription(super::setDescription, description);
    }
}

public class DescriptionSupport {
    public String getDescription(Supplier<String> s) {
        return s.get();

    }

    public void setDescription(Consumer<String> c, String description) {
        c.accept(description);
    }
}
</code>```

Title: Calling method Design in Java

Body:
I have one interface named HasDescription

public interface HasDescription {

    String getDescription();

    void setDescription(String description);
}

It has getter and setter method declarations.

I have another abstract class called ResidentialProperty that implements this interface.

public abstract class ResidentialProperty
        extends AbstractProperty
        implements HasDescription {
    .....
    private String description;

    @Override
    public String getDescription() {
        return description;
    }

    @Override
    public void setDescription(String description) {
        this.description = description;
    }

}

I have another class called Flat. In this class, i have delegated one descriptionSupportinstance. My thought is that, using this instance, i want to call ResidentialProperty's getter and setter method. I am coding this DescriptionSupport. Please assist me how i can do this?

public class Flat
extends ResidentialProperty {
 private final DescriptionSupport descriptionSupport = new DescriptionSupport();
 @Override
 public String getDescription() {
  return descriptionSupport.getDescription(this);
 }

 @Override
 public void setDescription(String description) {
  descriptionSupport.setDescription(this, description);
 }
}

public class DescriptionSupport {
 public < T extends HasDescription > String getDescription(T property) {
  //i want to call ResidentialProperty's getDescription method

 }

 public < T extends HasDescription > void setDescription(T property, String description) {
  //i want to call ResidentialProperty's setDescription method
 }
}

Body:
If you really want to use DescriptionSupport, I propose some modification:

public class Flat extends ResidentialProperty {
    private final DescriptionSupport descriptionSupport = new DescriptionSupport();
    @Override
    public String getDescription() {
        return descriptionSupport.getDescription(super::getDescription);
    }

    @Override
    public void setDescription(String description) {
        descriptionSupport.setDescription(super::setDescription, description);
    }
}

public class DescriptionSupport {
    public String getDescription(Supplier<String> s) {
        return s.get();

    }

    public void setDescription(Consumer<String> c, String description) {
        c.accept(description);
    }
}


问:
Is it possible to get the name of a select list from an item that has just been removed from that list
I am attempting to update the values in an array after an item has been removed from a selectize list. To do this I need the attr('name') for the list. On the event of an item_remove the $item can get the select list, but it cannot find the attr('name') that I need.

The solution below is how I am doing this for an item_add event. You'll see that the var thisSelect gets the select list and from that, I can populate the values array with the actual list values.

```<code>/**
 * Add callback behaviour once a select element has been selected.
 */
    $('[data-type="select"]').each(function(i, v) {
        v.selectize.on('item_add', function (value, $item) {
            var thisSelect = $item.parents('.controls').find('select'),
                name = thisSelect.attr('name'),
                values = [],
                exclusiveSelected = thisSelect.find('option[data-exclusive="true"]:selected');

            if (exclusiveSelected.length) {
                values.push({
                    "value": exclusiveSelected.val(),
                    "label": exclusiveSelected.text().trim(),
                    "label-key": exclusiveSelected.attr("label-key")
                });

                thisSelect.val(exclusiveSelected.val()).trigger('change');

            } else {
                thisSelect.siblings('.selectize-control').find('.item').each(function(i, v) {
                    values.push({
                        "value": $(v).data('value'),
                        "label": $(v).text().trim(),
                        "label-key": $(v).attr("label-key")
                    });
                });
            }

            setMultipleFieldValues(name, values);
            validate(documentId, name, fields);
        });
    });
</code>```

Below is my current solution for an item_remove event. A Cannot set property 'values' of undefined error occurs in the console because the values array cannot be populated due to the name of the list returning as undefined.

```<code>/**
 * Add callback behaviour once a select element has been unselected.
 */
    $('[data-type="select"]').each(function(i, v) {
        v.selectize.on('item_remove', function (value, $item) {
            var thisSelect = $item.parents('.controls').find('select'),
                name = thisSelect.attr('name'),
                values = [];

            thisSelect.siblings('.selectize-control').find('.item').each(function(i, v) {
                values.push({
                    "value": $(v).data('value'),
                    "label": $(v).text().trim(),
                    "label-key": $(v).attr("label-key")
                });
            });

            setMultipleFieldValues(name, values);
            validate(documentId, name, fields);
        });
    });
</code>```

Attached is the select element I am trying to get the name "additionalWork" from

答:
You need to get the object as it's deleted. I'd suggest parsing a function into the onDelete callback

Demo http://jsfiddle.net/uZmcD/91/

```<code>$(function() {
  $('#select-name').selectize({
    plugins: ['remove_button'],
    onDelete: function(values) {
      item_remove_function($(this));
    }
  });
});

function item_remove_function($this) {

  var name = $this[0].$wrapper.siblings('select').attr('name');
  alert('select name = ' + name);

}
</code>```

Body:
I am attempting to update the values in an array after an item has been removed from a selectize list. To do this I need the attr('name') for the list. On the event of an item_remove the $item can get the select list, but it cannot find the attr('name') that I need.

The solution below is how I am doing this for an item_add event. You'll see that the var thisSelect gets the select list and from that, I can populate the values array with the actual list values.

/**
 * Add callback behaviour once a select element has been selected.
 */
    $('[data-type="select"]').each(function(i, v) {
        v.selectize.on('item_add', function (value, $item) {
            var thisSelect = $item.parents('.controls').find('select'),
                name = thisSelect.attr('name'),
                values = [],
                exclusiveSelected = thisSelect.find('option[data-exclusive="true"]:selected');

            if (exclusiveSelected.length) {
                values.push({
                    "value": exclusiveSelected.val(),
                    "label": exclusiveSelected.text().trim(),
                    "label-key": exclusiveSelected.attr("label-key")
                });

                thisSelect.val(exclusiveSelected.val()).trigger('change');

            } else {
                thisSelect.siblings('.selectize-control').find('.item').each(function(i, v) {
                    values.push({
                        "value": $(v).data('value'),
                        "label": $(v).text().trim(),
                        "label-key": $(v).attr("label-key")
                    });
                });
            }

            setMultipleFieldValues(name, values);
            validate(documentId, name, fields);
        });
    });

Below is my current solution for an item_remove event. A Cannot set property 'values' of undefined error occurs in the console because the values array cannot be populated due to the name of the list returning as undefined.

/**
 * Add callback behaviour once a select element has been unselected.
 */
    $('[data-type="select"]').each(function(i, v) {
        v.selectize.on('item_remove', function (value, $item) {
            var thisSelect = $item.parents('.controls').find('select'),
                name = thisSelect.attr('name'),
                values = [];

            thisSelect.siblings('.selectize-control').find('.item').each(function(i, v) {
                values.push({
                    "value": $(v).data('value'),
                    "label": $(v).text().trim(),
                    "label-key": $(v).attr("label-key")
                });
            });

            setMultipleFieldValues(name, values);
            validate(documentId, name, fields);
        });
    });

Attached is the select element I am trying to get the name "additionalWork" from

Body:
You need to get the object as it's deleted. I'd suggest parsing a function into the onDelete callback

Demo http://jsfiddle.net/uZmcD/91/

$(function() {
  $('#select-name').selectize({
    plugins: ['remove_button'],
    onDelete: function(values) {
      item_remove_function($(this));
    }
  });
});

function item_remove_function($this) {

  var name = $this[0].$wrapper.siblings('select').attr('name');
  alert('select name = ' + name);

}


问:
Custom expression in JPA CriteriaBuilder
I have an Entity with a String field (storing JSON), and need to compare value from its database column with another value. Problem is that type of this database column is TEXT, but in fact it contains JSON. So, is there a way to write something like this? I.e. I need to compare my value with some field of JSON from TEXT column.</p>

```<code>criteriaBuilder.equal(root.get("json_column").customExpressionn(new Expression{
   Object handle(Object data){
    return ((Object)data).get("json_field")
}
}), value)
</code>```

答:
Assuming, you have a MySQL server with version > 5.7.x

I just had the same issue. I wanted to find all entities of a class that had a JSON field value inside a JSON object column.

The solution that worked for me was something along the lines (sorry typing from a phone)

```<code>(root, query, builder)->{
    return builder.equal(
        builder.function("JSON_EXTRACT", String.class, root.get("myEntityJsonAttribute"), builder.literal("$.json.path.to.json.field")),
        "searchedValueInJsonFieldOfJsonAttribute"
    )
}
</code>```

Body:
I have an Entity with a String field (storing JSON), and need to compare value from its database column with another value. Problem is that type of this database column is TEXT, but in fact it contains JSON. So, is there a way to write something like this? I.e. I need to compare my value with some field of JSON from TEXT column.

criteriaBuilder.equal(root.get("json_column").customExpressionn(new Expression{
   Object handle(Object data){
    return ((Object)data).get("json_field")
}
}), value)

Body:
Assuming, you have a MySQL server with version > 5.7.x

I just had the same issue. I wanted to find all entities of a class that had a JSON field value inside a JSON object column.

The solution that worked for me was something along the lines (sorry typing from a phone)

(root, query, builder)->{
    return builder.equal(
        builder.function("JSON_EXTRACT", String.class, root.get("myEntityJsonAttribute"), builder.literal("$.json.path.to.json.field")),
        "searchedValueInJsonFieldOfJsonAttribute"
    )
}


问:
accessing returned data from a states resolve function
I am using an AngularJS module ui-router and using the resolve property to fetch the id of an item.

In a separate file I have the component, patent for a state patents.patent, which has the function that returns the id. I need to access the returned id from the controller so I can then gather the correct data related to the selected item.

How do I access the resolve function returned value from the controller?

```<code>var app = angular.module('myApp', ['ui.router', 'chart.js']);

app.config(['$stateProvider', function($stateProvider) {

    $stateProvider
    .state('patents', {
        url: '/patents',
        component: 'patents',
        resolve: {
            patents: function(patentsService) {
                return patentsService.fetchAllPatents();
            },
            graphs: function(patentsService) {
                return  patentsService.fetchGraphData();
            }

        }
    })
    .state('patents.patent', {
        url: '/{patentId}',
        component: 'patent',
        resolve: {
            patent: function(patents, $stateParams) {
                return patents.find(function(patent){
                    return patent.id == $stateParams.patentId;
                })
            },
            graph: function(graphs, $stateParams) {
                return graphs.dataset.find(function(graph){
                    return graph.id == $stateParams.patentId; //NEED THIS VALUE
                })
            }
        }
    })

}]);
</code>```

```<code>angular.module('myApp').component('patent', {
    bindings: {
        patent: '=' ,
    },
    templateUrl: '../templates/patents/list/patent-item.htm',
    controller: function() {
        var vm = this;

        //WHERE I NEED TO ACCESS THE RETURNED VALUE

    }
});
</code>```

答:
To access your resolved data you simply define them as bindings to your controller. Like you've already done with patent. Then you access them through your vm variable (or this).

```<code>angular.module('myApp').component('patent', {
    bindings: {
        patent: '<' ,
        graph: '<'
    },
    templateUrl: '../templates/patents/list/patent-item.htm',
    controller: function() {
        var vm = this;

        vm.$onChanges = function(changeObj){
            if(changeObj.patent){
                console.log('I am your patent', vm.patent);
            }
            if(changeObj.patent){
                console.log('I am your graph', vm.graph);
            }
        }
    }
});
</code>```

As @rrd suggests, you should guard your controllers against minification, but not only that, you should also guard your resolve functions from minification.

Like so:

```<code>resolve: {
    patents: ['patentsService', function(patentsService) {
        return patentsService.fetchAllPatents();
    }],
    graphs: ['patentsService', function(patentsService) {
        return  patentsService.fetchGraphData();
    }]
}
</code>```

Body:
I am using an AngularJS module ui-router and using the resolve property to fetch the id of an item.

In a separate file I have the component, patent for a state patents.patent, which has the function that returns the id. I need to access the returned id from the controller so I can then gather the correct data related to the selected item.

How do I access the resolve function returned value from the controller?

var app = angular.module('myApp', ['ui.router', 'chart.js']);

app.config(['$stateProvider', function($stateProvider) {

    $stateProvider
    .state('patents', {
        url: '/patents',
        component: 'patents',
        resolve: {
            patents: function(patentsService) {
                return patentsService.fetchAllPatents();
            },
            graphs: function(patentsService) {
                return  patentsService.fetchGraphData();
            }

        }
    })
    .state('patents.patent', {
        url: '/{patentId}',
        component: 'patent',
        resolve: {
            patent: function(patents, $stateParams) {
                return patents.find(function(patent){
                    return patent.id == $stateParams.patentId;
                })
            },
            graph: function(graphs, $stateParams) {
                return graphs.dataset.find(function(graph){
                    return graph.id == $stateParams.patentId; //NEED THIS VALUE
                })
            }
        }
    })

}]);

angular.module('myApp').component('patent', {
    bindings: {
        patent: '=' ,
    },
    templateUrl: '../templates/patents/list/patent-item.htm',
    controller: function() {
        var vm = this;

        //WHERE I NEED TO ACCESS THE RETURNED VALUE

    }
});

Body:
To access your resolved data you simply define them as bindings to your controller. Like you've already done with patent. Then you access them through your vm variable (or this).

angular.module('myApp').component('patent', {
    bindings: {
        patent: '<' ,
        graph: '<'
    },
    templateUrl: '../templates/patents/list/patent-item.htm',
    controller: function() {
        var vm = this;

        vm.$onChanges = function(changeObj){
            if(changeObj.patent){
                console.log('I am your patent', vm.patent);
            }
            if(changeObj.patent){
                console.log('I am your graph', vm.graph);
            }
        }
    }
});

As @rrd suggests, you should guard your controllers against minification, but not only that, you should also guard your resolve functions from minification.

Like so:

resolve: {
    patents: ['patentsService', function(patentsService) {
        return patentsService.fetchAllPatents();
    }],
    graphs: ['patentsService', function(patentsService) {
        return  patentsService.fetchGraphData();
    }]
}


问:
PHP script not working. Receiving error 404. Web server DOES support PHP
I have the following form and php script: </p>

```<code><form method="post" action="index.php">
    <h1>Contact</h1>

    <label>Name</label>
    <input name="name" placeholder="Type Here">

    <label>Email</label>
    <input name="email" type="email" placeholder="Type Here">

    <label>Message</label>
    <textarea name="message" placeholder="Type Here"></textarea>

    <input id="submit" class="button" name="submit" type="submit" value="Submit">
</form>

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'SJW&T Contact Form';
    $to = 'someone@example.com';
    $subject = 'Hello';
    $human = $_POST['human'];

    $body = "From: $name\n E-Mail: $email\n Message:\n $message";

    if ($_POST['submit']) {
        if (mail ($to, $subject, $body, $from)) {
            echo '<p>Your message has been sent!</p>';
        } else {
            echo '<p>Something went wrong, go back and try again!</p>';
        }
    }
?>
</code>```

<p>But my web host seems to be returning an error 404. I tried the suggestion in this thread, which is a near duplicate, but it did not work. Anyone see any syntax errors? My web host is 000webhost.com. It doesn't give me an actual 404 message, but the URL it takes me to is error404.000webhost.com.  </p>

答: Make sure your form action name is the same thing as the file name. E.g form action-"forms.php".      make sure the folder or file name is also-forms.php </p>

Body:
I have the following form and php script:

<form method="post" action="index.php">

Contact

    Name
    <input name="name" placeholder="Type Here">

    Email
    <input name="email" type="email" placeholder="Type Here">

    Message
    <textarea name="message" placeholder="Type Here"></textarea>

    <input id="submit" class="button" name="submit" type="submit" value="Submit">
</form>

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'SJW&T Contact Form';
    $to = 'someone@example.com';
    $subject = 'Hello';
    $human = $_POST['human'];

    $body = "From: $name\n E-Mail: $email\n Message:\n $message";

    if ($_POST['submit']) {
        if (mail ($to, $subject, $body, $from)) {
            echo '
Your message has been sent!
';
        } else {
            echo '
Something went wrong, go back and try again!
';
        }
    }
?>

But my web host seems to be returning an error 404. I tried the suggestion in this thread, which is a near duplicate, but it did not work. Anyone see any syntax errors? My web host is 000webhost.com. It doesn't give me an actual 404 message, but the URL it takes me to is error404.000webhost.com.


问:
Object of class DateTime could not be converted
I can see that there are many questions along these lines but I am very confused as to why the following does not work, taken straight from the PHP docs:

```<code>$tempDate = DateTime::createFromFormat('j-M-Y', '15-Feb-2009');
echo $tempDate;
</code>```

The error:

PHP Catchable fatal error:  Object of class DateTime could not be converted to string.

In fact every example in the docs gives me this error. Any ideas?

答:
The error message:

PHP Catchable fatal error: Object of class DateTime could not be converted to string.

is self-explanatory. The statement:

```<code>echo $tempDate;
</code>```

attempts to print a DateTime object. The echo() language construct expects a string, you pass it a DateTime object. The DateTime class does not implement the __toString() magic method and PHP doesn't know how to convert a DateTime object to string.

There are so many ways to represent a DateTime object as string and all of them are handled by the DateTime::format() method.

In fact every example in the docs gives me this error.

In fact, every example in the documentation of DateTime::createFromFormat() reads:

```<code>echo $date->format('Y-m-d');
</code>```

which is a different thing that echo $date;.

Any ideas?

Read the documentation of DateTime and DateTime::format() carefully.

Body:
I can see that there are many questions along these lines but I am very confused as to why the following does not work, taken straight from the PHP docs:

$tempDate = DateTime::createFromFormat('j-M-Y', '15-Feb-2009');
echo $tempDate;

The error:

PHP Catchable fatal error:  Object of class DateTime could not be converted to string.

In fact every example in the docs gives me this error. Any ideas?

Body:
The error message:

PHP Catchable fatal error: Object of class DateTime could not be converted to string.

is self-explanatory. The statement:

echo $tempDate;

attempts to print a DateTime object. The echo() language construct expects a string, you pass it a DateTime object. The DateTime class does not implement the __toString() magic method and PHP doesn't know how to convert a DateTime object to string.

There are so many ways to represent a DateTime object as string and all of them are handled by the DateTime::format() method.

In fact every example in the docs gives me this error.

In fact, every example in the documentation of DateTime::createFromFormat() reads:

echo $date->format('Y-m-d');

which is a different thing that echo $date;.

Any ideas?

Read the documentation of DateTime and DateTime::format() carefully.


问:
Errors installing 'forecast' package in R version 3.3.2
Trying to install 'forecast' package in R version 3.3.2 on MacOS Sierra as follows:

```<code>install.packages("forecast")
</code>```

Getting a slew of errors I don't understand.  First it downloads all dependency packages from http://cloud.r-project.org.  First error I get is this:

```<code>* installing *source* package ‘quadprog’ ...
** package ‘quadprog’ successfully unpacked and MD5 sums checked
** libs
gfortran -arch x86_64   -fPIC  -g -O2  -c aind.f -o aind.o
make: gfortran: No such file or directory
make: *** [aind.o] Error 1
ERROR: compilation failed for package ‘quadprog’
* removing ‘/Users/ekorne201/Library/R/3.3/library/quadprog’
</code>```

It then moves on to:

```<code>* installing *source* package ‘fracdiff’ ...
** package ‘fracdiff’ successfully unpacked and MD5 sums checked
</code>```

After which it says:

```<code>ld: warning: directory not found for option '-L/Users/Shared/Jenkins/workspace/External-R-3.3.2/vendor/build/lib'
ld: warning: directory not found for option '-L/usr/local/lib/gcc/i686-apple-darwin8/4.2.3/x86_64'
ld: warning: directory not found for option '-L/usr/local/lib/x86_64'
ld: warning: directory not found for option '-L/usr/local/lib/gcc/i686-apple-darwin8/4.2.3'
ld: library not found for -lgfortran
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [fracdiff.so] Error 1
ERROR: compilation failed for package ‘fracdiff’
* removing ‘/Users/ekorne201/Library/R/3.3/library/fracdiff’
</code>```

Goes through the same thing for 'lmtest' and 'RcppArmadillo', after which it ends with:

```<code> ERROR: dependencies ‘tseries’, ‘fracdiff’, ‘lmtest’, ‘RcppArmadillo’ are not available for package ‘forecast’
    * removing ‘/Users/ekorne201/Library/R/3.3/library/forecast’

    The downloaded source packages are in
        ‘/private/var/folders/8p/54qnlb9x7bj8syz631_d58t92rmkyp/T/Rtmp246ipQ/downloaded_packages’
    Warning messages:
    1: In install.packages("forecast") :
      installation of package ‘quadprog’ had non-zero exit status
    2: In install.packages("forecast") :
      installation of package ‘fracdiff’ had non-zero exit status
    3: In install.packages("forecast") :
      installation of package ‘lmtest’ had non-zero exit status
    4: In install.packages("forecast") :
      installation of package ‘RcppArmadillo’ had non-zero exit status
    5: In install.packages("forecast") :
      installation of package ‘tseries’ had non-zero exit status
    6: In install.packages("forecast") :
      installation of package ‘forecast’ had non-zero exit status
</code>```

Stuck on how to proceed and would appreciate the advice.

答:
I got the same error. I solved it by installing the gfortran. In macOS, I can do it such that

```<code>brew install gcc
</code>```

and in R such that

```<code>install.packages("forecast")
</code>```

so

```<code>> library(forecast); fit <- tbats(UScitiesD);
> fit
BATS(0.566, {0,2}, -, -)

Call: tbats(y = UScitiesD)

Parameters
  Lambda: 0.565592
  Alpha: 0.2166945
  MA coefficients: -0.130506 -0.511551

Seed States:
         [,1]
[1,] 90.10291
[2,]  0.00000
[3,]  0.00000

Sigma: 27.61468
AIC: 761.9238
</code>```

As mentioned in comments, other method is to install it from here.

Related

Does installing gfortran with homebrew and with an installer create a conflict?

Body:
Trying to install 'forecast' package in R version 3.3.2 on MacOS Sierra as follows:

install.packages("forecast")

Getting a slew of errors I don't understand.  First it downloads all dependency packages from http://cloud.r-project.org.  First error I get is this:

* installing *source* package ‘quadprog’ ...
** package ‘quadprog’ successfully unpacked and MD5 sums checked
** libs
gfortran -arch x86_64   -fPIC  -g -O2  -c aind.f -o aind.o
make: gfortran: No such file or directory
make: *** [aind.o] Error 1
ERROR: compilation failed for package ‘quadprog’
* removing ‘/Users/ekorne201/Library/R/3.3/library/quadprog’

It then moves on to:

* installing *source* package ‘fracdiff’ ...
** package ‘fracdiff’ successfully unpacked and MD5 sums checked

After which it says:

ld: warning: directory not found for option '-L/Users/Shared/Jenkins/workspace/External-R-3.3.2/vendor/build/lib'
ld: warning: directory not found for option '-L/usr/local/lib/gcc/i686-apple-darwin8/4.2.3/x86_64'
ld: warning: directory not found for option '-L/usr/local/lib/x86_64'
ld: warning: directory not found for option '-L/usr/local/lib/gcc/i686-apple-darwin8/4.2.3'
ld: library not found for -lgfortran
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [fracdiff.so] Error 1
ERROR: compilation failed for package ‘fracdiff’
* removing ‘/Users/ekorne201/Library/R/3.3/library/fracdiff’

Goes through the same thing for 'lmtest' and 'RcppArmadillo', after which it ends with:

 ERROR: dependencies ‘tseries’, ‘fracdiff’, ‘lmtest’, ‘RcppArmadillo’ are not available for package ‘forecast’
    * removing ‘/Users/ekorne201/Library/R/3.3/library/forecast’

    The downloaded source packages are in
        ‘/private/var/folders/8p/54qnlb9x7bj8syz631_d58t92rmkyp/T/Rtmp246ipQ/downloaded_packages’
    Warning messages:
    1: In install.packages("forecast") :
      installation of package ‘quadprog’ had non-zero exit status
    2: In install.packages("forecast") :
      installation of package ‘fracdiff’ had non-zero exit status
    3: In install.packages("forecast") :
      installation of package ‘lmtest’ had non-zero exit status
    4: In install.packages("forecast") :
      installation of package ‘RcppArmadillo’ had non-zero exit status
    5: In install.packages("forecast") :
      installation of package ‘tseries’ had non-zero exit status
    6: In install.packages("forecast") :
      installation of package ‘forecast’ had non-zero exit status

Stuck on how to proceed and would appreciate the advice.

Body:
I got the same error. I solved it by installing the gfortran. In macOS, I can do it such that

brew install gcc

and in R such that

install.packages("forecast")

so

> library(forecast); fit <- tbats(UScitiesD);
> fit
BATS(0.566, {0,2}, -, -)

Call: tbats(y = UScitiesD)

Parameters
  Lambda: 0.565592
  Alpha: 0.2166945
  MA coefficients: -0.130506 -0.511551

Seed States:
         [,1]
[1,] 90.10291
[2,]  0.00000
[3,]  0.00000

Sigma: 27.61468
AIC: 761.9238

As mentioned in comments, other method is to install it from here.

Related

Does installing gfortran with homebrew and with an installer create a conflict?


问:
phpmyadmin server conncetion localhost/login.php not posting anything
What is physically wrong with this code.

```<code><?php
require "conn.php";
$user_name = "1234";
$user_pass = "4321";
$mysql_qry = "SELECT * FROM employee_data WHERE username like '$user_name'
&& password like '$user_pass';";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result > 0) {
echo "login success";
}
else{
echo "login not success";
}

?>
</code>```

(when I run it on the local host, there is nothing there [localhost/login.php])

答:
Try this:

```<code><?php
require "conn.php";
$user_name = "1234";
$user_pass = "4321";
$mysql_qry = "SELECT * FROM employee_data WHERE username like '$user_name'
               && password like '$user_pass';";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result) > 0) {
   echo "login success";
}
else{
   echo "login not success";
}
?>
</code>```

you had one problem. Refer http://php.net/manual/en/mysqli-result.num-rows.php

```<code>if(mysqli_num_rows($result) > 0)
</code>```

Body:
What is physically wrong with this code.

<?php
require "conn.php";
$user_name = "1234";
$user_pass = "4321";
$mysql_qry = "SELECT * FROM employee_data WHERE username like '$user_name'
&& password like '$user_pass';";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result > 0) {
echo "login success";
}
else{
echo "login not success";
}

?>

(when I run it on the local host, there is nothing there [localhost/login.php])

Body:
Try this:

<?php
require "conn.php";
$user_name = "1234";
$user_pass = "4321";
$mysql_qry = "SELECT * FROM employee_data WHERE username like '$user_name'
               && password like '$user_pass';";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result) > 0) {
   echo "login success";
}
else{
   echo "login not success";
}
?>

you had one problem. Refer http://php.net/manual/en/mysqli-result.num-rows.php

if(mysqli_num_rows($result) > 0)


问:
Woocommerce load an external page on thankyou page
I am using an SMS API to send sms to customer on Thankyou page of woocommerce. The API redirects to the API provide's page after sending the SMS. I asked them for a solution, they suggested to use the iframe. But the redirection exists. Then, they suggested to call variables from page checkout. I am unable to understand. Kindly, guide me. Here, is my code.</p>

```<code>function tz_send_message_to_customer($order_id){

$order = new WC_Order( $order_id );
$currency = $order->get_order_currency();
$total = $order->get_total();
$date = $order->order_date;
$name = $order->billing_first_name . $order->billing_last_name;

// Configuration variables
$id = "xxxxx"; // Account Username
$pass = "xxxx"; // Account Password
$mask = "xxxx"; // Account Masking

// Data for text message
$to =  $order->billing_phone; // Recipient Number with "92" Pakistan Code
$message = urlencode("Dear " . $name . "!" . "Your following Order is Under Process" . "Order ID: " .$order_id . "Total: " . $currency.$total.  "Thankyou For Shopping") ;

// Prepare data for POST request - DO NOT EDIT
$data = "id=".$id."&pass=".$pass."&msg=".$message."&to=".$to."&lang=English"."&mask=".$mask."&type=xml";

// Send the POST request with cURL - DO NOT EDIT
//header("location:http://ip-address/api/sendsms.php?".$data);
$url = "http://ip-address/api/sendsms.php?".$data;
?>
<iframe src="<?php echo $url; ?>"></iframe>
<?php
}

add_action( 'woocommerce_thankyou', 'tz_send_message_to_customer', 10, 1 );
</code>```

答:
I have found the solution by searching on Google. It was suggested that use sandbox attribute in iframe like  sandbox="allow-same-origin". So, the iframe code looks like as

```<code><iframe src="<?php echo $url; ?>" sandbox="allow-same-origin" style=" display: none;"></iframe>
</code>```

More info can be found at: https://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/

Body:
I am using an SMS API to send sms to customer on Thankyou page of woocommerce. The API redirects to the API provide's page after sending the SMS. I asked them for a solution, they suggested to use the iframe. But the redirection exists. Then, they suggested to call variables from page checkout. I am unable to understand. Kindly, guide me. Here, is my code.

function tz_send_message_to_customer($order_id){

$order = new WC_Order( $order_id );
$currency = $order->get_order_currency();
$total = $order->get_total();
$date = $order->order_date;
$name = $order->billing_first_name . $order->billing_last_name;

// Configuration variables
$id = "xxxxx"; // Account Username
$pass = "xxxx"; // Account Password
$mask = "xxxx"; // Account Masking

// Data for text message
$to =  $order->billing_phone; // Recipient Number with "92" Pakistan Code
$message = urlencode("Dear " . $name . "!" . "Your following Order is Under Process" . "Order ID: " .$order_id . "Total: " . $currency.$total.  "Thankyou For Shopping") ;

// Prepare data for POST request - DO NOT EDIT
$data = "id=".$id."&pass=".$pass."&msg=".$message."&to=".$to."&lang=English"."&mask=".$mask."&type=xml";

// Send the POST request with cURL - DO NOT EDIT
//header("location:http://ip-address/api/sendsms.php?".$data);
$url = "http://ip-address/api/sendsms.php?".$data;
?>
<iframe src="<?php echo $url; ?>">
<?php
}

add_action( 'woocommerce_thankyou', 'tz_send_message_to_customer', 10, 1 );

Body:
I have found the solution by searching on Google. It was suggested that use sandbox attribute in iframe like  sandbox="allow-same-origin". So, the iframe code looks like as

<iframe src="<?php echo $url; ?>" sandbox="allow-same-origin" style=" display: none;"></iframe>

More info can be found at: https://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/


问:
Prevent overlap of image views on touch and rotate
In the app that i am working on there are 2 separate image views in a relative layout. I want to have both images as movable and rotatable in response to the given action events the XML for my activity is:

```<code><RelativeLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context="com.example.vishalbisht.dragfeature.MainActivity">

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:id="@+id/Recycle"
    android:layout_alignParentLeft="true" />
<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/Ring"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true" />

</RelativeLayout>
</code>```

While the program part is :

```<code>public class MainActivity extends AppCompatActivity implements View.OnTouchListener {

ImageView jwl,rlo;
private final String TAG="DRAGFEATURE";
String Mode;
Bitmap bitmap,rotaBitmap;
BitmapDrawable bdr;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    jwl= (ImageView) findViewById(R.id.Recycle);
    rlo= (ImageView) findViewById(R.id.Ring);
    jwl.setImageResource(R.drawable.icon);
    rlo.setImageResource(R.drawable.ring);
    jwl.setOnTouchListener(this);
    rlo.setOnTouchListener(this);
}

@Override
public boolean onTouch(View v, MotionEvent event) {
    int eId = event.getActionMasked();
    Mode = "Move";
    switch (eId) {
        case MotionEvent.ACTION_MOVE:
                Log.v(TAG,"move image");
                drag(v, event);
                break;
        case MotionEvent.ACTION_DOWN:
                r = r + 13;
                rotate(v);
                break;
        default:break;
    }
    if (v != jwl && v != rlo)
        Log.v(TAG,"Not Valid");

    return true;
}

private int r =2;

private void rotate(View v) {
    if(v==jwl)
        bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.icon);
    else
        bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.ring);
    int w = bitmap.getWidth();
    int h = bitmap.getHeight();
    Matrix matrix = new Matrix();
    matrix.preRotate(-r);
    rotaBitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix,true);
    bdr = new BitmapDrawable(rotaBitmap);
    if(v==jwl)
        jwl.setImageDrawable(bdr);
    else
        rlo.setImageDrawable(bdr);
}

private void drag(View v, MotionEvent event) {
    RelativeLayout.LayoutParams mParams = (RelativeLayout.LayoutParams) jwl.getLayoutParams();
    Log.v(TAG,"Start of Move");
    int x = (int) event.getRawX();
    int y = (int) event.getRawY();
    mParams.leftMargin = x - 150;
    mParams.topMargin = y - 210;
    if(v==jwl)
        jwl.setLayoutParams(mParams);
    else
        rlo.setLayoutParams(mParams);

 }
}
</code>```

when i touch or drag the left image (Recycle) then its fine but when I click on Ring then the two images overlap and move/rotate together. Why is this happening and how to fix it ?

答:
change your layout xml as below :</p>

```<code><ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:id="@+id/Recycle"
    android:layout_alignParentLeft="true" />
<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/Ring"
    android:layout_toRightOf="@+id/Recycle"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true" />
</code>```

Body:
In the app that i am working on there are 2 separate image views in a relative layout. I want to have both images as movable and rotatable in response to the given action events the XML for my activity is:

<RelativeLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context="com.example.vishalbisht.dragfeature.MainActivity">

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:id="@+id/Recycle"
    android:layout_alignParentLeft="true" />
<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/Ring"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true" />

</RelativeLayout>

While the program part is :

public class MainActivity extends AppCompatActivity implements View.OnTouchListener {

ImageView jwl,rlo;
private final String TAG="DRAGFEATURE";
String Mode;
Bitmap bitmap,rotaBitmap;
BitmapDrawable bdr;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    jwl= (ImageView) findViewById(R.id.Recycle);
    rlo= (ImageView) findViewById(R.id.Ring);
    jwl.setImageResource(R.drawable.icon);
    rlo.setImageResource(R.drawable.ring);
    jwl.setOnTouchListener(this);
    rlo.setOnTouchListener(this);
}

@Override
public boolean onTouch(View v, MotionEvent event) {
    int eId = event.getActionMasked();
    Mode = "Move";
    switch (eId) {
        case MotionEvent.ACTION_MOVE:
                Log.v(TAG,"move image");
                drag(v, event);
                break;
        case MotionEvent.ACTION_DOWN:
                r = r + 13;
                rotate(v);
                break;
        default:break;
    }
    if (v != jwl && v != rlo)
        Log.v(TAG,"Not Valid");

    return true;
}

private int r =2;

private void rotate(View v) {
    if(v==jwl)
        bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.icon);
    else
        bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.ring);
    int w = bitmap.getWidth();
    int h = bitmap.getHeight();
    Matrix matrix = new Matrix();
    matrix.preRotate(-r);
    rotaBitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix,true);
    bdr = new BitmapDrawable(rotaBitmap);
    if(v==jwl)
        jwl.setImageDrawable(bdr);
    else
        rlo.setImageDrawable(bdr);
}

private void drag(View v, MotionEvent event) {
    RelativeLayout.LayoutParams mParams = (RelativeLayout.LayoutParams) jwl.getLayoutParams();
    Log.v(TAG,"Start of Move");
    int x = (int) event.getRawX();
    int y = (int) event.getRawY();
    mParams.leftMargin = x - 150;
    mParams.topMargin = y - 210;
    if(v==jwl)
        jwl.setLayoutParams(mParams);
    else
        rlo.setLayoutParams(mParams);

 }
}

when i touch or drag the left image (Recycle) then its fine but when I click on Ring then the two images overlap and move/rotate together. Why is this happening and how to fix it ?

Body:
change your layout xml as below :

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:id="@+id/Recycle"
    android:layout_alignParentLeft="true" />
<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/Ring"
    android:layout_toRightOf="@+id/Recycle"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true" />


问:
SQL - Salary difference between 2 months (Variance)
There are 2 separate SQL queries that returning NetPay amount MonthWise. I
want to combine them means i want Variance between 2 months
(Month 2 Amount - Month 1 Amount) as output.</p>

```<code>Query - 1
Select ISNULL(Sum(EPS.Amount),0) as Amount
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id = 5

Query - 2
Select ISNULL(Sum(EPS.Amount),0) as Amount
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id = 6
</code>```

答:
If you do not want to join in same query for your better visibility, use Union all</p>

```<code>Select Amount1-Amount As Variance
from
(
Select ISNULL(Sum(EPS.Amount),0) as Amount, '0.00' Amount1
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id = 5

UNION ALL

Select '0.00' Amount, ISNULL(Sum(EPS.Amount),0) as Amount1
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id = 6

)am
</code>```

Body:
There are 2 separate SQL queries that returning NetPay amount MonthWise. I
want to combine them means i want Variance between 2 months
(Month 2 Amount - Month 1 Amount) as output.

Query - 1
Select ISNULL(Sum(EPS.Amount),0) as Amount
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id = 5

Query - 2
Select ISNULL(Sum(EPS.Amount),0) as Amount
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id = 6

Body:
If you do not want to join in same query for your better visibility, use Union all

Select Amount1-Amount As Variance
from
(
Select ISNULL(Sum(EPS.Amount),0) as Amount, '0.00' Amount1
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id = 5

UNION ALL

Select '0.00' Amount, ISNULL(Sum(EPS.Amount),0) as Amount1
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id = 6

)am


问:
In .NET, how do I access an audio input stream?
Using VB.NET, I want to analyze input audio streams obtained from Web radio stations (e.g.: "Flower Power Radio" via TuneIn). However, I am struggling in finding a suitable starting point.

Obviously, when entering into the Web browser a Web address (as given in above example), a stream starts flowing and is being interpreted by, in this case, said Web browser.

Only that my planned experiments do not involve the requirement for a browser; and since I do not want to replay the received audio stream, nor record it, I can also abstain from using the MediaPlayer.

I "just" want to intercept the stream's payload data in order to perform time–frequency analysis for music signals. But, how do I access this continuously delivered data?

(Edit: I should probably add, that I do not really embrace using 3rd party libraries of any sort.)

答:
To intercept the stream's payload data use the browser's developer tools. Press F12, go to the Network tab and select 'All'. Then press F5 to refresh the page.

Notice the first row entry which is the stream's source. From there you can check the request/responses from this stream http://flower.serverhostingcenter.com:8433/;

Now to access the downloading data use:

```<code>Dim c As New WebClient()
        Dim responseData As Byte() = c.DownloadData("http://flower.serverhostingcenter.com:8433/;")
</code>```

Since the streaming is endless, the file will keep downloading. It's up to you when you want to stop it and analyse the results. You can use Async events as well.

Body:
To intercept the stream's payload data use the browser's developer tools. Press F12, go to the Network tab and select 'All'. Then press F5 to refresh the page.

Notice the first row entry which is the stream's source. From there you can check the request/responses from this stream http://flower.serverhostingcenter.com:8433/;

Now to access the downloading data use:

Dim c As New WebClient()
        Dim responseData As Byte() = c.DownloadData("http://flower.serverhostingcenter.com:8433/;")

Since the streaming is endless, the file will keep downloading. It's up to you when you want to stop it and analyse the results. You can use Async events as well.


问:
Is it possible to check the content of Excel/pdf file with the content of HTML file using java?
Am new to java. I am in a situation to compare two different files using Java.
Am able to capture the html content in html.txt file and able to download the excel/pdf files through the application. Now, I need to compare or atleast check if the excel/pdf files contains the content in html file. I checked other related questions but they arent helpful.

Please help me on this or suggest any other way.

答:
Your question is unclear but if you mean reading exact contents of the files and comparing them, I think you'll benefit from reading tutorials like this one: http://tutorials.jenkov.com/java-io/readers-writers.html.

You need to use java i/o in order to compare the contents of files.

The idea would be:

take in the files to be read

compare the files to see if one contains the strings of other

do something with the information


问:
How to decode Unicode escape sequences like "\u00ed" to proper UTF-8 encoded characters?
Is there a function in PHP that can decode Unicode escape sequences like "\u00ed" to "í" and all other similar occurrences?

I found similar question here but is doesn't seem to work.

答:
PHP 7+

As of PHP 7, you can use the Unicode codepoint escape syntax to do this.

echo "\u{00ed}"; outputs í.

ContentLicense: CC BY-SA 2.5


问:
Java Static
Duplicate: What does the 'static' keyword do in a class?

I've read this post already.

What does the "static" keyword in a method do?

I remember being told that static != clingy...but that is pretty much all I know about this keyword.

答:
The value of a static variable within a method is stored between calls to that method

```<code>

public void method() {
  static int callCount = 0;
  callCount++;
  System.out.println("Calls: " + callCount);
}

method(); // "Calls: 1"
method(); // "Calls: 2"
method(); // "Calls: 3"

</code>```

Note that this is completely different from a static method. A static method is called upon the class it is defined in instead of an instance of this class.

```<code>

class MyClass {
  public static void staticMethod() { ... }
  public void nonStaticMethod();
}

Myclass.staticMethod();

MyClass instance = new MyClass();
instance.nonStaticMethod();

</code>```

OwnerDisplayName: koldfyre

Title: Java Static

LastEditorDisplayName: nemo

Body:
The value of a static variable within a method is stored between calls to that method

public void method() {
  static int callCount = 0;
  callCount++;
  System.out.println("Calls: " + callCount);
}

method(); // "Calls: 1"
method(); // "Calls: 2"
method(); // "Calls: 3"

Note that this is completely different from a static method. A static method is called upon the class it is defined in instead of an instance of this class.

class MyClass {
  public static void staticMethod() { ... }
  public void nonStaticMethod();
}

Myclass.staticMethod();

MyClass instance = new MyClass();
instance.nonStaticMethod();

OwnerDisplayName: wvanbergen


问:
Python OpenWRT crontab
Im trying to run python script on OpenWrt box:

```<code>#!/root/system/usr/bin/python
import subprocess

p = subprocess.Popen([r"snmpget","-v","1","-c","public","-Oqv","-Ln", "192.168.1.1","1.3.6.1.2.1.2.2.1.10.7"], stdout=subprocess.PIPE).communicate()[0]
data = [r"curl","-d","iface_id=1&content="+ str(p).rstrip() ,"http://192.168.1.5:8080/stat/add_istat/"]
a = subprocess.Popen(data, stdout=subprocess.PIPE).communicate()[0]
</code>```

It's geting data over snmp, then post data by curl to local server.
Its working ok from shell:

```<code>root@OpenWrt:~/python# ./w.py
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0    34    0     6    0    28     31    146 --:--:-- --:--:-- --:--:--     0
</code>```

I can see data in DB.
but from cron:

```<code>0-55/5 * * * * /root/python/w.py
</code>```

I see in logread:

```<code>Dec 20 23:30:01 OpenWrt cron.err crond[1039]: USER root pid 16141 cmd /root/python/w.py
</code>```

But no data in DB :( and nothing in httpd access.log :( why?

答: Could it be that snmpget or curl are not in the path of cron?</p>

Title: Python OpenWRT crontab

Body:
Im trying to run python script on OpenWrt box:

#!/root/system/usr/bin/python
import subprocess

p = subprocess.Popen([r"snmpget","-v","1","-c","public","-Oqv","-Ln", "192.168.1.1","1.3.6.1.2.1.2.2.1.10.7"], stdout=subprocess.PIPE).communicate()[0]
data = [r"curl","-d","iface_id=1&content="+ str(p).rstrip() ,"http://192.168.1.5:8080/stat/add_istat/"]
a = subprocess.Popen(data, stdout=subprocess.PIPE).communicate()[0]

It's geting data over snmp, then post data by curl to local server.
Its working ok from shell:

root@OpenWrt:~/python# ./w.py
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0    34    0     6    0    28     31    146 --:--:-- --:--:-- --:--:--     0

I can see data in DB.
but from cron:

0-55/5 * * * * /root/python/w.py

I see in logread:

Dec 20 23:30:01 OpenWrt cron.err crond[1039]: USER root pid 16141 cmd /root/python/w.py

But no data in DB :( and nothing in httpd access.log :( why?


问:
How to connect with Hiveserver2 using Python 3.4.5
I need to connect to the Hiveserver2 from Python 3.4.5 and the code is being executed on the hadoop cluster itself. Usually, I execute hive -e "some query" from command line. From other servers, we connect to Hiveserver2 using username only mechanism providing IP and port. However, that should not be necessary as here I am running the code on same server.

I have tried the following:

Access Hive Data Using Python

https://github.com/cloudera/impyla/issues/165

How to connect to Hadoop Hive through python via pyhs2?

https://pypi.python.org/pypi/impyla

but no success. I am getting error at connection stage itself. I can share errors if anyone requires.

If nothing else, it would be great if someone can elaborate on the answer to
Hive client for Python 3.x

答:
Help from a friend and little bit tweaking of online available answers using impala.dbapi solved the issue:</p>

```<code>from impala.dbapi import connect
conn = connect(host='localhost', port = 10000,auth_mechanism='PLAIN')
cursor = conn.cursor()
cursor.execute('show databases')
results = cursor.fetchall()
print(type(results))
print(results)
</code>```

Body:
Help from a friend and little bit tweaking of online available answers using impala.dbapi solved the issue:

from impala.dbapi import connect
conn = connect(host='localhost', port = 10000,auth_mechanism='PLAIN')
cursor = conn.cursor()
cursor.execute('show databases')
results = cursor.fetchall()
print(type(results))
print(results)


问:
Unable to create Eventbrite event using API
I am trying to create an event using V3 API. The parameters I am sending are:

```<code>var _event = {
    "event" : {
        "name": {
            "html": "Test Event 01"
        },
        "description": {
            "html": "Test Event 01"
        },
        "start": {
            "timezone": "America/Chicago",
            "utc": "2017-07-10T18:00:00Z"
        },
        "end": {
            "timezone": "America/Chicago",
            "utc": "2017-07-10T20:00:00Z"
        },
        "currency": "USD"
    }
};
</code>```

This is how I am sending the request using NodeJS:

```<code>var request = require('request');
var _headers = {
    'Authorization': 'Bearer ' + _token,
    'Content-Type': 'application/json',
}

// Configure the request
var options = {
    url: EVENTBRITE_API_URL + "events/",
    method: 'POST',
    headers: _headers,
    form: _event
}
</code>```

I have also tried Content-Type: application/x-url-form-encoded and inside options, JSON.stringify(_event). I also tried to change _event object to:

```<code>var _event = {
    "name": {
        "html": "Test Event 01"
    },
    "description": {
        "html": "Test Event 01"
    },
    "start": {
        "timezone": "America/Chicago",
        "utc": "2017-07-10T18:00:00Z"
    },
    "end": {
        "timezone": "America/Chicago",
        "utc": "2017-07-10T20:00:00Z"
    },
    "currency": "USD"
};
</code>```

I have tried all the combinations but I always get the same response:

```<code>{
    "status_code": 400,
    "error_description": "There are errors with your arguments: event[currency] - Unknown parameter, event.start.timezone - This field is required., event.currency - This field is required., event.start.utc - This field is required., event[start][timezone] - Unknown parameter, event.end.utc - This field is required., event[end][utc] - Unknown parameter, event[description][html] - Unknown parameter, event[name][html] - Unknown parameter, event[end][timezone] - Unknown parameter, event[start][utc] - Unknown parameter, event.end.timezone - This field is required., event.name.html - This field is required.",
    "error": "ARGUMENTS_ERROR"
}
</code>```

Is there any sample create event request anywhere I can look into? What is the problem with above request?

答:
I think the issue is that you're currently sending a form post (by virtue of using the form option), but then your parameters should look like { "event.currency": "USD", "event.name.html": "Test Event 01", ... }. If you want to send JSON, you need to use json: true and pass a JSON-serializable body:

```<code>var request = require('request');
var _headers = {
    'Authorization': 'Bearer ' + _token,
    'Content-Type': 'application/json',
}

// Configure the request
var options = {
    url: EVENTBRITE_API_URL + "events/",
    method: 'POST',
    headers: _headers,

    // Instead of this:
    // form: _event

    // use this:
    json: true, // says you're sending JSON
    body: _event, // so the body should be JSON-serializable
};
</code>```

If you want to stick with a form post, I think this should do it:

```<code>var _event = {
    "event.name.html": "Test Event 01",
    "event.description.html": "Test Event 01",
    "event.start.timezone": "America/Chicago",
    "event.start.utc": "2017-07-10T18:00:00Z",
    "event.end.timezone": "America/Chicago",
    "event.end.utc": "2017-07-10T20:00:00Z",
    "event.currency": "USD",
};

var request = require('request');
var _headers = {
    'Authorization': 'Bearer ' + _token,
    'Content-Type': 'application/x-www-form-urlencoded',
}

// Configure the request
var options = {
    url: EVENTBRITE_API_URL + "events/",
    method: 'POST',
    headers: _headers,
    form: _event,
};
</code>```

Body:
I am trying to create an event using V3 API. The parameters I am sending are:

var _event = {
    "event" : {
        "name": {
            "html": "Test Event 01"
        },
        "description": {
            "html": "Test Event 01"
        },
        "start": {
            "timezone": "America/Chicago",
            "utc": "2017-07-10T18:00:00Z"
        },
        "end": {
            "timezone": "America/Chicago",
            "utc": "2017-07-10T20:00:00Z"
        },
        "currency": "USD"
    }
};

This is how I am sending the request using NodeJS:

var request = require('request');
var _headers = {
    'Authorization': 'Bearer ' + _token,
    'Content-Type': 'application/json',
}

// Configure the request
var options = {
    url: EVENTBRITE_API_URL + "events/",
    method: 'POST',
    headers: _headers,
    form: _event
}

I have also tried Content-Type: application/x-url-form-encoded and inside options, JSON.stringify(_event). I also tried to change _event object to:

var _event = {
    "name": {
        "html": "Test Event 01"
    },
    "description": {
        "html": "Test Event 01"
    },
    "start": {
        "timezone": "America/Chicago",
        "utc": "2017-07-10T18:00:00Z"
    },
    "end": {
        "timezone": "America/Chicago",
        "utc": "2017-07-10T20:00:00Z"
    },
    "currency": "USD"
};

I have tried all the combinations but I always get the same response:

{
    "status_code": 400,
    "error_description": "There are errors with your arguments: event[currency] - Unknown parameter, event.start.timezone - This field is required., event.currency - This field is required., event.start.utc - This field is required., event[start][timezone] - Unknown parameter, event.end.utc - This field is required., event[end][utc] - Unknown parameter, event[description][html] - Unknown parameter, event[name][html] - Unknown parameter, event[end][timezone] - Unknown parameter, event[start][utc] - Unknown parameter, event.end.timezone - This field is required., event.name.html - This field is required.",
    "error": "ARGUMENTS_ERROR"
}

Is there any sample create event request anywhere I can look into? What is the problem with above request?

Body:
I think the issue is that you're currently sending a form post (by virtue of using the form option), but then your parameters should look like { "event.currency": "USD", "event.name.html": "Test Event 01", ... }. If you want to send JSON, you need to use json: true and pass a JSON-serializable body:

var request = require('request');
var _headers = {
    'Authorization': 'Bearer ' + _token,
    'Content-Type': 'application/json',
}

// Configure the request
var options = {
    url: EVENTBRITE_API_URL + "events/",
    method: 'POST',
    headers: _headers,

    // Instead of this:
    // form: _event

    // use this:
    json: true, // says you're sending JSON
    body: _event, // so the body should be JSON-serializable
};

If you want to stick with a form post, I think this should do it:

var _event = {
    "event.name.html": "Test Event 01",
    "event.description.html": "Test Event 01",
    "event.start.timezone": "America/Chicago",
    "event.start.utc": "2017-07-10T18:00:00Z",
    "event.end.timezone": "America/Chicago",
    "event.end.utc": "2017-07-10T20:00:00Z",
    "event.currency": "USD",
};

var request = require('request');
var _headers = {
    'Authorization': 'Bearer ' + _token,
    'Content-Type': 'application/x-www-form-urlencoded',
}

// Configure the request
var options = {
    url: EVENTBRITE_API_URL + "events/",
    method: 'POST',
    headers: _headers,
    form: _event,
};


问:
how to validate string input field for pattern on JSF form
i have a requirement where a input field which takes strings can have only one of these formats, what is the best way to implement this using javascript or jsf validator:

N/A-N-N-N   or   N/A-N-N-N-N

There can be any alphabet in pattern above in place of A. there can be any numeric in pattern above in place of N other than 0.

答:
```<code><h:inputText>
    <f:validateRegex pattern="((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})" />
</h:inputText>
</code>```

from this pattern, it is accepted only if it is in range of 6 to 20 with at least one digit, one upper case letter, one lower case letter and one special symbol (“@#$%”)

Body:
<h:inputText>
    <f:validateRegex pattern="((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})" />
</h:inputText>

from this pattern, it is accepted only if it is in range of 6 to 20 with at least one digit, one upper case letter, one lower case letter and one special symbol (“@#$%”)


问:
android loading and saving images on the device
I am building the application that will load list of news from the website. Each news/headline has an image. I want to save/cash the images so user does not has to download them again.

Q: In your opinion, what would be a better/more sufficient way: Loading images and saving them on the device or use the CacheManager? At the moment I am using the first solution and everything works fine. However, the website has many categories and even more news per category therefore there are lot of images saved on the device. Is it normal in this type of applications to save the images on the device?

Thanks for your help,
marqs

答:
I don't think you should save the images on the device, because of many reasons:

Why wasting the device space on news images? All the user wants is to read the news and thats it. (In your case maybe open it later, but still - not forever)

You can save it on the device and make the app. delete those files after lets say 24 hours..

The main issue is the privacy issue, when the user is deleting the cache files he thinks all the webs he visited has wiped from the device, but in this case they aren't..

Maybe you can just add a "Clean Cache" button in the app. but after all I wrote I think using the Cache-manager is the best way - just because it was meant for those things exactly..

:)

Rotem


问:
Double quotes from excel query when copy/paste from Excel into SQL Server 2012
I have a query Excel in each of my rows, about 2000. When I copy paste all queries into SQL Server roughly 100 rows are showing a error. Might not even be an error but the query will paste into SQL Server with double quotes in front of entire query.

I have error checking in place so it has something to do with the data in my Excel sheet. My query pasted in SQL Server for instance:

```<code>"insert into
</code>```

I cannot paste the entire query or any data, sorry.

Thank you for looking at this

答:
Actually a lot easier then all of the posts here,
in another column do the following formula:

=CLEAN(MyCell)

Body:
I have a query Excel in each of my rows, about 2000. When I copy paste all queries into SQL Server roughly 100 rows are showing a error. Might not even be an error but the query will paste into SQL Server with double quotes in front of entire query.

I have error checking in place so it has something to do with the data in my Excel sheet. My query pasted in SQL Server for instance:

"insert into

I cannot paste the entire query or any data, sorry.

Thank you for looking at this


问:
search for example of inconsistent behavior java-8 stream?
In java 8 documentation (doc order stream), one can see this :

if [a stream] is not ordered, repeated execution might produce different
  results.

my question is quite simple : is there an easy way to illustrate this fact in a little unit test (maybe with an HashMap or some thing like this) ?

[Edit] the whole quote is here :

For sequential streams, the presence or absence of an encounter order does not affect performance, only determinism. If a stream is ordered, repeated execution of identical stream pipelines on an identical source will produce an identical result; if it is not ordered, repeated execution might produce different results.

Thus, my question is about a strictly sequential not parallele execution. It is this case that I'm questioning about.

答:
The obvious answer is that whenever you use unordered you should get different results. For example using this:

```<code>int first = Arrays.asList(1, 2, 3, 4).stream()
           .unordered()
           .parallel()
           .findFirst()
           .get();
System.out.println(first);
</code>```

should produce a result that is not always 1. Because the stream is unordered, so any result out of [1,2,3,4] is possible.

In java-8 this is not true, the stream pipeline does not take that unordered into account:

```<code>    @Override
    public <P_IN> O evaluateParallel(PipelineHelper<T> helper,
                                     Spliterator<P_IN> spliterator) {
        return new FindTask<>(this, helper, spliterator).invoke();
    }
</code>```

But things have change in java-9:

```<code>    @Override
    public <P_IN> O evaluateParallel(PipelineHelper<T> helper,
                                     Spliterator<P_IN> spliterator) {
        // This takes into account the upstream ops flags and the terminal
        // op flags and therefore takes into account findFirst or findAny
        boolean mustFindFirst = StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags());
        return new FindTask<>(this, mustFindFirst, helper, spliterator).invoke();
    }
</code>```

So running the same code  under java-9 multiple times will produce a different result.

There are operations that are already unordered like Stream#generate and Stream#forEach.

Body:
The obvious answer is that whenever you use unordered you should get different results. For example using this:

int first = Arrays.asList(1, 2, 3, 4).stream()
           .unordered()
           .parallel()
           .findFirst()
           .get();
System.out.println(first);

should produce a result that is not always 1. Because the stream is unordered, so any result out of [1,2,3,4] is possible.

In java-8 this is not true, the stream pipeline does not take that unordered into account:

    @Override
    public <P_IN> O evaluateParallel(PipelineHelper<T> helper,
                                     Spliterator<P_IN> spliterator) {
        return new FindTask<>(this, helper, spliterator).invoke();
    }

But things have change in java-9:

    @Override
    public <P_IN> O evaluateParallel(PipelineHelper<T> helper,
                                     Spliterator<P_IN> spliterator) {
        // This takes into account the upstream ops flags and the terminal
        // op flags and therefore takes into account findFirst or findAny
        boolean mustFindFirst = StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags());
        return new FindTask<>(this, mustFindFirst, helper, spliterator).invoke();
    }

So running the same code  under java-9 multiple times will produce a different result.

There are operations that are already unordered like Stream#generate and Stream#forEach.


问:
Can I use Layer Normalization with CNN?
I see the Layer Normalization is the modern normalization method than Batch Normalization, and it is very simple to coding in Tensorflow.
But I think the layer normalization is designed for RNN, and the batch normalization for CNN.
Can I use the layer normalization with CNN that process image classification task?
What are the criteria for choosing batch normalization or layer?</p>

答:
You can use Layer normalisation in CNNs, but i don't think it more 'modern' than Batch Norm. They both normalise differently. Layer norm normalises all the activations of a single layer from a batch by collecting statistics from every unit within the layer, while batch norm normalises the whole batch for every single activation, where the statistics is collected for every single unit across the batch.

Batch norm is generally preferred over layer norm as it tries to normalise every activation to a unit gaussian distribution, while layer norm tries to get the 'average' of all activations to unit gaussian. But if the batch size is too small to collect reasonable statistics, then layer norm is preferred.

Title: Can I use Layer Normalization with CNN?


问:
Anyone know how to turn off will_paginate in Spree?
Deleting the lines of

```<code><%  if paginated_products.is_a?(WillPaginate::Collection)
      params.delete(:search)
      params.delete(:taxon)

%><div class="clear"></div><%= will_paginate(paginated_products,
                    :previous_label => "« #{t('previous')}",
                    :next_label => "#{t('next')} »") %>
<%  end -%>
</code>```

Only makes it so that the pagination nav disappears but not the pagination as a whole.

答:
It's a bit hackey but you could just set the per_page setting to something like 1,000 so it wouldn't ever have to paginate the results.

Throwing something like this in config/initializers/will_paginate.rb should work.

```<code>ActiveRecord::Base.instance_eval do
  def per_page
    1000
  end
end
</code>```

Body:
Deleting the lines of

<%  if paginated_products.is_a?(WillPaginate::Collection)
      params.delete(:search)
      params.delete(:taxon)

%>

<%= will_paginate(paginated_products,
                    :previous_label => "« #{t('previous')}",
                    :next_label => "#{t('next')} »") %>
<%  end -%>

Only makes it so that the pagination nav disappears but not the pagination as a whole.

Body:
It's a bit hackey but you could just set the per_page setting to something like 1,000 so it wouldn't ever have to paginate the results.

Throwing something like this in config/initializers/will_paginate.rb should work.

ActiveRecord::Base.instance_eval do
  def per_page
    1000
  end
end


问:
C# Calculation in Xamarin, issue displaying answer.
I am new to C# and Xamarin, I may be going about this solution incorrectly, however I am declaring values that will be obtained by user input 0-10 numbers no decimals no negative numbers. That will do a basic math operation a/b*c=answer... I then want to display the var C (answer) and use that eventually to change a timer interval. However for now, I am having a hard time making the code display my answer as text for the user to see.... Please see my code below. </p>

```<code>[Activity(Label = "Infusion Calculator")]
public class infusionact : Activity
{
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        SetContentView(Resource.Layout.Infusion);
        // Create your application here
        var volume = FindViewById<EditText>(Resource.Id.boxvolume);
        var drip = FindViewById<EditText>(Resource.Id.boxdrip);
        var dripmins = FindViewById<EditText>(Resource.Id.boxmins);
        var answermins = (Resource.Id.boxvolume / Resource.Id.boxmins * Resource.Id.boxdrip);

        Button button = FindViewById<Button>(Resource.Id.btncalculate);
        TextView textView1 = (TextView)FindViewById(Resource.Id.textView1);

        button.Click += delegate
        {
            // NEED TO FIGURE OUT HOW TO SET TXT LABEL WITH VAR ANSWERMINS ON CLICK
            textView1.SetText(answermins);

        };

    }

}
</code>```

答:
Remove the line because you are using the resource ID to do calculation and not the value in the EditText.

```<code>var answermins = (Resource.Id.boxvolume / Resource.Id.boxmins * Resource.Id.boxdrip);
</code>```

Update the click event to do the calculation.

```<code>button.Click += delegate
    {
        var volumeValue = 0;
        var dripValue = 0;
        var dripMinsValue = 0;

        // Parse value in text to integer
        int.TryParse(volume.Text, out volumeValue);
        int.TryParse(drip.Text, out dripValue);
        int.TryParse(dripmins.Text, out dripMinsValue);

        var answermins = 0;
        if (dripMinsValue != 0)
        {
            answermins = volumeValue / dripMinsValue * dripValue;
        }

        textView1.SetText(answermins);
    };
</code>```

Body:
I am new to C# and Xamarin, I may be going about this solution incorrectly, however I am declaring values that will be obtained by user input 0-10 numbers no decimals no negative numbers. That will do a basic math operation a/b*c=answer... I then want to display the var C (answer) and use that eventually to change a timer interval. However for now, I am having a hard time making the code display my answer as text for the user to see.... Please see my code below.

[Activity(Label = "Infusion Calculator")]
public class infusionact : Activity
{
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        SetContentView(Resource.Layout.Infusion);
        // Create your application here
        var volume = FindViewById<EditText>(Resource.Id.boxvolume);
        var drip = FindViewById<EditText>(Resource.Id.boxdrip);
        var dripmins = FindViewById<EditText>(Resource.Id.boxmins);
        var answermins = (Resource.Id.boxvolume / Resource.Id.boxmins * Resource.Id.boxdrip);

        Button button = FindViewById<Button>(Resource.Id.btncalculate);
        TextView textView1 = (TextView)FindViewById(Resource.Id.textView1);

        button.Click += delegate
        {
            // NEED TO FIGURE OUT HOW TO SET TXT LABEL WITH VAR ANSWERMINS ON CLICK
            textView1.SetText(answermins);

        };

    }

}

Body:
Remove the line because you are using the resource ID to do calculation and not the value in the EditText.

var answermins = (Resource.Id.boxvolume / Resource.Id.boxmins * Resource.Id.boxdrip);

Update the click event to do the calculation.

button.Click += delegate
    {
        var volumeValue = 0;
        var dripValue = 0;
        var dripMinsValue = 0;

        // Parse value in text to integer
        int.TryParse(volume.Text, out volumeValue);
        int.TryParse(drip.Text, out dripValue);
        int.TryParse(dripmins.Text, out dripMinsValue);

        var answermins = 0;
        if (dripMinsValue != 0)
        {
            answermins = volumeValue / dripMinsValue * dripValue;
        }

        textView1.SetText(answermins);
    };


问:
Reading Custom HTTP response headers in Angular 2
In my angular 2 application , I am making a HTTP POST request to a service(HTTPS) , the HTTP response returned by service
has a custom RESPONSE header "X-COUNT", but in below code the console.log does not print info about custom header "X-COUNT" , but it does print
info about other headers.

```<code>this._http.post(restUri, postdata, options)
            .map(itemsResult =>
            {
                console.log(JSON.stringify(itemsResult.headers));
                return items;
        }).catch((err) => {

            return Observable.of([]);

        });
</code>```

Any idea why I am not able to get custom header info.

答:
Since not all headers are allowed to be accessed from client side, You need to expose the "X-COUNT" header from the server side. "access-control-expose-headers" is used for that purpose.

Hope this helps.

Body:
In my angular 2 application , I am making a HTTP POST request to a service(HTTPS) , the HTTP response returned by service
has a custom RESPONSE header "X-COUNT", but in below code the console.log does not print info about custom header "X-COUNT" , but it does print
info about other headers.

this._http.post(restUri, postdata, options)
            .map(itemsResult =>
            {
                console.log(JSON.stringify(itemsResult.headers));
                return items;
        }).catch((err) => {

            return Observable.of([]);

        });

Any idea why I am not able to get custom header info.


问:
sql select update multiple column and check not null before update
I have two tables.

Table1 structure NOT NULL.

Table2 some value NULL.

I want update table2 to table1 ,

I want when select value if null don't update and skip next column have value to update.

My Table

```<code>table1      value(table1)      table2       value(table2)
t1ID        1234               t2ID         1234
t1Name      Bear               t2Name       null
t1Adress    87/25              t2Adress     99/77
t1Tel       01254798535        t2Tel        null
</code>```

My Code

```<code>UPDATE table1
SET t1Name = (SELECT t2Name
    FROM table2
    WHERE t2Name IS NOT NULL
    ),
    t1Adress = (SELECT t2Adress
    FROM table2
    WHERE t2Adress IS NOT NULL
    ),
    t1Tel = (SELECT t2Tel
    FROM table2
    WHERE t2Tel IS NOT NULL
    )
FROM table1,table2
WHERE t1ID = '1234' AND t2ID ='1234'
</code>```

When I execute I get error:

SQL error : Msg 512, Level 16, State 1, Line 1 Subquery returned more
  than 1 value.  This is not permitted when the subquery follows =, !=,
  <, <= , >, >= or when the subquery is used as an expression.  The
  statement has been terminated.

How can I fix it?

答:
I think you intend:

```<code>UPDATE t1
    SET t1Name = COALESCE(t2.t2Name, t1.t1Name),
        t1Adress = COALESCE(t2.t2Adress, t1.t1Adress),
        t1Tel = COALESCE(t2.t2Tel, t1.t2Tel)
    FROM table1 t1 JOIN
         table2 t2
         ON t1.t1id = t2.t2id
    WHERE t1.t1ID = 1234;
</code>```

Note that I removed the single quotes on '1234'.  Ids are usually numbers so they should be compared to numbers.

Your code fails because you are using subqueries instead of the values from the join.  You seem to have multiple rows in table2, so you are getting the subquery returned more than one row error.

Body:
I have two tables.

Table1 structure NOT NULL.

Table2 some value NULL.

I want update table2 to table1 ,

I want when select value if null don't update and skip next column have value to update.

My Table

table1      value(table1)      table2       value(table2)
t1ID        1234               t2ID         1234
t1Name      Bear               t2Name       null
t1Adress    87/25              t2Adress     99/77
t1Tel       01254798535        t2Tel        null

My Code

UPDATE table1
SET t1Name = (SELECT t2Name
    FROM table2
    WHERE t2Name IS NOT NULL
    ),
    t1Adress = (SELECT t2Adress
    FROM table2
    WHERE t2Adress IS NOT NULL
    ),
    t1Tel = (SELECT t2Tel
    FROM table2
    WHERE t2Tel IS NOT NULL
    )
FROM table1,table2
WHERE t1ID = '1234' AND t2ID ='1234'

When I execute I get error:

SQL error : Msg 512, Level 16, State 1, Line 1 Subquery returned more
  than 1 value.  This is not permitted when the subquery follows =, !=,
  <, <= , >, >= or when the subquery is used as an expression.  The
  statement has been terminated.

How can I fix it?

Body:
I think you intend:

UPDATE t1
    SET t1Name = COALESCE(t2.t2Name, t1.t1Name),
        t1Adress = COALESCE(t2.t2Adress, t1.t1Adress),
        t1Tel = COALESCE(t2.t2Tel, t1.t2Tel)
    FROM table1 t1 JOIN
         table2 t2
         ON t1.t1id = t2.t2id
    WHERE t1.t1ID = 1234;

Note that I removed the single quotes on '1234'.  Ids are usually numbers so they should be compared to numbers.

Your code fails because you are using subqueries instead of the values from the join.  You seem to have multiple rows in table2, so you are getting the subquery returned more than one row error.


问:
NFC tag not detected on iOS11 iphone 7
I have downloaded sample app from WWDC and tried all the steps including provisioning profile and setting up NFC capabilities and adding to project entitlements file. I can successfully ran the app and the sheet successfully appear

But When I tapped on one of my NFC tag. Nothing happens. How can i go further testing for NFC and may I know which one tag do I need to use to be detectable.
Please see my attached NFC tag which I am using currently.

答: iOS11 currently only detects NDEF formatted tags. So you shoould make sure that your tag is actually formatted correctly. Easiest way would be to use an Android Phone and NFC TagInfo.</p>

Title: NFC tag not detected on iOS11 iphone 7


问:
Tripadvisor web scraping using python
i am using the following code to extract reviews from a url using python, but the exported csv doesnt have all reviews in a column. Instead, it exports data in different columns.
Do i have to add any code to the existing one?</p>

```<code>import requests
from unidecode import unidecode
from bs4 import BeautifulSoup
URL = "https://www.tripadvisor.in/Hotel_Review-g295424-d1735662-Reviews-
Winchester_Grand_Hotel_Apartments-Dubai_Emirate_of_Dubai/"
r = requests.get(URL)
soup = BeautifulSoup(r.content, 'html5lib')

resultsoup = soup.find_all("p", {"class" : "partial_entry"})

with open('testreview.csv', 'w') as fid:
   for review in resultsoup:
      review_list = review.get_text()
      fid.write(unidecode(review_list))
</code>```

答:
All you need is probably to add a new line character ('\n') to the line you're writing to file.

All you need is probably to add a new line character ('\n') to the line you're writing to file.

```<code>with open('testreview.csv', 'w') as fid:
    for review in resultsoup:
        review_list = review.get_text()
        fid.write(unidecode(review_list+'\n'))
</code>```

Title: Tripadvisor web scraping using python

Body:
i am using the following code to extract reviews from a url using python, but the exported csv doesnt have all reviews in a column. Instead, it exports data in different columns.
Do i have to add any code to the existing one?

import requests
from unidecode import unidecode
from bs4 import BeautifulSoup
URL = "https://www.tripadvisor.in/Hotel_Review-g295424-d1735662-Reviews-
Winchester_Grand_Hotel_Apartments-Dubai_Emirate_of_Dubai/"
r = requests.get(URL)
soup = BeautifulSoup(r.content, 'html5lib')

resultsoup = soup.find_all("p", {"class" : "partial_entry"})

with open('testreview.csv', 'w') as fid:
   for review in resultsoup:
      review_list = review.get_text()
      fid.write(unidecode(review_list))

Body:
All you need is probably to add a new line character ('\n') to the line you're writing to file.

All you need is probably to add a new line character ('\n') to the line you're writing to file.

with open('testreview.csv', 'w') as fid:
    for review in resultsoup:
        review_list = review.get_text()
        fid.write(unidecode(review_list+'\n'))


问:
Return the contents of an image in php file?
I really do not know any PHP but I'd love to do one simple thing:

I access a php page from within a  and I'd like to have an image returned from another URL.

I came up with:

```<code><?php
header('Content-Type: image/png');
readfile('i' . rand(1,3) . '.png');
exit;
</code>```

And it works:

Avatar selection http://vercas.webuda.com/img.php?.png

(Reload the page a few times!)

答:
Why not just reference the image directly then? If you are trying to hide the fact you are pulling an image from an external source, that external source will still be able to tell you are pulling their images.

Otherwise, pass a Content-Type header with the appropriate mime-type and echo the results of file_get_contents($imageUrl).

Body:
I really do not know any PHP but I'd love to do one simple thing:

I access a php page from within a  and I'd like to have an image returned from another URL.

I came up with:

<?php
header('Content-Type: image/png');
readfile('i' . rand(1,3) . '.png');
exit;

And it works:

Avatar selection http://vercas.webuda.com/img.php?.png

(Reload the page a few times!)


问:
Sub query to eliminate duplicates in the result set
```<code>select
         PIH.[No_] as [Document No]
        ,PIH.[Pre-Assigned No_] as [Original No]
        ,PIL. [Description]
        ,(PL.[Outstanding Quantity]*PL.[Direct Unit Cost]) as Dispute_Amt
        ,100*(COALESCE(PL.[Outstanding Quantity]*PL.[Direct Unit Cost] / NULLIF(PL.[Amount],0), 0) ) as [Dispute%]
        ,PIH.[Buy-from Vendor Name]
        ,PIH.[Buy-from Vendor No_]
        ,PH."Creation Date"
        ,PH."Expected Receipt Date" as [Actl.Posting Date]
        ,PH."Document Date"
        ,PIH.[Notes] as [Header Notes]
        ,(PL.[Outstanding Quantity] *PL.[Direct Unit Cost]) as [Tolerance Amount]
        ,100*(COALESCE(PL.[Outstanding Quantity]*PL.[Direct Unit Cost] / NULLIF(PL.[Amount],0), 0) ) as [Tolerance%]
        ,PL.[Document No_] as [P.O.Number]
        ,PL.[Original Quantity]  as [PO.Quantity]
        ,PL.[Amount] as [PO Value]
        ,PL.[Quantity Received] as [Delivered Qty]
        ,PL.[Quantity Invoiced] as [Invoiced Qty]
        ,PL.[Return Qty_ to Ship] as [Return Qty]
        ,PL.[Outstanding Quantity]
        ,PL.[Direct Unit Cost]
                 from [ Trading$Purch_ Inv_ Header] PIH
        Inner join [Trading$Purch_ Inv_ Line] PIL
        ON PIH.[No_]=PIL.[Document No_]
        inner join [Trading$Purchase Header] PH
        ON PH.[No_]=PIH.[PO Number]
        inner join [Trading$Purchase Line] PL
        On PL.[Document No_]=PH.[No_]
        where
        PIL.[No_]  in ('170050','700220','700300')
</code>```

[If am using this code iam getting 4500 records ,but i want to filter the result set by eliminating duplicate PIH[Document_No] with PIL[No_]'s 170050,700220,700300 with invoice issues like missing stock,Invoice dispute amount etc  i.e no records with dispute amt zero should come up.

any help please?

    ]

答:
WHERE PL.[Outstanding Quantity]*PL.[Direct Unit Cost] is not null
and PL.[Outstanding Quantity]*PL.[Direct Unit Cost] <> 0</p>

Body:
select
         PIH.[No_] as [Document No]
        ,PIH.[Pre-Assigned No_] as [Original No]
        ,PIL. [Description]
        ,(PL.[Outstanding Quantity]*PL.[Direct Unit Cost]) as Dispute_Amt
        ,100*(COALESCE(PL.[Outstanding Quantity]*PL.[Direct Unit Cost] / NULLIF(PL.[Amount],0), 0) ) as [Dispute%]
        ,PIH.[Buy-from Vendor Name]
        ,PIH.[Buy-from Vendor No_]
        ,PH."Creation Date"
        ,PH."Expected Receipt Date" as [Actl.Posting Date]
        ,PH."Document Date"
        ,PIH.[Notes] as [Header Notes]
        ,(PL.[Outstanding Quantity] *PL.[Direct Unit Cost]) as [Tolerance Amount]
        ,100*(COALESCE(PL.[Outstanding Quantity]*PL.[Direct Unit Cost] / NULLIF(PL.[Amount],0), 0) ) as [Tolerance%]
        ,PL.[Document No_] as [P.O.Number]
        ,PL.[Original Quantity]  as [PO.Quantity]
        ,PL.[Amount] as [PO Value]
        ,PL.[Quantity Received] as [Delivered Qty]
        ,PL.[Quantity Invoiced] as [Invoiced Qty]
        ,PL.[Return Qty_ to Ship] as [Return Qty]
        ,PL.[Outstanding Quantity]
        ,PL.[Direct Unit Cost]
                 from [ Trading$Purch_ Inv_ Header] PIH
        Inner join [Trading$Purch_ Inv_ Line] PIL
        ON PIH.[No_]=PIL.[Document No_]
        inner join [Trading$Purchase Header] PH
        ON PH.[No_]=PIH.[PO Number]
        inner join [Trading$Purchase Line] PL
        On PL.[Document No_]=PH.[No_]
        where
        PIL.[No_]  in ('170050','700220','700300')

[If am using this code iam getting 4500 records ,but i want to filter the result set by eliminating duplicate PIH[Document_No] with PIL[No_]'s 170050,700220,700300 with invoice issues like missing stock,Invoice dispute amount etc  i.e no records with dispute amt zero should come up.

any help please?

    ]


问:
Create a text file with a variable name and write to it
For an application i'm working on, i am trying to create a 'save data' feature.

First off, it needs to create a .txt file with a custom name, this needs to be the date (today) and the text of a textbox, it needs to be in the format of yyyymmdd_textbox1(.txt)

How would i go about doing this? it can create it where ever, but if it already exists it needs to append to it on a new line

thanks for any responses

答:
If you want a file-name from user-input you first need this method:

```<code>Public Function SanitizeFileName(fileName as String) As String
    For Each c In IO.Path.GetInvalidFileNameChars()
        filename = filename.Replace(c, "_"c)
    Next
    Return fileName
End Function
</code>```

Then it's easy

```<code>Dim filename = $"{DateTime.Today.ToString("yyyyMMdd")}_{SanitizeFileName(textbox1.Text)}.txt"
</code>```

Body:
If you want a file-name from user-input you first need this method:

Public Function SanitizeFileName(fileName as String) As String
    For Each c In IO.Path.GetInvalidFileNameChars()
        filename = filename.Replace(c, "_"c)
    Next
    Return fileName
End Function

Then it's easy

Dim filename = $"{DateTime.Today.ToString("yyyyMMdd")}_{SanitizeFileName(textbox1.Text)}.txt"


问:
Create python script that don't depend on modules
I've made a python script that depends of numpy, cv2 and some other modules to run and need to run it on a Linux server where I'm not allowed to install anything.
Is there a way to join all that stuff into a single executable that runs without installing anything?</p>

答:
You could create a standalone executable using Nuitka. Assuming you have all required packages on your development machine you can run

```<code>nuitka --python-version=2.7 --standalone foobar
</code>```

Just make sure you run it with the standalone flag and correct python version.

Body:
You could create a standalone executable using Nuitka. Assuming you have all required packages on your development machine you can run

nuitka --python-version=2.7 --standalone foobar

Just make sure you run it with the standalone flag and correct python version.


问:
Using CSS selectors to access specific table rows with selenium
If I have the following HTML:

```<code><tbody id="items">
<tr><td>Item 1</td></tr>
<tr><td>Item 2</td></tr>
<tr><td>Item 3</td></tr>
<tr><td>Item 4</td></tr>
<tr><td>Item 5</td></tr>
<tr><td>Item 6</td></tr>
</tbody>
</code>```

How would I use CSS selectors with Selenium to access Item 4(or really any item I wanted)?

答:
Do you want to select by content ("Item 4")? By Position (the 4st row)? Or is
 and selecting
    tr#foo>td
an option?

Body:
If I have the following HTML:

Item 1

Item 2

Item 3

Item 4

Item 5

Item 6

How would I use CSS selectors with Selenium to access Item 4(or really any item I wanted)?

Body:
Do you want to select by content ("Item 4")? By Position (the 4st row)? Or is <tr id="foo"> and selecting
    tr#foo>td
an option?


答: It sounds like you're looking for PyInstaller, which bundles all the modules your script depends on into a single program. It even includes Python itself. There are a few alternatives, some of which are listed on this page.</p>

Title: Create python script that don't depend on modules

Body:
I've made a python script that depends of numpy, cv2 and some other modules to run and need to run it on a Linux server where I'm not allowed to install anything.
Is there a way to join all that stuff into a single executable that runs without installing anything?