问:
Read and save list of Object using list of interface

I have seen someone's code and unable to understand how it works.

As the code save List of object in list of Interfaces and can read it back.

Please explain how it works. And can we save Object in interface (where Object implements it). AFAIK interface doesn't have members. How this code save and retrieve please explain.

ContactBO implementing BusinessObject

```<code>public class ContactBO implements BusinessObject {

    private String id, fullName, department, ;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    @Override
    public boolean isSection() {
        // TODO Auto-generated method stub
        return false;
    }

}
</code>```

Where BussinessObject

```<code>public interface BusinessObject {
    boolean isSection();
}
</code>```

Saving list of Contact code

```<code>List<ContactBO> contactList = new Gson().fromJson(jsonArray.toString(),
                new TypeToken<List<ContactBO>>() {}.getType());
        List<BusinessObject> list = new ArrayList<BusinessObject>();
        list.addAll(contactList);
</code>```

read List of ContactBO using List of Interface

```<code>List<ContactBO> contactListItems = (List<ContactBO>) (List<?>) result.list;//where list is public List<BusinessObject> list;
</code>```

答:
Here is what I can understand from the source.

```<code>List<ContactBO> contactList = new Gson().fromJson(jsonArray.toString(),
                new TypeToken<List<ContactBO>>() {}.getType());
</code>```

This does not mean

As the code save List of object in list of Interfaces and can read it
  back

The above line converts response using GSON to a List object of type ContactBO.
By implementing BusinessObject interface,  ContactBO is still a class and not an interface.

Now the next line

```<code>List<BusinessObject> list = new ArrayList<BusinessObject>();
</code>```

This again creates a List of type BusinessObject

Now the following line. list.addAll(contactList); Adds object of type ContactList to super object which is of type BusinessObject

Body:
I have seen someone's code and unable to understand how it works.

As the code save List of object in list of Interfaces and can read it back.

Please explain how it works. And can we save Object in interface (where Object implements it). AFAIK interface doesn't have members. How this code save and retrieve please explain.

ContactBO implementing BusinessObject

public class ContactBO implements BusinessObject {

    private String id, fullName, department, ;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    @Override
    public boolean isSection() {
        // TODO Auto-generated method stub
        return false;
    }

}

Where BussinessObject

public interface BusinessObject {
    boolean isSection();
}

Saving list of Contact code

List<ContactBO> contactList = new Gson().fromJson(jsonArray.toString(),
                new TypeToken<List<ContactBO>>() {}.getType());
        List<BusinessObject> list = new ArrayList<BusinessObject>();
        list.addAll(contactList);

read List of ContactBO using List of Interface

List<ContactBO> contactListItems = (List<ContactBO>) (List<?>) result.list;//where list is public List<BusinessObject> list;

Body:
Here is what I can understand from the source.

List<ContactBO> contactList = new Gson().fromJson(jsonArray.toString(),
                new TypeToken<List<ContactBO>>() {}.getType());

This does not mean

As the code save List of object in list of Interfaces and can read it
  back

The above line converts response using GSON to a List object of type ContactBO.
By implementing BusinessObject interface,  ContactBO is still a class and not an interface.

Now the next line

List<BusinessObject> list = new ArrayList<BusinessObject>();

This again creates a List of type BusinessObject

Now the following line. list.addAll(contactList); Adds object of type ContactList to super object which is of type BusinessObject


来源: stackexchange

问:
How to get the last x lines of a string in Java?
I get some result from an external command (semi-api) and want to parse the result.
I'm only interested in the last few lines of the result.

How can get the last x lines of a string in Java?

答:
Java 8 Streams (memory friendly) answer.

Code:

```<code>public class Main
{
    public static void main( String[] args )
    {
        String rawData = "John\n\nDavid\nGeorge\nFrank\nTom";

        Pattern pattern = Pattern.compile("\\n");

        System.out.println( lastN( pattern.splitAsStream( rawData ),4));
        System.out.println( lastN( pattern.splitAsStream( rawData ),40));
    }

    public static <T> List<T> lastN( Stream<T> stream, int n )
    {
        Deque<T> result = new ArrayDeque<>( n );
        stream.forEachOrdered( x -> {
            if ( result.size() == n )
            {
                result.pop();
            }
            result.add( x );
        } );
        return new ArrayList<>( result );
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Java 8 Streams (memory friendly) answer.

Code:

public class Main
{
    public static void main( String[] args )
    {
        String rawData = "John\n\nDavid\nGeorge\nFrank\nTom";

        Pattern pattern = Pattern.compile("\\n");

        System.out.println( lastN( pattern.splitAsStream( rawData ),4));
        System.out.println( lastN( pattern.splitAsStream( rawData ),40));
    }

    public static <T> List<T> lastN( Stream<T> stream, int n )
    {
        Deque<T> result = new ArrayDeque<>( n );
        stream.forEachOrdered( x -> {
            if ( result.size() == n )
            {
                result.pop();
            }
            result.add( x );
        } );
        return new ArrayList<>( result );
    }
}


问:
php url_exists function for https urls
```function url_exists($url) {
        $return = false;
        $content=@file_get_contents($url, FALSE, NULL, 0, 20);
        if($content == false ) {
            $return = false;
        } else if (count($content) ```

How to modify this function to check on content on https URLS as well. This is currently not able to check existense of file there.

答: Have you tried PHPs file_exists() that supports URLs, too?

ContentLicense: CC BY-SA 2.5

Title: php url_exists function for https urls

Body:
function url_exists($url) {
        $return = false;
        $content=@file_get_contents($url, FALSE, NULL, 0, 20);
        if($content == false ) {
            $return = false;
        } else if (count($content)

How to modify this function to check on content on https URLS as well. This is currently not able to check existense of file there.


问:
how to pass the data from jsp page(for each) to servlet class
I Have JSP code like this. I fetch the Image and data of the product using `forach in one page:

```<code><c:forEach var="product" items="${products}" >
<div class="col-md-3">
    <div class="panel-body">
        <div>
            <a href="description.html">
                <div class="thumbnail">
                    <img src="data:image/jpeg;base64,${product.base64EncodedImage}" alt="image">
                    <div class="caption" align="center">
                        <p>
                            <h4>${product.name}</h4>
                            <h5>cost:Rs ${product.price}/-</h5>
                        </p>
                    </div>
                </div>
            </a>
        </div>
    </div>
</div>
</code>```

Image of fetched data

Now I have to get the data and image OF PARTICULAR PRODUCT when I click on a tumbnail. I have to get the data in the servlet class and have to print the output in another page:

This is what I expect to see when I click on a thumbnail:

答:
Pass product details to servlet using URL parameters:

```<code><img src="data:image/jpeg;base64,${product.base64EncodedImage}" alt="image" href="<your-servlet>?productId=${product.productId}">
</code>```

Retrieve the same in your Product detail servlet class and read the same,passing on the details to the respective page

```<code>request.getParameter("productId")
</code>```

Body:
I Have JSP code like this. I fetch the Image and data of the product using `forach in one page:

<c:forEach var="product" items="${products}" >

${product.name}

cost:Rs ${product.price}/-

Image of fetched data

Now I have to get the data and image OF PARTICULAR PRODUCT when I click on a tumbnail. I have to get the data in the servlet class and have to print the output in another page:

This is what I expect to see when I click on a thumbnail:

Body:
Pass product details to servlet using URL parameters:

<img src="data:image/jpeg;base64,${product.base64EncodedImage}" alt="image" href="<your-servlet>?productId=${product.productId}">

Retrieve the same in your Product detail servlet class and read the same,passing on the details to the respective page

request.getParameter("productId")


问:
Can I store only month and year part of the date into a DATE column in Oracle 11g?
Please don't confuse this as selecting month and year from an already stored date value. I need to store only month and year and retrieve it as. The column data type has to be DATE and not VARCHAR.</p>

答:
A DATE data type is stored internally as 7- or 8-bytes and always has day, hour, minute and second components. So, if you are using a DATE data type then you will always have to store those values.

However, you can use TRUNC( date_value, 'MM' ) to truncate the date to the first day of the month and add this to a check constraint on your table to ensure that the day/time components are always a fixed value (01 00:00:00):

```<code>CREATE TABLE your_table (
  date_column DATE
              CONSTRAINT your_table__date_column__chk
                CHECK ( date_column = TRUNC( date_column, 'MM' ) )
);

INSERT INTO your_table ( date_column )
VALUES ( TRUNC( SYSDATE, 'MM' ) );
</code>```

Body:
A DATE data type is stored internally as 7- or 8-bytes and always has day, hour, minute and second components. So, if you are using a DATE data type then you will always have to store those values.

However, you can use TRUNC( date_value, 'MM' ) to truncate the date to the first day of the month and add this to a check constraint on your table to ensure that the day/time components are always a fixed value (01 00:00:00):

CREATE TABLE your_table (
  date_column DATE
              CONSTRAINT your_table__date_column__chk
                CHECK ( date_column = TRUNC( date_column, 'MM' ) )
);

INSERT INTO your_table ( date_column )
VALUES ( TRUNC( SYSDATE, 'MM' ) );


答:
NO you can t store just month and year part of the date into a DATE column in oracle 11g

look this link

Title: Can I store only month and year part of the date into a DATE column in Oracle 11g?

Body: Please don't confuse this as selecting month and year from an already stored date value. I need to store only month and year and retrieve it as. The column data type has to be DATE and not VARCHAR.


问:
Fetch all first child elements from a table
Pretty simple I need to fetch all first type of th elements text :

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

  <table>
  <tr>
    <th>1</th>
    <th>2</th>
    <th>3</th>
  </tr>
  <tr>
    <td>Line #1</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Line #2</td>
    <td>SLD</td>
    <td>68</td>
  </tr>
  <tr>
    <td>Line #3</td>
    <td>MDK</td>
    <td>68</td>
  </tr>
</table>

<script type="text/javascript">

console.log(document.querySelectorAll('table tr td:first-of-type'));

</script>

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

I want to be able to fetch all table tr td:first-of-type innertext... small tweak needed here.

答:
table tr td:first-child

As Dan Philip mentioned, you need to adjust your HTML like below.

```<code><table>
  <tr>
    <td>Line #1</td>
    <td>Lastname</td>
    <td>Age</td>
  </tr>
  <tr>
    <td>Line #2</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Line #3</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
</table>
</code>```

Here's a Codepen.io example using jquery (just to illustrate):

https://codepen.io/wykydtronik/pen/yMGMYw

```<code>$( "table tr td:first-child" )
  .css( "text-decoration", "underline" )
  .hover(function() {
    $( this ).addClass( "gogreen" );
  }, function() {
    $( this ).removeClass( "gogreen" );
  });

var theFirstChilds = document.querySelectorAll('table tr td:first-child');

console.log(theFirstChilds[0]);
console.log(theFirstChilds[1]);
console.log(theFirstChilds[2]);
</code>```

Note the jQuery is just an example of what you're attempting to do. On codepen you can open up the console at the bottom to see what the objects stored from the node.

Body:
Pretty simple I need to fetch all first type of th elements text :

    1
    2
    3

    Line #1
    Smith
    50

    Line #2
    SLD
    68

    Line #3
    MDK
    68

I want to be able to fetch all table tr td:first-of-type innertext... small tweak needed here.

Body:
table tr td:first-child

As Dan Philip mentioned, you need to adjust your HTML like below.

<table>
  <tr>
    <td>Line #1</td>
    <td>Lastname</td>
    <td>Age</td>
  </tr>
  <tr>
    <td>Line #2</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Line #3</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
</table>

Here's a Codepen.io example using jquery (just to illustrate):

https://codepen.io/wykydtronik/pen/yMGMYw

$( "table tr td:first-child" )
  .css( "text-decoration", "underline" )
  .hover(function() {
    $( this ).addClass( "gogreen" );
  }, function() {
    $( this ).removeClass( "gogreen" );
  });

var theFirstChilds = document.querySelectorAll('table tr td:first-child');

console.log(theFirstChilds[0]);
console.log(theFirstChilds[1]);
console.log(theFirstChilds[2]);

Note the jQuery is just an example of what you're attempting to do. On codepen you can open up the console at the bottom to see what the objects stored from the node.


问:
Code to run that can help benchmark a new SAS drive?
We just got a new Server at work that will be used only for running SAS code, and I've been asked to run some tests and make sure that it's performing better than our other servers. I'm not an expert at this so I want to make sure I avoid making naive mistakes that don't properly measure the performance of the server. My header looks like this:

```<code>options fullstimer;
%LET BenchStartTime =  %sysfunc(datetime(),22.);
</code>```

Which I use as a check for the "real time" report in the log. I have a vague understanding of the difference between "user cpu time" and "system cpu time", but if anyone wants to offer up additional information on that, that would be helpful.

Anyway, the main point of this post is that I want to know if there are any standard benchmark tests that I should be using in order to see if this new server is better than the old ones. Currently I'm using something I found online which is just appending a bunch of copies of sashelp.class (but I think this might be a bad idea because pulling from the C: and loading it into a different drive might be the same across all servers, right? If the C: is the slowest drive, doesn't that become the bottleneck?), and I'm also using code that basically generates a bunch of random data of a fixed size and comparing runtimes. Is this the correct approach? Is there something else I should be doing? How many times should I be running these benchmark tests to make sure that it isn't a fluke?

Thanks for your help!

答:
On SAS 9.2 and later you can use the %SASHOME%/SASFoundation/9.x/sasiotest.exe utility. You will find some further Guidance in Support note 51659.

Edit:

A similiar utility can be downloaded for Unix Plattform, details in Support note 51660.

Body:
We just got a new Server at work that will be used only for running SAS code, and I've been asked to run some tests and make sure that it's performing better than our other servers. I'm not an expert at this so I want to make sure I avoid making naive mistakes that don't properly measure the performance of the server. My header looks like this:

options fullstimer;
%LET BenchStartTime =  %sysfunc(datetime(),22.);

Which I use as a check for the "real time" report in the log. I have a vague understanding of the difference between "user cpu time" and "system cpu time", but if anyone wants to offer up additional information on that, that would be helpful.

Anyway, the main point of this post is that I want to know if there are any standard benchmark tests that I should be using in order to see if this new server is better than the old ones. Currently I'm using something I found online which is just appending a bunch of copies of sashelp.class (but I think this might be a bad idea because pulling from the C: and loading it into a different drive might be the same across all servers, right? If the C: is the slowest drive, doesn't that become the bottleneck?), and I'm also using code that basically generates a bunch of random data of a fixed size and comparing runtimes. Is this the correct approach? Is there something else I should be doing? How many times should I be running these benchmark tests to make sure that it isn't a fluke?

Thanks for your help!


问:
How to sort an array as per index value using PHP
I need one help.I need to sort array as per its index value using PHP. I am explaining my code below.

```<code>Array ( [0] => Array ( [id] => 17 [name] => Exhibition ) [2] => Array ( [id] => 16 [name] => Office Space ) [3] => Array ( [id] => 15 [name] => Storage ) [1] => Array ( [id] => 14 [name] => Parking ) )
</code>```

Here this arrays order is different like 0,2,3,1. I need its index like 0,1,2,3. Please help me.

答: ksort() is the answer you need.

Body:
I need one help.I need to sort array as per its index value using PHP. I am explaining my code below.

Array ( [0] => Array ( [id] => 17 [name] => Exhibition ) [2] => Array ( [id] => 16 [name] => Office Space ) [3] => Array ( [id] => 15 [name] => Storage ) [1] => Array ( [id] => 14 [name] => Parking ) )

Here this arrays order is different like 0,2,3,1. I need its index like 0,1,2,3. Please help me.

Body: ksort() is the answer you need.


问:
Using localStorage to store numerical value
I am trying to use localStorage to hold the value of the players health in an HTML5 based game, and when the HP value is below 0, nothing happens.

```<code><!--Calling Statement-->
<ul>
    <li><a href="../S5/S5.html" onclick="alterHP(-3);"
        class="ghost-button">Go on to the next scene</a></li>
</ul>
</code>```

in a separate .js file

```<code>function declareHP() {
    if (typeof (Storage) !== "undefined") {
        localStorage.setItem("HP", "20");
    } else {
        /*Can't Store, Oh well*/
    }
}

function alterHP(value) {
    if (typeof (Storage) !== "undefined") {
        var currentHP = parseInt(localStorage.HP);
        localStorage.HP = currentHP + value;
        if (!(parseInt(localStorage.HP) > 0)) {
            window.location.assign('../youLose.html');
        }
    }
}
</code>```

答:
If you change the line

```<code>var currentHP = parseInt(localStorage.HP);
</code>```

to

```<code>var currentHP = localStorage.HP ? parseInt(localStorage.HP) : 0;
</code>```

it will work

And you could do like this

```<code>function alterHP(value) {
    if (typeof (Storage) !== "undefined") {
        localStorage.HP = (localStorage.HP ? parseInt(localStorage.HP) : 0) + value;
        if (!(parseInt(localStorage.HP) > 0)) {
            window.location.assign('../youLose.html');
        }
    }
}
</code>```

Body:
I am trying to use localStorage to hold the value of the players health in an HTML5 based game, and when the HP value is below 0, nothing happens.

Go on to the next scene

in a separate .js file

function declareHP() {
    if (typeof (Storage) !== "undefined") {
        localStorage.setItem("HP", "20");
    } else {
        /*Can't Store, Oh well*/
    }
}

function alterHP(value) {
    if (typeof (Storage) !== "undefined") {
        var currentHP = parseInt(localStorage.HP);
        localStorage.HP = currentHP + value;
        if (!(parseInt(localStorage.HP) > 0)) {
            window.location.assign('../youLose.html');
        }
    }
}

Body:
If you change the line

var currentHP = parseInt(localStorage.HP);

to

var currentHP = localStorage.HP ? parseInt(localStorage.HP) : 0;

it will work

And you could do like this

function alterHP(value) {
    if (typeof (Storage) !== "undefined") {
        localStorage.HP = (localStorage.HP ? parseInt(localStorage.HP) : 0) + value;
        if (!(parseInt(localStorage.HP) > 0)) {
            window.location.assign('../youLose.html');
        }
    }
}


问:
Add attributes to the selected list items in select2
Here is a working jsfiddle. I wish to add attributes (in particular id) to the
 elements created. My use case is slightly different from the fiddle, rather than using an array, I am getting my data from ajax. In addition I want to give my users flexibility to create new tags if the same are not present in database. To save newly created item list having id's is a much better handle than just plain classes. Can I modify the attributes of the
 elements created?

My actual code is something like this:

```<code>$(".js-data-example-ajax").select2({
        ajax : {
            url : "/content/search_skills",
            dataType : 'json',
            delay : 250,
            data : function(params) {
                return {
                    q : params.term, // search term
                    page : params.page
                };
            },
            processResults : function(data, params) {
                params.page = params.page || 1;

                return {
                    results : data.items,
                    pagination : {
                        more : (params.page * 5) < data.total_count
                    }
                };
            },
            cache : true
        },
        escapeMarkup : function(markup) {
            return markup;
        }, // let our custom formatter work
        minimumInputLength : 1,
        templateResult : formatRepo,
        templateSelection : formatRepoSelection,
        tags : true,
        createTag : function (params) {
            return {
                id: params.term,
                text: params.term,
                newOption: true
              }
            },
    });
    function formatRepo(repo) {
        if (repo.loading)
            return repo.text;

        var markup = '<ul class="list-group clear-list m-t">' + '<li class="list-group-item fist-item"><span class="pull-right">' + repo.id + '</span> <span class="label label-success">' + repo.count + '</span> ' + repo.text + '</li>';

        return markup;
    }

     function formatRepoSelection (repo) {
         var markup = repo.text;
         return markup;
          }
</code>```

And my jsp (html) is:

```<code><select class="js-data-example-ajax" style="width: 100%" multiple="multiple">
    //Iterating through database query result to pre-load option items
    <option value="<%=skill_objective.get("id")%>" selected="selected"><%=skill_objective.get("id")%> <%=skill_objective.get("name") %></option>
</select>
</code>```

答:
Here is a working solution:

$(".js-data-example-ajax").select2('data') will give me a hash of all the objects selected.

Body:
Here is a working jsfiddle. I wish to add attributes (in particular id) to the
 elements created. My use case is slightly different from the fiddle, rather than using an array, I am getting my data from ajax. In addition I want to give my users flexibility to create new tags if the same are not present in database. To save newly created item list having id's is a much better handle than just plain classes. Can I modify the attributes of the
 elements created?

My actual code is something like this:

$(".js-data-example-ajax").select2({
        ajax : {
            url : "/content/search_skills",
            dataType : 'json',
            delay : 250,
            data : function(params) {
                return {
                    q : params.term, // search term
                    page : params.page
                };
            },
            processResults : function(data, params) {
                params.page = params.page || 1;

                return {
                    results : data.items,
                    pagination : {
                        more : (params.page * 5) < data.total_count
                    }
                };
            },
            cache : true
        },
        escapeMarkup : function(markup) {
            return markup;
        }, // let our custom formatter work
        minimumInputLength : 1,
        templateResult : formatRepo,
        templateSelection : formatRepoSelection,
        tags : true,
        createTag : function (params) {
            return {
                id: params.term,
                text: params.term,
                newOption: true
              }
            },
    });
    function formatRepo(repo) {
        if (repo.loading)
            return repo.text;

        var markup = '
' + '
' + repo.id + ' ' + repo.count + ' ' + repo.text + '
';

        return markup;
    }

     function formatRepoSelection (repo) {
         var markup = repo.text;
         return markup;
          }

And my jsp (html) is:

<select class="js-data-example-ajax" style="width: 100%" multiple="multiple">
    //Iterating through database query result to pre-load option items
    <option value="<%=skill_objective.get("id")%>" selected="selected"><%=skill_objective.get("id")%> <%=skill_objective.get("name") %></option>
</select>


问:
How to construct an XML document out of an XPATH Java
I have the following xpath:

```<code>/Parent/Children/child
</code>```

My goal is to construct the following XML document based solely off the xpath above:

```<code><Parent>
  <Children>
    <child></child>
  </Children>
</Parent>
</code>```

How can I accomplish my goal using Java?

答: This can be achieved by using xslt transformation. https://docs.oracle.com/javase/tutorial/jaxp/xslt/transformingXML.html</p>

Body:
I have the following xpath:

/Parent/Children/child

My goal is to construct the following XML document based solely off the xpath above:

<Parent>
  <Children>
    <child></child>
  </Children>
</Parent>

How can I accomplish my goal using Java?


问:
How come Gradle appcompat-v7 error even though the version of the targeSdkVersoin is the same at 24?

The app runs when I build it, and works fine. But I want to solve this problem, cause it may cause problem in the future. The picture shows the error when I hover on it. Any advice on how to fix this issue?

And I'm confused as to why it found two version 24.2.1 and 24.0.0, why is this? Which version is the right one?

Thank You

UPDATE

I run gradlew app:dependencies on the terminal and found this,
if you look at the botton and found this com.android.support:appcompat-v7:24.0.0 (at the bottom):

```<code>+--- com.google.android.gms:play-services:10.2.1
|    +--- com.google.android.gms:play-services-ads:10.2.1
|    |    +--- com.google.android.gms:play-services-ads-lite:10.2.1
|    |    |    \--- com.google.android.gms:play-services-basement:10.2.1
|    |    |         \--- com.android.support:support-v4:24.0.0 -> 24.2.1 (*)
|    |    +--- com.google.android.gms:play-services-base:10.2.1
|    |    |    +--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    |    \--- com.google.android.gms:play-services-tasks:10.2.1
|    |    |         \--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-clearcut:10.2.1
|    |    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    |    \--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    \--- com.google.android.gms:play-services-gass:10.2.1
|    |         \--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    +--- com.google.android.gms:play-services-ads-lite:10.2.1 (*)
|    +--- com.google.android.gms:play-services-analytics:10.2.1
|    |    +--- com.google.android.gms:play-services-analytics-impl:10.2.1
|    |    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    |    \--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    \--- com.google.android.gms:play-services-tagmanager-v4-impl:10.2.1
|    |         +--- com.google.android.gms:play-services-analytics-impl:10.2.1 (*)
|    |         +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |         \--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    +--- com.google.android.gms:play-services-analytics-impl:10.2.1 (*)
|    +--- com.google.android.gms:play-services-appinvite:10.2.1
|    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    \--- com.google.android.gms:play-services-tasks:10.2.1 (*)
|    +--- com.google.android.gms:play-services-auth:10.2.1
|    |    +--- com.google.android.gms:play-services-auth-base:10.2.1
|    |    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    |    \--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    \--- com.google.android.gms:play-services-tasks:10.2.1 (*)
|    +--- com.google.android.gms:play-services-auth-base:10.2.1 (*)
|    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    +--- com.google.android.gms:play-services-cast-framework:10.2.1
|    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-cast:10.2.1
|    |    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    |    +--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    |    \--- **com.android.support:mediarouter-v7:24.0.0**
|    |    |         +--- com.android.support:palette-v7:24.0.0
|    |    |         |    \--- com.android.support:support-v4:24.0.0 -> 24.2.1 (*)
|    |    |         \--- **com.android.support:appcompat-v7:24.0.0** -> 24.2.1 (*)
</code>```

And if I follow the root of it and found com.android.support:mediarouter-v7:24.0.0, so I add it to the dependencies and change it to compile com.android.support:mediarouter-v7:24.2.1, and the error is gone now. Is this the right way of doing it? Btw, I run my app and there is no error(There app still runs before, eventhough there is an error in the gradle).

Thanks

答:
And I'm confused as to why it found two version 24.2.1 and 24.0.0,

You have to use gradlew app:dependencies.

In this way you will find which libraries has the dependency with 24.2.1 and 24.0.0

Body:
The app runs when I build it, and works fine. But I want to solve this problem, cause it may cause problem in the future. The picture shows the error when I hover on it. Any advice on how to fix this issue?

And I'm confused as to why it found two version 24.2.1 and 24.0.0, why is this? Which version is the right one?

Thank You

UPDATE

I run gradlew app:dependencies on the terminal and found this,
if you look at the botton and found this com.android.support:appcompat-v7:24.0.0 (at the bottom):

+--- com.google.android.gms:play-services:10.2.1
|    +--- com.google.android.gms:play-services-ads:10.2.1
|    |    +--- com.google.android.gms:play-services-ads-lite:10.2.1
|    |    |    \--- com.google.android.gms:play-services-basement:10.2.1
|    |    |         \--- com.android.support:support-v4:24.0.0 -> 24.2.1 (*)
|    |    +--- com.google.android.gms:play-services-base:10.2.1
|    |    |    +--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    |    \--- com.google.android.gms:play-services-tasks:10.2.1
|    |    |         \--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-clearcut:10.2.1
|    |    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    |    \--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    \--- com.google.android.gms:play-services-gass:10.2.1
|    |         \--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    +--- com.google.android.gms:play-services-ads-lite:10.2.1 (*)
|    +--- com.google.android.gms:play-services-analytics:10.2.1
|    |    +--- com.google.android.gms:play-services-analytics-impl:10.2.1
|    |    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    |    \--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    \--- com.google.android.gms:play-services-tagmanager-v4-impl:10.2.1
|    |         +--- com.google.android.gms:play-services-analytics-impl:10.2.1 (*)
|    |         +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |         \--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    +--- com.google.android.gms:play-services-analytics-impl:10.2.1 (*)
|    +--- com.google.android.gms:play-services-appinvite:10.2.1
|    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    \--- com.google.android.gms:play-services-tasks:10.2.1 (*)
|    +--- com.google.android.gms:play-services-auth:10.2.1
|    |    +--- com.google.android.gms:play-services-auth-base:10.2.1
|    |    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    |    \--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    \--- com.google.android.gms:play-services-tasks:10.2.1 (*)
|    +--- com.google.android.gms:play-services-auth-base:10.2.1 (*)
|    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    +--- com.google.android.gms:play-services-cast-framework:10.2.1
|    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-cast:10.2.1
|    |    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    |    +--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    |    \--- **com.android.support:mediarouter-v7:24.0.0**
|    |    |         +--- com.android.support:palette-v7:24.0.0
|    |    |         |    \--- com.android.support:support-v4:24.0.0 -> 24.2.1 (*)
|    |    |         \--- **com.android.support:appcompat-v7:24.0.0** -> 24.2.1 (*)

And if I follow the root of it and found com.android.support:mediarouter-v7:24.0.0, so I add it to the dependencies and change it to compile com.android.support:mediarouter-v7:24.2.1, and the error is gone now. Is this the right way of doing it? Btw, I run my app and there is no error(There app still runs before, eventhough there is an error in the gradle).

Thanks


问:
send variable to
I have a option selector, and I want the value of the chosen option to be based on to a href="#top"> tag. So that
Godfather links to #top,
Shawshank to #middle
Fightclub to #bottom

I have the following code:

```<code><select id="one">
    <option></option>
    <option value="1">Godfather</option>
    <option value="2">Shawshank</option>
    <option value="3">Fightclub</option>
</select>
</code>```

Javascript

```<code>var url;

    $("select").change(function () {

        //console.log($(this).val());

        var val = $(this).val();

        if (val == "1") {
            $("#image").css({"background-image": "url(image/godfather.jpg)"});
            url = "goodfather";
        }
        if (val == "2") {
            $("#image").css({"background-image": "url(image/shawshank.jpg)"});
            url = "shawshank";
        }
        if (val == "3") {
            $("#image").css({"background-image": "url(image/fightclub.jpg)"});
                            url = "fightclub";
</code>```

答:
```<code>    <a href="">My Link</a>
    <select id="one">
        <option></option>
        <option value="1">Godfather</option>
        <option value="2">Shawshank</option>
        <option value="3">Fightclub</option>
    </select>

    <div id="goodfather"></div>
    <div id="shawshank"></div>
    <div id="fightclub"></div>
</code>```

here the changes in the js:

```<code>var url;
$("select").change(function () {
  //console.log($(this).val());
  var val = $(this).val();
  if (val == "1") {
    $("#image").css({"background-image": "url(image/godfather.jpg)"});
    url = "goodfather";
  }
  if (val == "2") {
    $("#image").css({"background-image": "url(image/shawshank.jpg)"});
    url = "shawshank";
  }
  if (val == "3") {
    $("#image").css({"background-image": "url(image/fightclub.jpg)"});
    url = "fightclub";
  }
  $('a').attr('href', '#' + url).text(url);
});
</code>```

working fine in fiddle if this is what you are searching for: https://jsfiddle.net/v89c4tg6/

Title: send variable to <a href>

Body:
I have a option selector, and I want the value of the chosen option to be based on to a  tag. So that
Godfather links to #top,
Shawshank to #middle
Fightclub to #bottom

I have the following code:

<select id="one">
    <option></option>
    <option value="1">Godfather</option>
    <option value="2">Shawshank</option>
    <option value="3">Fightclub</option>
</select>

Javascript

var url;

    $("select").change(function () {

        //console.log($(this).val());

        var val = $(this).val();

        if (val == "1") {
            $("#image").css({"background-image": "url(image/godfather.jpg)"});
            url = "goodfather";
        }
        if (val == "2") {
            $("#image").css({"background-image": "url(image/shawshank.jpg)"});
            url = "shawshank";
        }
        if (val == "3") {
            $("#image").css({"background-image": "url(image/fightclub.jpg)"});
                            url = "fightclub";

Body:
    <a href="">My Link</a>
    <select id="one">
        <option></option>
        <option value="1">Godfather</option>
        <option value="2">Shawshank</option>
        <option value="3">Fightclub</option>
    </select>

    <div id="goodfather"></div>
    <div id="shawshank"></div>
    <div id="fightclub"></div>

here the changes in the js:

var url;
$("select").change(function () {
  //console.log($(this).val());
  var val = $(this).val();
  if (val == "1") {
    $("#image").css({"background-image": "url(image/godfather.jpg)"});
    url = "goodfather";
  }
  if (val == "2") {
    $("#image").css({"background-image": "url(image/shawshank.jpg)"});
    url = "shawshank";
  }
  if (val == "3") {
    $("#image").css({"background-image": "url(image/fightclub.jpg)"});
    url = "fightclub";
  }
  $('a').attr('href', '#' + url).text(url);
});

working fine in fiddle if this is what you are searching for: https://jsfiddle.net/v89c4tg6/


问:
Display employee name,total salary of each employee(total salary=salary+commission)
Display employee name, total salary of each employee.

Conditions:

if commission is not NULL then total salary=(salary + commission)

else total salary = salary;

Here is my table:

Table name: myemp

Columns:

```<code>empno [Primary key], name, salary, commission, deptno

create table myemp
(
     empno number primary key,
     name varchar2(20),
     salary number,
     commission number,
     deptno number
);
</code>```

Query:

```<code>select
    name, salary, commission,
    (salary + ((salary*commission) / 100)) as "total_salary"
from myemp;
</code>```

This query give incorrect result.

When commission is NULL, then total_salary = 0. But it should be total_salay=salary;

How to fix this?

答:
select salarymonths as totalearing,count() from Employee  group by totalearing order by totalearing desc limit 1;

created by
Rahul Panwar

Body:
Display employee name, total salary of each employee.

Conditions:

if commission is not NULL then total salary=(salary + commission)

else total salary = salary;

Here is my table:

Table name: myemp

Columns:

empno [Primary key], name, salary, commission, deptno

create table myemp
(
     empno number primary key,
     name varchar2(20),
     salary number,
     commission number,
     deptno number
);

Query:

select
    name, salary, commission,
    (salary + ((salary*commission) / 100)) as "total_salary"
from myemp;

This query give incorrect result.

When commission is NULL, then total_salary = 0. But it should be total_salay=salary;

How to fix this?


问:
Printing statements in thenReturn of mockito
I am using Mockito to mock a certain class while writing my test cases.

Is there a way to print some statements before returning a value? Like:

```<code>when(x.callFunction(10).thenReturn(new String("Hello"));
</code>```

The above statement works, however I am not able to do the following:

```<code>when(x.callFunction(10).thenReturn({
   System.out.println("Mock called---going to return hello");
   return new String("Hello");});
</code>```

答:
With thenAnswer you can execute additional actions every time the mocked method is invoked.

```<code>when(x.callFunction(10)).thenAnswer(new Answer<String>() {
    public String answer(InvocationOnMock invocation)  {
        System.out.println("Mock called---going to return hello");
        return "Hello";
    }
});
</code>```

See also thenAnswer Vs thenReturn.

Body:
I am using Mockito to mock a certain class while writing my test cases.

Is there a way to print some statements before returning a value? Like:

when(x.callFunction(10).thenReturn(new String("Hello"));

The above statement works, however I am not able to do the following:

when(x.callFunction(10).thenReturn({
   System.out.println("Mock called---going to return hello");
   return new String("Hello");});

Body:
With thenAnswer you can execute additional actions every time the mocked method is invoked.

when(x.callFunction(10)).thenAnswer(new Answer<String>() {
    public String answer(InvocationOnMock invocation)  {
        System.out.println("Mock called---going to return hello");
        return "Hello";
    }
});

See also thenAnswer Vs thenReturn.


问:
What causes WriteFile to return ERROR_ACCESS_DENIED?
We currently face the problem of a call to WriteFile (or, rather CFile::Write - but that just calls WriteFile internally) causing the Win32 error 5 ERROR_ACCESS_DENIED.

(EDIT: Note that we can't repro the behavior. All we have at the moment is a logfile indicating the source line where the CFile::Write was and containing as error ERROR_ACCESS_DENIED!)

(EDIT: The file is on a local drive and it is in fact a file and not a directory.)

Now, WriteFiles's documentation doesn't really help, and experimenting with a simple test-app yields the following results:

WriteFile will cause ERROR_ACCESS_DENIED if it is called for a file handle that is not opened for writing (i.e. is opened for reading only).

It will not cause ERROR_ACCESS_DENIED if

The handle is not valid or the file isn't open at all

The access rights, or the write protected flag for the file are modified after the file has been opened by the process. (If these are modified before the file is opened, then we never get to WriteFile because opening the file will fail.)

The file is somehow locked by another process/handle (This will at best result in error 32 ERROR_SHARING_VIOLATION).

That leaves us with the situation, that apparently the only possibility for this call to fail if the file was actually opened with the read flag instead of the write flag. However, looking at our code, this seems extremely unlikely. (Due to our tracing, we can be sure that WriteFile failed and  we can be sure that the error is ERROR_ACCESS_DENIED, we cannot be 100.1% sure of the opening flags, because these are not traced out.)

Are there any other known circumstances where WriteFile (CFile::Write) would cause an ERROR_ACCESS_DENIED?

Note: To additionally clarify the context of this question:

The file was open, therefore it can't be a directory or somesuch

All tests I performed indicate that while the file is open it cannot be deleted, so the file should still have been there on the call to WriteFile

The file is located on a local drive and not on a network drive.

I should add that we're running on WIndows XP sp3 and the app is compiled with Visual Studio 2005.

答:
There is about a dozen different situations that might result in ERROR_ACCESS_DENIED. Internally, all WriteFile does is call NtWriteFile and map its (somewhat meaningful) NTSTATUS error code into a less meaningful HRESULT.

Among other things, ERROR_ACCESS_DENIED could indicate that the file is on a network volume and something went wrong with write permissions, or that the file is really not a file but a directory.


答:
use ksort(), which sorts an array by its keys.

So I created this dummy $test array
example:

```<code>array(4) {
    [0]=> array(2) { ["id"]=> int(1) ["name"]=> string(3) "one" }
    [3]=> array(2) { ["id"]=> int(4) ["name"]=> string(4) "four" }
    [1]=> array(2) { ["id"]=> int(2) ["name"]=> string(3) "two" }
    [2]=> array(2) { ["id"]=> int(3) ["name"]=> string(5) "three" }
}
</code>```

next ksort() Sorts an array by key, maintaining key to data correlations.

```<code>ksort($test);
</code>```

Now var_dump gives output

```<code>array(4) {
    [0]=> array(2) { ["id"]=> int(1) ["name"]=> string(3) "one" }
    [1]=> array(2) { ["id"]=> int(2) ["name"]=> string(3) "two" }
    [2]=> array(2) { ["id"]=> int(3) ["name"]=> string(5) "three" }
    [3]=> array(2) { ["id"]=> int(4) ["name"]=> string(4) "four" }
}
</code>```

Title: How to sort an array as per index value using PHP

Body:
use ksort(), which sorts an array by its keys.

So I created this dummy $test array
example:

array(4) {
    [0]=> array(2) { ["id"]=> int(1) ["name"]=> string(3) "one" }
    [3]=> array(2) { ["id"]=> int(4) ["name"]=> string(4) "four" }
    [1]=> array(2) { ["id"]=> int(2) ["name"]=> string(3) "two" }
    [2]=> array(2) { ["id"]=> int(3) ["name"]=> string(5) "three" }
}

next ksort() Sorts an array by key, maintaining key to data correlations.

ksort($test);

Now var_dump gives output

array(4) {
    [0]=> array(2) { ["id"]=> int(1) ["name"]=> string(3) "one" }
    [1]=> array(2) { ["id"]=> int(2) ["name"]=> string(3) "two" }
    [2]=> array(2) { ["id"]=> int(3) ["name"]=> string(5) "three" }
    [3]=> array(2) { ["id"]=> int(4) ["name"]=> string(4) "four" }
}


问:
Am using inspinia admin template and wanted to send http post request to web API. I have angular JS script and were to use it.?
I have the following Anguar Script. And where to use it. should I have to use in same page i.e., views/somefile.html or in any other controller? Am new to Angular JS and this template.</p>

```<code>$http({
    url: 'url-here',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    data: JSON.stringify(parameter)
}).success(function(data, status) {

    if (data.status == 'success') {
        $scope.succ = "success";
        var sessionid = data.doctor.doctor_id;

        $timeout(function() {
            $window.location.href = 'login?sessionid=' + sessionid + '';
        }, 1000);
    } else if (data.status == 'failure') {
        $scope.succ = "fail";
    }
});
</code>```

答:
Here is an example which might help you.
Keeping your code clean and reusable is most important. So always keep your common code at service layer.

// Using Angular 1

```<code>var app = angular.module("Demo", []);
app.controller("DemoController", ["$scope", "DemoService", "$window",    "$timeout", function($scope, DemoService, $window, $timeout){
    $scope.validateUser = function(){
        DemoService.userValidation($scope.user, $scope.validateUserSuccess, $scope.validateUserError);
    }

    $scope.validateUserSuccess = function(data){
        // Success Callback
        $scope.succ = "success";
        var sessionid = data.doctor.doctor_id;

        $timeout(function() {
            $window.location.href = 'login?sessionid=' + sessionid + '';
        }, 1000);
    };

    $scope.validateUserError = function(data){
        // Error Callback
        $scope.succ = "fail";
    };
}]);

app.service("DemoService", ["$http", function($http){
    this.userValidation = function(parameter, successCB, errorCB){
        $http({
            url: 'url-here',
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            data: JSON.stringify(parameter)
        }).success(function(data, status) {

           if (data.status == 'success') {
               successCB(data);
            } else if (data.status == 'failure') {
                errorCB(data);
           }

    });
};
}]);
</code>```

// Using Angular 2

```<code>            // parent.module.ts

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { HttpModule, JsonpModule } from '@angular/http';

    import { LandingComponent } from './view/landing.component';

    import { AdminService } from './service/admin.service';

    @NgModule({
      imports : [
        BrowserModule,
        HttpModule,
        JsonpModule
      ],
      declarations : [
        LoginComponent
      ],
      providers : [
        AdminService
      ],
      bootstrap : [ LandingComponent ]
    })
    export class ParentModule {}

    // admin.service.ts

    import { Injectable } from '@angular/core';
    import { Admin } from '../util/admin';
    import { Http, Headers } from '@angular/http';

    import 'rxjs/add/operator/toPromise';

    @Injectable()
    export class ValidateUser {
      adminObj = {};
      option = new Headers({
        "Content-Type": "application/json"
      });

      constructor (private http: Http) {}

      validateUser(user: any) : Promise<any> {
        return this.http.post("http://127.0.0.1:3002/users", JSON.stringify(user), {headers:this.option}).toPromise();
      }
    }

    // login.component.ts

    import { Component } from '@angular/core';
    import { AdminService } from '../../service/admin.service';
    import { Admin } from '../../util/admin';

    @Component({
      moduleId : module.id,
      templateUrl : "./login.component.html",
      styleUrls : ['./login.component.css']
    })
    export class LoginComponent {
      adminUser = {};

      constructor(
        private adminService : AdminService
      ){}

      validate() : void {
        this.adminService.validateUser(this.adminUser).then((success)=>{
            this.adminService.setAdminDetail(JSON.parse(success._body));
        }).catch((err)=>{
          alert("Invalid credential")
        });
      }
    }
</code>```

Body:
I have the following Anguar Script. And where to use it. should I have to use in same page i.e., views/somefile.html or in any other controller? Am new to Angular JS and this template.

$http({
    url: 'url-here',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    data: JSON.stringify(parameter)
}).success(function(data, status) {

    if (data.status == 'success') {
        $scope.succ = "success";
        var sessionid = data.doctor.doctor_id;

        $timeout(function() {
            $window.location.href = 'login?sessionid=' + sessionid + '';
        }, 1000);
    } else if (data.status == 'failure') {
        $scope.succ = "fail";
    }
});

Body:
Here is an example which might help you.
Keeping your code clean and reusable is most important. So always keep your common code at service layer.

// Using Angular 1

var app = angular.module("Demo", []);
app.controller("DemoController", ["$scope", "DemoService", "$window",    "$timeout", function($scope, DemoService, $window, $timeout){
    $scope.validateUser = function(){
        DemoService.userValidation($scope.user, $scope.validateUserSuccess, $scope.validateUserError);
    }

    $scope.validateUserSuccess = function(data){
        // Success Callback
        $scope.succ = "success";
        var sessionid = data.doctor.doctor_id;

        $timeout(function() {
            $window.location.href = 'login?sessionid=' + sessionid + '';
        }, 1000);
    };

    $scope.validateUserError = function(data){
        // Error Callback
        $scope.succ = "fail";
    };
}]);

app.service("DemoService", ["$http", function($http){
    this.userValidation = function(parameter, successCB, errorCB){
        $http({
            url: 'url-here',
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            data: JSON.stringify(parameter)
        }).success(function(data, status) {

           if (data.status == 'success') {
               successCB(data);
            } else if (data.status == 'failure') {
                errorCB(data);
           }

    });
};
}]);

// Using Angular 2

            // parent.module.ts

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { HttpModule, JsonpModule } from '@angular/http';

    import { LandingComponent } from './view/landing.component';

    import { AdminService } from './service/admin.service';

    @NgModule({
      imports : [
        BrowserModule,
        HttpModule,
        JsonpModule
      ],
      declarations : [
        LoginComponent
      ],
      providers : [
        AdminService
      ],
      bootstrap : [ LandingComponent ]
    })
    export class ParentModule {}

    // admin.service.ts

    import { Injectable } from '@angular/core';
    import { Admin } from '../util/admin';
    import { Http, Headers } from '@angular/http';

    import 'rxjs/add/operator/toPromise';

    @Injectable()
    export class ValidateUser {
      adminObj = {};
      option = new Headers({
        "Content-Type": "application/json"
      });

      constructor (private http: Http) {}

      validateUser(user: any) : Promise<any> {
        return this.http.post("http://127.0.0.1:3002/users", JSON.stringify(user), {headers:this.option}).toPromise();
      }
    }

    // login.component.ts

    import { Component } from '@angular/core';
    import { AdminService } from '../../service/admin.service';
    import { Admin } from '../../util/admin';

    @Component({
      moduleId : module.id,
      templateUrl : "./login.component.html",
      styleUrls : ['./login.component.css']
    })
    export class LoginComponent {
      adminUser = {};

      constructor(
        private adminService : AdminService
      ){}

      validate() : void {
        this.adminService.validateUser(this.adminUser).then((success)=>{
            this.adminService.setAdminDetail(JSON.parse(success._body));
        }).catch((err)=>{
          alert("Invalid credential")
        });
      }
    }


问:
Passing data from one node express app to another in same/different domain
I need to pass some data from one node express app A to another B that may/may not run on the same domain. I want to do this using a 301 redirection. I learnt that you can do this by a connect-flash node module but it works only across the same app middleware. Any suggestions or reference would be helpful. Thanks.

```<code>// App A
var express = require('express');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var flash = require('connect-flash');
var app = express();

app.use(require('body-parser').json());
app.use(cookieParser('secret'));
app.use(session({cookie: { maxAge: 60000 }}));
app.use(flash());

app.post('/forceRedirect', function (req, res, next) {
    var dataRecieved = {
        requestHeaderVersion:req.get('version'),
        requestBodyParam:req.body.firstname,
        path:req.originalUrl
    };

    console.log('Data logging on node app A: ' +     JSON.stringify(dataRecieved));

    req.flash('testdata', 'it worked');
    return res.redirect(301, 'http://mydomain/test') // Pass to     app  B that is on different domain

})

app.listen(3000, function () {
  console.log('Node 1 listening on port 3000!')
})
</code>```

```<code>//App B - running on different domain

var express = require('express')
var session = require('express-session');
var cookieParser = require('cookie-parser');
var flash = require('connect-flash');
var app = express()

app.use(require('body-parser').json());
app.use(cookieParser('secret'));
app.use(session({cookie: { maxAge: 60000 }}));
app.use(flash());

app.get('/test', function (req, res) {
  console.log('Node app B is hit! and recieved data from node app A is :' + JSON.stringify(req.flash('testdata')));
  res.end();
})

app.listen(4000, function () {
  console.log('Node app 2 listening on port 4000!')
})
</code>```

答:
One way of doing this would be if you really want a 301,

//APP A

```<code> return res.redirect(301, 'http://mydomain/test/data1/data2')
</code>```

//APP B

```<code>app.get('test/:data1/:data2', function (req, res) {
    console.log(req.params.data1);
    console.log(req.params.data1);
</code>```

});

EDIT

A better way would be

```<code>res.redirect(307, 'http://mydomain/test');
</code>```

This will redirect the orginal content of the POST to another POST presumably in APP B.

Body:
I need to pass some data from one node express app A to another B that may/may not run on the same domain. I want to do this using a 301 redirection. I learnt that you can do this by a connect-flash node module but it works only across the same app middleware. Any suggestions or reference would be helpful. Thanks.

// App A
var express = require('express');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var flash = require('connect-flash');
var app = express();

app.use(require('body-parser').json());
app.use(cookieParser('secret'));
app.use(session({cookie: { maxAge: 60000 }}));
app.use(flash());

app.post('/forceRedirect', function (req, res, next) {
    var dataRecieved = {
        requestHeaderVersion:req.get('version'),
        requestBodyParam:req.body.firstname,
        path:req.originalUrl
    };

    console.log('Data logging on node app A: ' +     JSON.stringify(dataRecieved));

    req.flash('testdata', 'it worked');
    return res.redirect(301, 'http://mydomain/test') // Pass to     app  B that is on different domain

})

app.listen(3000, function () {
  console.log('Node 1 listening on port 3000!')
})

//App B - running on different domain

var express = require('express')
var session = require('express-session');
var cookieParser = require('cookie-parser');
var flash = require('connect-flash');
var app = express()

app.use(require('body-parser').json());
app.use(cookieParser('secret'));
app.use(session({cookie: { maxAge: 60000 }}));
app.use(flash());

app.get('/test', function (req, res) {
  console.log('Node app B is hit! and recieved data from node app A is :' + JSON.stringify(req.flash('testdata')));
  res.end();
})

app.listen(4000, function () {
  console.log('Node app 2 listening on port 4000!')
})

Body:
One way of doing this would be if you really want a 301,

//APP A

 return res.redirect(301, 'http://mydomain/test/data1/data2')

//APP B

app.get('test/:data1/:data2', function (req, res) {
    console.log(req.params.data1);
    console.log(req.params.data1);

});

EDIT

A better way would be

res.redirect(307, 'http://mydomain/test');

This will redirect the orginal content of the POST to another POST presumably in APP B.


问:
Process Uploaded file on web server without storing locally first?
I am trying to process the user uploaded file real time on the websever,
but it seems, APACHE invokes PHP, only once complete file is uploaded.

When i uploaded the file using CURL, and set

Transfer-Encoding : "Chunked"

I had some success, but can't do same thing via browser.

I used Dropzone.js but when i tried to set same header, it said Transfer -Encoding is an unsafe header, hence not setting it.

This answer explains what is the issue there.
Can't set Transfer-Encoding :"Chunked from Browser"

In a Nutshell problem is , when a user uploads the file to webserver, i want webserver to start processing it as soon as first byte is available.
by process i mean, PIPING it to a Named Pipe.

Dont want 500mb first getting uploaded to a server, then start processing it.

But with current Webserver (APACHE - PHP), I cant seem to be able to accomplish it.

could someone please explain, what technology stack or workarounds to use, so that i can upload the large file via browser and start processing it, as soon as first byte is available.

答:
It is possible to use NodeJS/Multiparty to do that. Here they have an example of a direct upload to Amazon S3. This is the form, which sets content type to multipart/form-data. And here is the function for form parts processing. part parameter is of type ReadableStream, which will allow per-chunk processing of the input using data event.

More on readable streams in node js is here.


问:
How to pass coefficient derived from lm from train to test?
I have devided my dataset to 2 parts (Train 80% and Test 20%)

```<code>randomData<-  head(diamonds,n=length(diamonds$price)*0.8)
test      <-  tail(diamonds,n=length(diamonds$price)*0.2)
</code>```

Then i tried to train a linear model with train data

```<code>res<-lm(price ~carat+cut+color+clarity+depth+table+x+y+z,data=randomData) #Train
</code>```

But then i need to apply the coefficients which come from train part to the test
,but i have no idea how i can do it?

it seems that i should somehow pass res$coefficients  to lm and apply the test as my data

答:
"train" and "test" are just machine learning jargon for "fit" and "predict". You've done the fit, now predict:</p>

```<code>predict(res,newdata=test)
</code>```

Body:
I have devided my dataset to 2 parts (Train 80% and Test 20%)

randomData<-  head(diamonds,n=length(diamonds$price)*0.8)
test      <-  tail(diamonds,n=length(diamonds$price)*0.2)

Then i tried to train a linear model with train data

res<-lm(price ~carat+cut+color+clarity+depth+table+x+y+z,data=randomData) #Train

But then i need to apply the coefficients which come from train part to the test
,but i have no idea how i can do it?

it seems that i should somehow pass res$coefficients  to lm and apply the test as my data

Body:
"train" and "test" are just machine learning jargon for "fit" and "predict". You've done the fit, now predict:

predict(res,newdata=test)


问:
using javascript/jQuery to show certain elements on certain dates?
Pretty much as the title. I have been asked if it is possible to have a specific banner shown in a section on a website on different days without any external user input.

My first thoughts are the use of javascript/jquery. We are limited with the functionality however as the site is controlled by the horror that is Netsuite.

Any help/ideas are appreciated :)

-Wayne

答:
```<code>var now = new Date();
var date = now.getMonth() + "-" + now.getDay();
switch(date) {
  case "04-01":
    $('<p>APRIL FOOLS!</p>').appendTo("body");
    break;
  case "01-01":
    $('<p>Happy New Year!</p>').appendTo("body");
    break;
}
</code>```


问:
My recursive function not properly remove all children
This code remove all container's children, and set every children = null to free the memory. The structure of myElement is not always the same, so i would like a dynamic thing.

```<code>var cont1 = myElement.children.length;
for(var i = cont1 - 1 ; i >= 0 ; i--){
    var cont2 = myElement.children[i].children.length;
    for (var j = cont2 - 1; j >= 0; j--) {
        var cont3 = myElement.children[i].children[j].children.length;
        for (var k = cont3 - 1; k >= 0; k--) {
            var cont4 = myElement.children[i].children[j].children[k].children.length;
            for (var w = cont4 - 1; w >= 0; w--) {
                myElement.children[i].children[j].children[k].remove(myElement.children[i].children[j].children[k].children[w]);
                myElement.children[i].children[j].children[k].children[w] = null;
            }
            myElement.children[i].children[j].remove(myElement.children[i].children[j].children[k]);
            myElement.children[i].children[j].children[k] = null;
        }
        myElement.children[i].remove(myElement.children[i].children[j]);
        myElement.children[i].children[j] = null;
    }
    myElement.remove(myElement.children[i]); //i loop
    myElement.children[i] = null; //i loop
}
</code>```

This is my recursive test function.
Seems to work only in part. The first level is not deleted , it would be the i loop of the old code. How i can remove also that level of children?

```<code>function deleteRecursive(element){
    if(element.children.length > 0){
        for(var i = element.children.length - 1 ; i >= 0 ; i--){
            if(element.children[i].children.length > 0){
                deleteRecursive(element.children[i]);
            }else{
                element.remove(element.children[i]);
                element.children[i] = null;
            }
        }
    }
}
</code>```

答:
You should call remove also after you come back from the recursive call.

NB: the first if is not necessary, as this condition is already checked by the for loop. And you can remove the similar check that you do before calling the function recursively, as again the recursive call will check it in its for loop:

```<code>function deleteRecursive(element){
    for(var i = element.children.length - 1 ; i >= 0 ; i--){
        deleteRecursive(element.children[i]);
        element.remove(element.children[i]);
    }
}
</code>```

Body:
This code remove all container's children, and set every children = null to free the memory. The structure of myElement is not always the same, so i would like a dynamic thing.

var cont1 = myElement.children.length;
for(var i = cont1 - 1 ; i >= 0 ; i--){
    var cont2 = myElement.children[i].children.length;
    for (var j = cont2 - 1; j >= 0; j--) {
        var cont3 = myElement.children[i].children[j].children.length;
        for (var k = cont3 - 1; k >= 0; k--) {
            var cont4 = myElement.children[i].children[j].children[k].children.length;
            for (var w = cont4 - 1; w >= 0; w--) {
                myElement.children[i].children[j].children[k].remove(myElement.children[i].children[j].children[k].children[w]);
                myElement.children[i].children[j].children[k].children[w] = null;
            }
            myElement.children[i].children[j].remove(myElement.children[i].children[j].children[k]);
            myElement.children[i].children[j].children[k] = null;
        }
        myElement.children[i].remove(myElement.children[i].children[j]);
        myElement.children[i].children[j] = null;
    }
    myElement.remove(myElement.children[i]); //i loop
    myElement.children[i] = null; //i loop
}

This is my recursive test function.
Seems to work only in part. The first level is not deleted , it would be the i loop of the old code. How i can remove also that level of children?

function deleteRecursive(element){
    if(element.children.length > 0){
        for(var i = element.children.length - 1 ; i >= 0 ; i--){
            if(element.children[i].children.length > 0){
                deleteRecursive(element.children[i]);
            }else{
                element.remove(element.children[i]);
                element.children[i] = null;
            }
        }
    }
}

Body:
You should call remove also after you come back from the recursive call.

NB: the first if is not necessary, as this condition is already checked by the for loop. And you can remove the similar check that you do before calling the function recursively, as again the recursive call will check it in its for loop:

function deleteRecursive(element){
    for(var i = element.children.length - 1 ; i >= 0 ; i--){
        deleteRecursive(element.children[i]);
        element.remove(element.children[i]);
    }
}


问:
How to differentiate between text and number in scanned text?
I am using Microsoft Cognitive Services Computer Vision Api as an OCR service to read food menus.

I am able to scan the menu successfully but now i am want to save the dish name part and price part in two different arrays.

The result now after scanning is totally devastated because of special characters like rupee sign,parenthesis,menu-number.

I just want the dish name and price without rupee sign.
Can someone tell me how could I achieve that?
Here is github link and some code that could help you in assisting me:

```<code>@Override
    protected void onPostExecute(String data) {
        super.onPostExecute(data);
        // Display based on error existence

        if (e != null) {
            mEditText.setText("Error: " + e.getMessage());
            this.e = null;
        } else {
            Gson gson = new Gson();
            OCR r = gson.fromJson(data, OCR.class);

            String result = "";
            for (Region reg : r.regions) {
                for (Line line : reg.lines) {
                    for (Word word : line.words) {
                        result += word.text + " ";
                    }
                    result += "\n";
                }
                result += "\n\n";
            }

            mEditText.setText(result);
        }
        mButtonSelectImage.setEnabled(true);
    }
</code>```

What I want is:

1) I don't want any of these special characters in result.

2) I want to save the dish name and price in two different arrays.

Here are the screen shots of the output and the menu.

答:
I found the answer, thanks for your help guys!!

I obtained only characters by using this regex:

```<code>resultString = result.replaceAll("\\P{L}", " ");
</code>```

and only numbers using this regex:

```<code>resultNumber = result.replaceAll("[^\\d.]", "");
</code>```

Body:
I am using Microsoft Cognitive Services Computer Vision Api as an OCR service to read food menus.

I am able to scan the menu successfully but now i am want to save the dish name part and price part in two different arrays.

The result now after scanning is totally devastated because of special characters like rupee sign,parenthesis,menu-number.

I just want the dish name and price without rupee sign.
Can someone tell me how could I achieve that?
Here is github link and some code that could help you in assisting me:

@Override
    protected void onPostExecute(String data) {
        super.onPostExecute(data);
        // Display based on error existence

        if (e != null) {
            mEditText.setText("Error: " + e.getMessage());
            this.e = null;
        } else {
            Gson gson = new Gson();
            OCR r = gson.fromJson(data, OCR.class);

            String result = "";
            for (Region reg : r.regions) {
                for (Line line : reg.lines) {
                    for (Word word : line.words) {
                        result += word.text + " ";
                    }
                    result += "\n";
                }
                result += "\n\n";
            }

            mEditText.setText(result);
        }
        mButtonSelectImage.setEnabled(true);
    }

What I want is:

1) I don't want any of these special characters in result.

2) I want to save the dish name and price in two different arrays.

Here are the screen shots of the output and the menu.

Body:
I found the answer, thanks for your help guys!!

I obtained only characters by using this regex:

resultString = result.replaceAll("\\P{L}", " ");

and only numbers using this regex:

resultNumber = result.replaceAll("[^\\d.]", "");


问:
Can PL/pgSQL return a function from a function? Or even a set of functions?
Can I declare a PL/pgSQL function where the return type is a function?  Or even a set of functions?  Is there even a function type in the language?

I was noodling with the idea of a library of PL/pgSQL functions that could handle function chaining to make using the library easier.  Syntax akin to method dispatch isn't possible, but returning a function from a function should allow for some basic syntax magic.  Unfortunately I don't have enough of a mastery of PL/pgSQL yet to try to describe what I'm asking in a code example, I hope the question is clear enough as stated.

A variant of this question, Is SQL a functional language was asked 8 years ago, but my question is a little more specific (besides, the #1 answer on that question is incorrect!).

答:
You can create a function which returns set of references to the system catalog pg_proc, e.g.:

```<code>create or replace function get_function(name text)
returns setof regprocedure language plpgsql as $$
begin
    return query
    select oid::regprocedure
    from pg_proc
    where proname = name;
end $$;
</code>```

The above function can be used to extract information about functions with a given name, e.g.:

```<code>select get_function('get_function');

    get_function
--------------------
 get_function(text)
(1 row)

select get_function('regexp_split_to_table'); -- overloaded function

                     get_function
-------------------------------------------------------
 regexp_split_to_table(text,text)
 regexp_split_to_table(text,text,text)
(2 rows)
</code>```

It seems you could try to use this mechanism to dynamically execute retrieved functions in plpgsql code. It is not obvious however how to pass arguments in these calls. Probably it will not be without some text manipulations which may question the whole idea.

Body:
You can create a function which returns set of references to the system catalog pg_proc, e.g.:

create or replace function get_function(name text)
returns setof regprocedure language plpgsql as $$
begin
    return query
    select oid::regprocedure
    from pg_proc
    where proname = name;
end $$;

The above function can be used to extract information about functions with a given name, e.g.:

select get_function('get_function');

    get_function
--------------------
 get_function(text)
(1 row)

select get_function('regexp_split_to_table'); -- overloaded function

                     get_function
-------------------------------------------------------
 regexp_split_to_table(text,text)
 regexp_split_to_table(text,text,text)
(2 rows)

It seems you could try to use this mechanism to dynamically execute retrieved functions in plpgsql code. It is not obvious however how to pass arguments in these calls. Probably it will not be without some text manipulations which may question the whole idea.


问:
Create a CardView with a semicircle on top
I am very much into designing a login screen.

Something like this:

How Do I actually cut the card from the top so as to fill the drawable on top of it? Any help would be of great value.

[Source: https://www.uplabs.com/posts/login-android-app/]

答:
You can achieve almost similar by following:

Create a RelativeLayout as a container of CardView and ImageView

Set card_view:cardElevation="0dp" to show ImageView over CardView

On ImageView, set a transparent circle image for profile Icon.

FYI, If you want elevation for your CardView,
set CardView elevation ascard_view:cardElevation="4dp" and set ImageView elevation higher asandroid:elevation="8dp" to show ImageView over CardView.

Here is the fully working code. Try this:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#727272">

    <RelativeLayout
        android:id="@+id/card_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:layout_marginLeft="24dp"
        android:layout_marginRight="24dp"
        android:layout_centerInParent="true">

        <android.support.v7.widget.CardView
            android:id="@+id/card_login"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="50dp"
            android:foreground="?android:attr/selectableItemBackground"
            card_view:cardBackgroundColor="#ffffff"
            card_view:cardCornerRadius="4dp"
            card_view:cardElevation="0dp"
            card_view:cardUseCompatPadding="false" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:layout_marginTop="50dp"
                android:padding="24dp">

                <EditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="Login"/>

                <EditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="16dp"
                    android:hint="Password"
                    android:inputType="textPassword"/>

                <Button
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="16dp"
                    android:text="Sign In"
                    android:background="@android:color/holo_orange_light"/>

            </LinearLayout>
        </android.support.v7.widget.CardView>

        <ImageView
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:src="@drawable/icon_circular_profile"
            android:layout_centerHorizontal="true" />

    </RelativeLayout>
</RelativeLayout>
</code>```

OUTPUT:

ICON: I have used circular profile icon image from this link

Hope this will help~

Body:
You can achieve almost similar by following:

Create a RelativeLayout as a container of CardView and ImageView

Set card_view:cardElevation="0dp" to show ImageView over CardView

On ImageView, set a transparent circle image for profile Icon.

FYI, If you want elevation for your CardView,
set CardView elevation ascard_view:cardElevation="4dp" and set ImageView elevation higher asandroid:elevation="8dp" to show ImageView over CardView.

Here is the fully working code. Try this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#727272">

    <RelativeLayout
        android:id="@+id/card_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:layout_marginLeft="24dp"
        android:layout_marginRight="24dp"
        android:layout_centerInParent="true">

        <android.support.v7.widget.CardView
            android:id="@+id/card_login"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="50dp"
            android:foreground="?android:attr/selectableItemBackground"
            card_view:cardBackgroundColor="#ffffff"
            card_view:cardCornerRadius="4dp"
            card_view:cardElevation="0dp"
            card_view:cardUseCompatPadding="false" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:layout_marginTop="50dp"
                android:padding="24dp">

                <EditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="Login"/>

                <EditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="16dp"
                    android:hint="Password"
                    android:inputType="textPassword"/>

                <Button
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="16dp"
                    android:text="Sign In"
                    android:background="@android:color/holo_orange_light"/>

            </LinearLayout>
        </android.support.v7.widget.CardView>

        <ImageView
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:src="@drawable/icon_circular_profile"
            android:layout_centerHorizontal="true" />

    </RelativeLayout>
</RelativeLayout>

OUTPUT:

ICON: I have used circular profile icon image from this <a href="https://www.google.com/search?q=circular%20profile%20icon&client=ubuntu&hs=k7C&channel=fs&tbm=isch&imgil=MxudZ79j99TnyM%253A%253B7Ud9wXS6f7-agM%253Bhttp%25253A%25252F%25252Fcssdeck.com%25252Flabs%25252Fcss3icon%25252F&source=iu&pf=m&fir=MxudZ79j99TnyM%253A%252C7Ud9wXS6f7-agM%252C_&usg=__FE__ZjFu1mGmIcmnWGHtBGlP5qw%3D&biw=1535&bih=805&ved=0ahUKEwiupJOVjYDTAhUMqY8KHUiED34QyjcIPQ&ei=dfXdWO6VEYzSvgTIiL7wBw#imgrc=MxudZ79j99TnyM:" rel="nofollow noreferrer">link

Hope this will help~


问:
Swift TableView ProgressView indicator on multiple rows on single select
I have a tableview list that has a select action tied to it.  When the user selects the row, it gives them a prompt and begins to download a file and displays progress using a progressive indicator.  For some reason, the indicator is being displayed every 12 records from the selection.  Why is this happening... am I selecting the cell incorrectly?

Here is my code:

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = self.tableView.cellForRow(at: indexPath) as! downloadCell
    let cellName = CurrentFiles[indexPath.row].labelName
    let internalName = CurrentFiles[indexPath.row].internalName
    let fileLocation = CurrentFiles[indexPath.row].fileName
    let safeURL = fileLocation.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
    let fileExtension = CurrentFiles[indexPath.row].fileExtension
    let fileDate = CurrentFiles[indexPath.row].lastUpdate
    if (cell.progressView.isHidden) && (cell.fileStatus == "Installed") && (cell.fileIcon.image ==  nil) {
        let fileLoc = getSharedFilePath(appGroup:applicationGroup,sharedFilename:"\(internalName).\(fileExtension)")
        let defaults = UserDefaults.standard
        defaults.set(fileLoc, forKey: "loadmap")
        defaults.set(cellName, forKey: "loadmapName")
        performSegue(withIdentifier: "gotoMap", sender: self)
    } else if (cell.progressView.isHidden) {
        alertControllerMsg(msgStyle: UIAlertControllerStyle.alert,msgTitle: "Download File", msgBody: "Are you sure you want to download \(cellName)?", cancelLbl: "Cancel", actionLbl: "Download", complete: {
            cell.fileStatus = "Installed"      //prevent double download
            //download file
            let destination: (URL, HTTPURLResponse) -> (URL, DownloadRequest.DownloadOptions) = {
                (temporaryURL, response) in
                if let directoryURL = FileManager().containerURL(forSecurityApplicationGroupIdentifier: applicationGroup), let suggestedFilename = response.suggestedFilename {
                    let filePath = directoryURL.appendingPathComponent("\(suggestedFilename)")
                    return (filePath, [.removePreviousFile, .createIntermediateDirectories])
                }
                return (temporaryURL, [.removePreviousFile, .createIntermediateDirectories])
            }
            if self.reachability.isReachableViaWiFi {
                cell.progressView.isHidden = false
                //BackendAPI is used to allow for downloads in background
                BackendAPIManager.sharedInstance.alamoFireManager.download(safeURL!, to: destination)
                    .downloadProgress { progress in
                        cell.fileIcon.image =  nil
                        cell.progressView.setProgress(Float(progress.fractionCompleted), animated: true)
                        cell.pctLabel.text = "\(String(format:"%g",round(progress.fractionCompleted*100)))%"
                    }.response { response in
                        cell.pctLabel.text = nil
                        cell.progressView.isHidden = true
                        cell.additionalLbl.text = nil
                        UserDefaults(suiteName: applicationGroup)!.set(fileDate, forKey: internalName)
                        cell.fileStatus = "Installed"
                        self.getAvailSpace()
                }
            } else {
                self.alertControllerMsg(msgStyle: UIAlertControllerStyle.alert,msgTitle: "Insufficient Network", msgBody: "Please connect to a Wifi network to download this file.", cancelLbl: "Cancel", actionLbl: "Retry", complete: {
                    self.downloadAndSort()
                })
            }
        })
    }
}
</code>```

EDIT:

CellforRowAt code

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if let cell = tableView.dequeueReusableCell(withIdentifier: "downloadCell", for: indexPath) as? downloadCell {
        let currentFile = CurrentFiles[indexPath.row]
        cell.configureCell(currentFile: currentFile)
        return cell
    } else {
        return downloadCell()
    }
}
</code>```

EDIT 2:

```<code>class downloadCell: UITableViewCell {

@IBOutlet weak var fileLbl: UILabel!
@IBOutlet weak var fileIcon: UIImageView!
@IBOutlet weak var pctLabel: UILabel!
@IBOutlet weak var additionalLbl: UILabel!
@IBOutlet weak var fileSize: UILabel!
@IBOutlet weak var progressView: UIProgressView!

var fileStatus = "NotInstalled"
func configureCell(currentFile: currentFiles) {

    fileLbl.text = currentFile.labelName
    fileSize.text = currentFile.fileSize
    let internalName = currentFile.internalName
    fileIcon.image = UIImage(named: "download")
    additionalLbl.text = "Updated: \(convertDateFormatter(date: currentFile.lastUpdate))"

    let fileExists = (readFromSharedFile(sharedFilename: internalName, fileExtension: currentFile.fileExtension))
    if fileExists == "Success" {
        //file has been downloaded on device
        let lastUpdateDate = UserDefaults(suiteName: applicationGroup)!.string(forKey: internalName)

        if lastUpdateDate != currentFile.lastUpdate {
                fileIcon.image =  UIImage(named: "download")
                fileStatus = "NeedsUpdate"
            } else {
                fileIcon.image = nil
                fileStatus = "Installed"
                additionalLbl.text = nil
            }
    } else {
        // not on device
        fileStatus = "NotInstalled"

    }
}
}
</code>```

答: Tick the cell.progressview hidden flag to true in inspector builder either this. or you have to print and check your hidden status for progressview.</p>

Body:
I have a tableview list that has a select action tied to it.  When the user selects the row, it gives them a prompt and begins to download a file and displays progress using a progressive indicator.  For some reason, the indicator is being displayed every 12 records from the selection.  Why is this happening... am I selecting the cell incorrectly?

Here is my code:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = self.tableView.cellForRow(at: indexPath) as! downloadCell
    let cellName = CurrentFiles[indexPath.row].labelName
    let internalName = CurrentFiles[indexPath.row].internalName
    let fileLocation = CurrentFiles[indexPath.row].fileName
    let safeURL = fileLocation.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
    let fileExtension = CurrentFiles[indexPath.row].fileExtension
    let fileDate = CurrentFiles[indexPath.row].lastUpdate
    if (cell.progressView.isHidden) && (cell.fileStatus == "Installed") && (cell.fileIcon.image ==  nil) {
        let fileLoc = getSharedFilePath(appGroup:applicationGroup,sharedFilename:"\(internalName).\(fileExtension)")
        let defaults = UserDefaults.standard
        defaults.set(fileLoc, forKey: "loadmap")
        defaults.set(cellName, forKey: "loadmapName")
        performSegue(withIdentifier: "gotoMap", sender: self)
    } else if (cell.progressView.isHidden) {
        alertControllerMsg(msgStyle: UIAlertControllerStyle.alert,msgTitle: "Download File", msgBody: "Are you sure you want to download \(cellName)?", cancelLbl: "Cancel", actionLbl: "Download", complete: {
            cell.fileStatus = "Installed"      //prevent double download
            //download file
            let destination: (URL, HTTPURLResponse) -> (URL, DownloadRequest.DownloadOptions) = {
                (temporaryURL, response) in
                if let directoryURL = FileManager().containerURL(forSecurityApplicationGroupIdentifier: applicationGroup), let suggestedFilename = response.suggestedFilename {
                    let filePath = directoryURL.appendingPathComponent("\(suggestedFilename)")
                    return (filePath, [.removePreviousFile, .createIntermediateDirectories])
                }
                return (temporaryURL, [.removePreviousFile, .createIntermediateDirectories])
            }
            if self.reachability.isReachableViaWiFi {
                cell.progressView.isHidden = false
                //BackendAPI is used to allow for downloads in background
                BackendAPIManager.sharedInstance.alamoFireManager.download(safeURL!, to: destination)
                    .downloadProgress { progress in
                        cell.fileIcon.image =  nil
                        cell.progressView.setProgress(Float(progress.fractionCompleted), animated: true)
                        cell.pctLabel.text = "\(String(format:"%g",round(progress.fractionCompleted*100)))%"
                    }.response { response in
                        cell.pctLabel.text = nil
                        cell.progressView.isHidden = true
                        cell.additionalLbl.text = nil
                        UserDefaults(suiteName: applicationGroup)!.set(fileDate, forKey: internalName)
                        cell.fileStatus = "Installed"
                        self.getAvailSpace()
                }
            } else {
                self.alertControllerMsg(msgStyle: UIAlertControllerStyle.alert,msgTitle: "Insufficient Network", msgBody: "Please connect to a Wifi network to download this file.", cancelLbl: "Cancel", actionLbl: "Retry", complete: {
                    self.downloadAndSort()
                })
            }
        })
    }
}

EDIT:

CellforRowAt code

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if let cell = tableView.dequeueReusableCell(withIdentifier: "downloadCell", for: indexPath) as? downloadCell {
        let currentFile = CurrentFiles[indexPath.row]
        cell.configureCell(currentFile: currentFile)
        return cell
    } else {
        return downloadCell()
    }
}

EDIT 2:

class downloadCell: UITableViewCell {

@IBOutlet weak var fileLbl: UILabel!
@IBOutlet weak var fileIcon: UIImageView!
@IBOutlet weak var pctLabel: UILabel!
@IBOutlet weak var additionalLbl: UILabel!
@IBOutlet weak var fileSize: UILabel!
@IBOutlet weak var progressView: UIProgressView!

var fileStatus = "NotInstalled"
func configureCell(currentFile: currentFiles) {

    fileLbl.text = currentFile.labelName
    fileSize.text = currentFile.fileSize
    let internalName = currentFile.internalName
    fileIcon.image = UIImage(named: "download")
    additionalLbl.text = "Updated: \(convertDateFormatter(date: currentFile.lastUpdate))"

    let fileExists = (readFromSharedFile(sharedFilename: internalName, fileExtension: currentFile.fileExtension))
    if fileExists == "Success" {
        //file has been downloaded on device
        let lastUpdateDate = UserDefaults(suiteName: applicationGroup)!.string(forKey: internalName)

        if lastUpdateDate != currentFile.lastUpdate {
                fileIcon.image =  UIImage(named: "download")
                fileStatus = "NeedsUpdate"
            } else {
                fileIcon.image = nil
                fileStatus = "Installed"
                additionalLbl.text = nil
            }
    } else {
        // not on device
        fileStatus = "NotInstalled"

    }
}
}


问:
Including a VB project within a VC++ project
I'm looking for some help with a dependency issue.  In a nutshell, I've included a makefile project within a larger VC++ workspace, but the sub-project always rebuilds, even when it's not necessary.

The Details

I've inherited a large project that consists of several different modules, including a (primary) Visual C++ 6.0 executable and a smaller Visual Basic 6.0 DLL.

Today it's built manually, by launching each IDE and generating each component from its own environment.  I'd like to turn this into a one-click build from within the VC++ IDE.  (The end goal is to export the makefile, automate the entire process, and institute nightly builds.)

To this end, I've added a "Makefile" project to the VC++ workspace.  The makefile builds the VB DLL by invoking the VB compiler from a command line.

The problem is that the VB project always rebuilds itself, adding several minutes to the build process.  I suppose I could avoid this by adding all of the VB source files as dependencies, but this would likely turn into a maintenance problem, as it would require developers to update the VC++ workspace each time the VB component changes.

Is there a way to make the build process more selective, so VB runs only when the DLL needs to be rebuilt, short of adding every source file to the VC++ project as a dependency?

Thanks for your thoughts!

答:
You could do the dependency scan yourself.  Trigger the VB build only when any VB source file is newer than the build-output of the VB-build (where you can scan recursively using wild cards, i.e. no explicit configuration).  You may need to additionally care for the references the VB project uses.

This of course needs some manual make-file writing.  As VB6 seemingly does not support any dependency checking itself, I can't think of any purely IDE based solution (which does not require the double-bookkeeping you mentioned).

As you're just starting to implement nightly builds for a VB project, this seems to indicate that this project may be in development/maintenance for a longer time.  This longer time itself may be an indication to port the VB project to VB.NET, which improves the build process for VB projects by quite a good margin.

OwnerDisplayName: Adam Liss

OwnerDisplayName: gimpf