问:
Highlight text in idle python
I try to output a highlighted text in Python IDLE but I couldn't get the result just like I want. Anyway I'd tried in Python exe it is able to highlight the text.

```<code>>>> from lazyme.string import color_print
>>> color_print('abc', color='pink')
[95mabc[0m
</code>```

This is in python exe:

```<code>>>> from lazyme.string import color_print
>>> color_print('abc', color='pink')
abc
</code>```

Anybody please help me on this. Is there any possible solution to this matter?
Thank you. Cheers!

答:
Since IDLE shell isn't a terminal, it won't render the ANSI escape sequences.

So the result you got:

```<code>>>> from lazyme.string import color_print
>>> color_print('abc', color='pink')
[95mabc[0m
</code>```

though it is correct, it won't render the color for you.

Title: Highlight text in idle python

Body:
I try to output a highlighted text in Python IDLE but I couldn't get the result just like I want. Anyway I'd tried in Python exe it is able to highlight the text.

>>> from lazyme.string import color_print
>>> color_print('abc', color='pink')
[95mabc[0m

This is in python exe:

>>> from lazyme.string import color_print
>>> color_print('abc', color='pink')
abc

Anybody please help me on this. Is there any possible solution to this matter?
Thank you. Cheers!

Body:
Since IDLE shell isn't a terminal, it won't render the ANSI escape sequences.

So the result you got:

>>> from lazyme.string import color_print
>>> color_print('abc', color='pink')
[95mabc[0m

though it is correct, it won't render the color for you.


来源: stackexchange

问:
How to do a proper JOIN logic between 2 tables
Rather new to SQL.

I have 2 tables where I need to create an appropriate join between them.  Tables: Table1 and Table2.
Table1 has the following columns: Domain, Instance, Project, and Upload.
Table2 has the following columns: Domain, Instance, Project Derivation, Upload, and ID.

Ultimately I want to bring the ID column from Table2 into Table1.  However, Project and Project Derivation are not an exact match.  Rather the value of Project will be found somewhere in Project Derivation.

My thinking is the following:

```<code>Table1.Domain=Table2.Domain
Table1.Instance=Table2.Domain
Table1.Upload=Table2.Upload
</code>```

Table1.Project is in Table2.Project Derivation

Any help would be greatly appreciated.

Table 1

Table 2

答:
The join would include LIKE, so as to compare

```<code>WHERE 'Cloud, Cloud - Config' LIKE '%Cloud - Con%'
</code>```

The query:

```<code>SELECT *
FROM t1
JOIN t2 ON  t2.domain = t1.domain
        AND t2.instance = t1.instance
        AND t2.project_derivation like '%' || t1.project || '%';
</code>```

However, you would also find entries for a project 'Better Plans' when looking for a project called 'Bet' or 'Plan'. This is because your table design is not good. You are not using the relational database system properly. If parts of a string are of interest to your query, then store the parts separately.

Without knowing much of your data, I'd suggest in your case to have a project_derivation table containing one record per project derivation along with the related project. Then you would no longer be interested in substrings, but merely find the link from project derivation to project in this table.

There may be more flaws in your database design. Why do both tables share domain and instance? Does a project only have a meaning within the two (i.e. there can be a project Audit for Google.com/Dev and quite another project with the same name for Ebay.com/Dev)? This may be okay and you'd have a composite key then, but maybe you are merely storing data redundantly.

ContentLicense: CC BY-SA 3.0

Body:
Rather new to SQL.

I have 2 tables where I need to create an appropriate join between them.  Tables: Table1 and Table2.
Table1 has the following columns: Domain, Instance, Project, and Upload.
Table2 has the following columns: Domain, Instance, Project Derivation, Upload, and ID.

Ultimately I want to bring the ID column from Table2 into Table1.  However, Project and Project Derivation are not an exact match.  Rather the value of Project will be found somewhere in Project Derivation.

My thinking is the following:

Table1.Domain=Table2.Domain
Table1.Instance=Table2.Domain
Table1.Upload=Table2.Upload

Table1.Project is in Table2.Project Derivation

Any help would be greatly appreciated.

Table 1

Table 2

Body:
The join would include LIKE, so as to compare

WHERE 'Cloud, Cloud - Config' LIKE '%Cloud - Con%'

The query:

SELECT *
FROM t1
JOIN t2 ON  t2.domain = t1.domain
        AND t2.instance = t1.instance
        AND t2.project_derivation like '%' || t1.project || '%';

However, you would also find entries for a project 'Better Plans' when looking for a project called 'Bet' or 'Plan'. This is because your table design is not good. You are not using the relational database system properly. If parts of a string are of interest to your query, then store the parts separately.

Without knowing much of your data, I'd suggest in your case to have a project_derivation table containing one record per project derivation along with the related project. Then you would no longer be interested in substrings, but merely find the link from project derivation to project in this table.

There may be more flaws in your database design. Why do both tables share domain and instance? Does a project only have a meaning within the two (i.e. there can be a project Audit for Google.com/Dev and quite another project with the same name for Ebay.com/Dev)? This may be okay and you'd have a composite key then, but maybe you are merely storing data redundantly.


问:
I wanna make a textbox that can collect the answer and bind with search url
I am trying to create a textbox that can collect the answer and bind it with the search url.

My problems are that I can type in the text box, but it won't the script.

The error being displayed is:

Uncaught TypeError: document.getElementById is not a constructor

at myFunction (index.html:23)

at HTMLButtonElement.onclick (index.html:14)

Tested in Chrome and Maxthon 5

And Here is my Code
https://hastebin.com/uqelimudoc.xml

答:
Couldnt explain with the above comments,so rewriting again only the script function.</p>

```<code><script>
function myFunction() {
    var y = document.getElementById("myForm").elements[0].value;
    document.getElementById("version").innerHTML = y;
    var z = document.getElementById("version").innerHTML;

    //z will be in the form of string,converting it to number format
    if (Number(z) > 3.5) {
    document.getElementById("final").innerHTML = "You're Lastest Version.";
   } else {
    document.getElementById("final").innerHTML = "You're Outdated. Please Go Download Lastest.";
   }
}
</script>
</code>```

Body:
Couldnt explain with the above comments,so rewriting again only the script function.

<script>
function myFunction() {
    var y = document.getElementById("myForm").elements[0].value;
    document.getElementById("version").innerHTML = y;
    var z = document.getElementById("version").innerHTML;

    //z will be in the form of string,converting it to number format
    if (Number(z) > 3.5) {
    document.getElementById("final").innerHTML = "You're Lastest Version.";
   } else {
    document.getElementById("final").innerHTML = "You're Outdated. Please Go Download Lastest.";
   }
}
</script>


问:
Need help with a Windows batch script which should set val of var based on part of a file name
This is not a homework - who would have homework on batch scripting?
I need to automate something. Currently there is a hard-coded batch script meant to be run daily to get systems, and it needs to work in a dynamic fashion. All it needs as an input is a build number, which can be deduced from the name of the file located at ... say C:\DumpLocation\. I am not good at batch scripting, and looking for a batch Ninja. If it was up to me, I would code this up in Python myself, but I cannot expect others to install it just for this. PowerShell is also not available on every Windows computer, so batch script is the lowest common denominator.

This should help:
http://www.techsupportforum.com/microsoft-support/windows-xp-support/54848-set-variable-based-output-seach-string-batch.html

Here is what I want the script to do:

```<code>dirToLookAt = 'C:\DumpLocation\'
# In that location there should be a single file named
# Custom_SomethingBuild34567Client_12345.zip
# I want to extract the build number into a variable to this effect:
buildNumber = '34567'
# strings which surround the build number are fixed.
# If there is more than one zip file with a build number in it,
# I need to print a warning and pick the largest one.
# I can do the rest.
</code>```

The following should help as well:

http://www.computing.net/answers/programming/batch-string-substitution/12097.html

Please let me know if you have questions.

答:
Assuming that Custom_SomethingBuild and Client_12345.zip are constants, this should do the trick:

```<code>@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

REM Get a count of the files in the directory

set /a FileCount=0
for /f "tokens=* delims= " %%a in ('dir/s/b/a-d C:\DumpLocation') do (
set /a FileCount+=1
)

REM If the file count is greater than or equal to 2, warn the user
IF %FileCount% GTR 1 ECHO The total number of files in the directory is:  %FileCount%

REM If the file count is less than or equal to 0, pause and exit
IF %FileCount% LEQ 0 PAUSE & EXIT

:: For each build number, use that number if it is the largest number
:: In the loop, we'll strip out the assumed constants, leaving us with a build number.

SET Build=
SET /a BuildNum=0
FOR /F %%A IN ('DIR /P /B C:\DumpLocation') DO (
   SET Build=%%A
   SET Build=!Build:Custom_SomethingBuild=!
   SET Build=!Build:Client_12345.zip=!
   IF !Build! GTR !BuildNum! SET /a BuildNum=!Build!
)

ECHO The greatest build number in the directory is:  %BuildNum%

PAUSE
</code>```

ContentLicense: CC BY-SA 2.5

Body:
This is not a homework - who would have homework on batch scripting?
I need to automate something. Currently there is a hard-coded batch script meant to be run daily to get systems, and it needs to work in a dynamic fashion. All it needs as an input is a build number, which can be deduced from the name of the file located at ... say C:\DumpLocation\. I am not good at batch scripting, and looking for a batch Ninja. If it was up to me, I would code this up in Python myself, but I cannot expect others to install it just for this. PowerShell is also not available on every Windows computer, so batch script is the lowest common denominator.

This should help:
http://www.techsupportforum.com/microsoft-support/windows-xp-support/54848-set-variable-based-output-seach-string-batch.html

Here is what I want the script to do:

dirToLookAt = 'C:\DumpLocation\'
# In that location there should be a single file named
# Custom_SomethingBuild34567Client_12345.zip
# I want to extract the build number into a variable to this effect:
buildNumber = '34567'
# strings which surround the build number are fixed.
# If there is more than one zip file with a build number in it,
# I need to print a warning and pick the largest one.
# I can do the rest.

The following should help as well:

http://www.computing.net/answers/programming/batch-string-substitution/12097.html

Please let me know if you have questions.

Body:
Assuming that Custom_SomethingBuild and Client_12345.zip are constants, this should do the trick:

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

REM Get a count of the files in the directory

set /a FileCount=0
for /f "tokens=* delims= " %%a in ('dir/s/b/a-d C:\DumpLocation') do (
set /a FileCount+=1
)

REM If the file count is greater than or equal to 2, warn the user
IF %FileCount% GTR 1 ECHO The total number of files in the directory is:  %FileCount%

REM If the file count is less than or equal to 0, pause and exit
IF %FileCount% LEQ 0 PAUSE & EXIT

:: For each build number, use that number if it is the largest number
:: In the loop, we'll strip out the assumed constants, leaving us with a build number.

SET Build=
SET /a BuildNum=0
FOR /F %%A IN ('DIR /P /B C:\DumpLocation') DO (
   SET Build=%%A
   SET Build=!Build:Custom_SomethingBuild=!
   SET Build=!Build:Client_12345.zip=!
   IF !Build! GTR !BuildNum! SET /a BuildNum=!Build!
)

ECHO The greatest build number in the directory is:  %BuildNum%

PAUSE


问:
below is my code for ngtable pagination.in this my all data are loaded in one page only even i write count:3 and page:1
below is my code for ngtable pagination.

in this my all data are loaded in one page only even i write count:3 and page:1

how could i implement the pagination.

Here is what i have tried till now:

 var app=angular.module("app",["ngTable"]);
                app.controller("ctrl",["$scope","NgTableParams",function($scope,NgTableParams)
                    {
                   $scope.user=[
                           {name:"anuradha",age:21,college:"NSIT"},
                           {name:"ABV",age:22,college:"IIT"},
                           {name:"ABCD",age:23,college:"KIT"},
                           {name:"anuradha",age:24,college:"GIT"},
                           {name:"POOJA",age:25,college:"SIT"},
                           {name:"ABC",age:26,college:"NT"},
                           {name:"abc",age:12,college:"abcd"},
                           {name:"qwe",age:22,college:"opqr"},
                           {name:"rty",age:45,college:"stiu"},
                           {name:"uio",age:14,college:"abcfgh"},
                           {name:"pas",age:19,college:"mnop"},
                           {name:"dfg",age:16,college:"qrst"},
                           ];
                    $scope.table=new NgTableParams({page:1, count:3},{
                     counts: [],
                    total: $scope.user.length,

                    getData: function (params) {
                        return $scope.user.slice((params.page() - 1) *
                        params.count(), params.page() * params.count());
                       // console.log("user.length");
                     }});

                }]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ng-table/1.0.0/ng-table.js"></script>
<body ng-app="app" ng-controller="ctrl">
            <table ng-table="table" show-filter=true class="table table-bordered table-striped">
                <tr ng-repeat="u in user">
                    <td title="'NAME'" >{{u.name}} </td>
                    <td title="'AGE'">{{u.age}}</td>
                    <td title="'COLLEGE'">{{u.college}}</td>
                </tr>
            </table>
          </body></code>```

答:
Here is working example. You had some error in your js and you were using ngtableparams in wrong way.

var app = angular.module("app", ["ngTable"]);
app.controller("ctrl", ["$scope", "NgTableParams", function($scope, NgTableParams) {
  $scope.users = [{
      name: "Madhav Sai",
      age: 10,
      location: 'Nagpur'
    },
    {
      name: "Suresh Dasari",
      age: 30,
      location: 'Chennai'
    },
    {
      name: "Rohini Alavala",
      age: 29,
      location: 'Chennai'
    },
    {
      name: "Praveen Kumar",
      age: 25,
      location: 'Bangalore'
    },
    {
      name: "Sateesh Chandra",
      age: 27,
      location: 'Vizag'
    },
    {
      name: "Siva Prasad",
      age: 38,
      location: 'Nagpur'
    },
    {
      name: "Sudheer Rayana",
      age: 25,
      location: 'Kakinada'
    },
    {
      name: "Honey Yemineni",
      age: 7,
      location: 'Nagpur'
    },
    {
      name: "Mahendra Dasari",
      age: 22,
      location: 'Vijayawada'
    },
    {
      name: "Mahesh Dasari",
      age: 23,
      location: 'California'
    },
    {
      name: "Nagaraju Dasari",
      age: 34,
      location: 'Atlanta'
    },
    {
      name: "Gopi Krishna",
      age: 29,
      location: 'Repalle'
    },
    {
      name: "Sudheer Uppala",
      age: 19,
      location: 'Guntur'
    },
    {
      name: "Sushmita",
      age: 27,
      location: 'Vizag'
    }
  ];
  $scope.usersTable = new NgTableParams({
    page: 1,
    count: 5
  }, {
    counts: [5, 10, 20],
    total: $scope.users.length,
    dataset: $scope.users
  });
}]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ng-table/1.0.0/ng-table.js"></script>
<link rel="stylesheet" ; href="https://unpkg.com/ng-table@2.0.2/bundles/ng-table.min.css">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<body ng-app="app">
  <div ng-controller="ctrl">
    <table ng-table="usersTable" class="table table-condensed table-bordered table-striped">
      <tr ng-repeat="row in $data">
        <td data-title="'Name'">{{row.name}}</td>
        <td data-title="'Age'">{{row.age}}</td>
        <td data-title="'Location'">{{row.location}}</td>
      </tr>
    </table>
  </div>
</body></code>```

Body:
below is my code for ngtable pagination.

in this my all data are loaded in one page only even i write count:3 and page:1

how could i implement the pagination.

Here is what i have tried till now:

 var app=angular.module("app",["ngTable"]);
                app.controller("ctrl",["$scope","NgTableParams",function($scope,NgTableParams)
                    {
                   $scope.user=[
                           {name:"anuradha",age:21,college:"NSIT"},
                           {name:"ABV",age:22,college:"IIT"},
                           {name:"ABCD",age:23,college:"KIT"},
                           {name:"anuradha",age:24,college:"GIT"},
                           {name:"POOJA",age:25,college:"SIT"},
                           {name:"ABC",age:26,college:"NT"},
                           {name:"abc",age:12,college:"abcd"},
                           {name:"qwe",age:22,college:"opqr"},
                           {name:"rty",age:45,college:"stiu"},
                           {name:"uio",age:14,college:"abcfgh"},
                           {name:"pas",age:19,college:"mnop"},
                           {name:"dfg",age:16,college:"qrst"},
                           ];
                    $scope.table=new NgTableParams({page:1, count:3},{
                     counts: [],
                    total: $scope.user.length,

                    getData: function (params) {
                        return $scope.user.slice((params.page() - 1) *
                        params.count(), params.page() * params.count());
                       // console.log("user.length");
                     }});

                }]);

                    {{u.name}}
                    {{u.age}}
                    {{u.college}}

Body:
Here is working example. You had some error in your js and you were using ngtableparams in wrong way.

var app = angular.module("app", ["ngTable"]);
app.controller("ctrl", ["$scope", "NgTableParams", function($scope, NgTableParams) {
  $scope.users = [{
      name: "Madhav Sai",
      age: 10,
      location: 'Nagpur'
    },
    {
      name: "Suresh Dasari",
      age: 30,
      location: 'Chennai'
    },
    {
      name: "Rohini Alavala",
      age: 29,
      location: 'Chennai'
    },
    {
      name: "Praveen Kumar",
      age: 25,
      location: 'Bangalore'
    },
    {
      name: "Sateesh Chandra",
      age: 27,
      location: 'Vizag'
    },
    {
      name: "Siva Prasad",
      age: 38,
      location: 'Nagpur'
    },
    {
      name: "Sudheer Rayana",
      age: 25,
      location: 'Kakinada'
    },
    {
      name: "Honey Yemineni",
      age: 7,
      location: 'Nagpur'
    },
    {
      name: "Mahendra Dasari",
      age: 22,
      location: 'Vijayawada'
    },
    {
      name: "Mahesh Dasari",
      age: 23,
      location: 'California'
    },
    {
      name: "Nagaraju Dasari",
      age: 34,
      location: 'Atlanta'
    },
    {
      name: "Gopi Krishna",
      age: 29,
      location: 'Repalle'
    },
    {
      name: "Sudheer Uppala",
      age: 19,
      location: 'Guntur'
    },
    {
      name: "Sushmita",
      age: 27,
      location: 'Vizag'
    }
  ];
  $scope.usersTable = new NgTableParams({
    page: 1,
    count: 5
  }, {
    counts: [5, 10, 20],
    total: $scope.users.length,
    dataset: $scope.users
  });
}]);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ng-table/1.0.0/ng-table.js"></script>
<link rel="stylesheet" ; href="https://unpkg.com/ng-table@2.0.2/bundles/ng-table.min.css">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<body ng-app="app">
  <div ng-controller="ctrl">
    <table ng-table="usersTable" class="table table-condensed table-bordered table-striped">
      <tr ng-repeat="row in $data">
        <td data-title="'Name'">{{row.name}}</td>
        <td data-title="'Age'">{{row.age}}</td>
        <td data-title="'Location'">{{row.location}}</td>
      </tr>
    </table>
  </div>
</body>


问:
google map is not displaying with bootstrap

var map;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          zoom: 16,
          center: new google.maps.LatLng(18.511325, 73.820176),
          mapTypeId: 'roadmap'
        });

        var iconBase = 'img/contactus/';
        var icons = {
          info: {
            icon: iconBase + 'map.png'
          }
        };

        var features = [
          {
            position: new google.maps.LatLng(18.511325, 73.820176),
            type: 'info'
          }
        ];

        // Create markers.
        features.forEach(function(feature) {
          var marker = new google.maps.Marker({
            position: feature.position,
            icon: icons[feature.type].icon,
            map: map
          });
        });
      }```
<pre class="snippet-code-css lang-css prettyprint-override"><code> #map{
    margin-left: 20%;
    height:100;
  }</code>```

```

hello above code is for Google map, i am integrating Google map inside my project & display custom logo in it. but its not displaying map to me i am using bootstrap.but when click on inspect element & uncheck position:relative then my map is displaying but not in proper way it should look like.

答:
```<code>i hope it will works , just do in the below way, remove all inline css and
add a height: 500px;
<style>
  #map{
       margin-left: 20%;
       height:500px;
      }
 </style>
 <script>
   var map;
   function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      zoom: 16,
      center: new google.maps.LatLng(18.511325, 73.820176),
      mapTypeId: 'roadmap'
    });

    var iconBase = 'img/contactus/';
    var icons = {
      info: {
        icon: iconBase + 'map.png'
      }
    };

    var features = [
      {
        position: new google.maps.LatLng(18.511325, 73.820176),
        type: 'info'
      }
    ];

    // Create markers.
    features.forEach(function(feature) {
      var marker = new google.maps.Marker({
        position: feature.position,
        icon: icons[feature.type].icon,
        map: map
      });
    });
  }
 </script>
  <script async defer
  src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA9rik1af5EY8G-
  fO6KNukN0-ROACLhAPg&callback=initMap">
  </script>

  <div id="map" class="map"></div>
</code>```

Body:
var map;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          zoom: 16,
          center: new google.maps.LatLng(18.511325, 73.820176),
          mapTypeId: 'roadmap'
        });

        var iconBase = 'img/contactus/';
        var icons = {
          info: {
            icon: iconBase + 'map.png'
          }
        };

        var features = [
          {
            position: new google.maps.LatLng(18.511325, 73.820176),
            type: 'info'
          }
        ];

        // Create markers.
        features.forEach(function(feature) {
          var marker = new google.maps.Marker({
            position: feature.position,
            icon: icons[feature.type].icon,
            map: map
          });
        });
      }

 #map{
    margin-left: 20%;
    height:100;
  }

hello above code is for Google map, i am integrating Google map inside my project & display custom logo in it. but its not displaying map to me i am using bootstrap.but when click on inspect element & uncheck position:relative then my map is displaying but not in proper way it should look like.


问:
How count common elements for every combination of rows in a matrix?
I am trying to count the common elements among each combination of rows in a dataset. I manage to do it with a nested loop which works fine for a small dataset but for the real one (1380*1380 combinations) takes too long. I wonder if there is a straightforward and less computation intensive way to do it.

```<code>a <- c(1,5,6,8,9)
b <- c(4,3,6,8,2)
c <- c(4,3,6,1,9)
df <- rbind(a,b,c)
</code>```

Result should look like this

```<code>data.frame(p1= c('a','a','a','b','b','b','c','c','c'),
           p2= c('a','b','c','a','b','c','a','b','c'),
           res= c(5,2,2,2,5,3,2,3,5))
</code>```

If it takes out comparisons between self would be even better.
Thank you very much for your help!

答:
If you don't need the same rows to be compared (i.e. a with a), then combn can work as follows,

```<code>combn(1:nrow(df), 2, FUN = function(i) sum(df[i[1],] - df[i[2],]==0))
#[1] 2 2 3

# or add the names of combinations as well,

setNames(combn(1:3, 2, FUN = function(i) sum(df[i[1],] - df[i[2],]==0)),
         combn(rownames(df), 2, toString))
#a, b a, c b, c
#   2    2    3
</code>```

Body:
I am trying to count the common elements among each combination of rows in a dataset. I manage to do it with a nested loop which works fine for a small dataset but for the real one (1380*1380 combinations) takes too long. I wonder if there is a straightforward and less computation intensive way to do it.

a <- c(1,5,6,8,9)
b <- c(4,3,6,8,2)
c <- c(4,3,6,1,9)
df <- rbind(a,b,c)

Result should look like this

data.frame(p1= c('a','a','a','b','b','b','c','c','c'),
           p2= c('a','b','c','a','b','c','a','b','c'),
           res= c(5,2,2,2,5,3,2,3,5))

If it takes out comparisons between self would be even better.
Thank you very much for your help!

Body:
If you don't need the same rows to be compared (i.e. a with a), then combn can work as follows,

combn(1:nrow(df), 2, FUN = function(i) sum(df[i[1],] - df[i[2],]==0))
#[1] 2 2 3

# or add the names of combinations as well,

setNames(combn(1:3, 2, FUN = function(i) sum(df[i[1],] - df[i[2],]==0)),
         combn(rownames(df), 2, toString))
#a, b a, c b, c
#   2    2    3


问:
How to create a table with 3 columns in iOS App?(Objective C)

Want to create a table as shown in the image in iOS Xcode

Unable to remove space between cells Using Collection view as in the image below:

enter image description here

答:
Using Tableview:</p>

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   static NSString *CellIdentifier = @"Cell";
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

   UILabel *labelData1 = ...;
   labelData1.text = @"333";
   UILabel *labelData2 = ...;
   labelData2.text = @"56";
   UILabel *labelData3 = ...;
   labelData3.text = @"12";

   UILabel *label1 = ...;
   label1.text = @"Questions";
   UILabel *label2 = ...;
   label2.text = @"Sections";
   UILabel *label3 = ...;
   label3.text = @"Exams";

   return cell;

}
</code>```

Body:
Using Tableview:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   static NSString *CellIdentifier = @"Cell";
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

   UILabel *labelData1 = ...;
   labelData1.text = @"333";
   UILabel *labelData2 = ...;
   labelData2.text = @"56";
   UILabel *labelData3 = ...;
   labelData3.text = @"12";

   UILabel *label1 = ...;
   label1.text = @"Questions";
   UILabel *label2 = ...;
   label2.text = @"Sections";
   UILabel *label3 = ...;
   label3.text = @"Exams";

   return cell;

}


问:
Is it possible to get Homebrew to install from the latest commit on GitHub?
I need to use the LFTP program for a script I run. I tried installing it from the website using the instructions in the downloaded folder's "INSTALL" file, but running config always failed. So, I tried to have Homebrew install it, and that worked great.

I have no idea where Homebrew fetches its source from, but the latest version it pulled has a bug which the developer has since fixed on GitHub. Is there a way I can get Homebrew to install the source from the latest commit?

答:
Some packages, such as numpy have a --HEAD option.

```<code>--HEAD
    Install HEAD version
</code>```

but the lftp package doesn't have this option. One solution could be to implement it yourserlf:

```<code>brew edit lftp
</code>```

P.S. the homebrew version of lftp already include a patch:

```<code>https://raw.githubusercontent.com/macports/macports-ports/edf0ee1e2cf/devel/m4/files/secure_snprintf.patch
</code>```

it's maybe the same you are looking for. You can see how it's apply whit brew edit lftp.

Body:
Some packages, such as numpy have a --HEAD option.

--HEAD
    Install HEAD version

but the lftp package doesn't have this option. One solution could be to implement it yourserlf:

brew edit lftp

P.S. the homebrew version of lftp already include a patch:

https://raw.githubusercontent.com/macports/macports-ports/edf0ee1e2cf/devel/m4/files/secure_snprintf.patch

it's maybe the same you are looking for. You can see how it's apply whit brew edit lftp.


问:
Pandas average timestamp for DateFrame subset
I am really new of Pandas and I have a problem how to calculate the average value of a set of time.

I have a csv file with columns: Date, Time, Outside temperature

I imported and modify it as:

```<code>df = pd.read_csv("./file.csv", parse_dates=[0], dayfirst=True)
df["Date"] = pd.to_datetime(df["Date"])
df["Time"] = pd.to_datetime(df["Time"]).dt.time
</code>```

I prefer to have the date and time separate in two different columns and not use them as index.

I already extracted the part I need and obtaining something like this:

```<code>           Date      Time  Outside Temperature
4343 2006-06-30  13:00:00                 15.9
4344 2006-06-30  13:10:00                 15.9
4345 2006-06-30  13:20:00                 15.9
4346 2006-06-30  13:30:00                 15.9
4347 2006-06-30  13:40:00                 15.9
</code>```

as you can see at same temperature I have different time, I would like to have the average value of the time, something like: 13:22:34

How can I do it?

I checked other questions as: Average time for datetime list, I tried several way to access to the time, for example:

```<code>print(tempdf["Time"].dt.hour)
</code>```

but I obtain the error:

```<code>AttributeError: Can only use .dt accessor with datetimelike values
</code>```

I think I make a mistake in the conversion to timestamp.

Do you have any suggestion?

I am using python3.5 and pandas 0.20.2

Thanks a lot

Ciccio

Edit:

The original csv file for the time has the format hh:mm without the seconds.

答:
I think you can use timedelatas by to_timedelta, then convert to ns, get mean and convert back:

```<code>df = pd.read_csv("./file.csv", parse_dates=[0], dayfirst=True)

a = pd.to_timedelta(df["Time"] + ':00').mean()
print (a)
0 days 13:20:00
</code>```

```<code>a = pd.to_timedelta(pd.to_timedelta(df["Time"] + ':00').values.astype(np.int64).mean())
print (a)
0 days 13:20:00
</code>```

If need average time for each unique dates:

```<code>df['td']= pd.to_timedelta(df["Time"] + ':00').values.astype(np.int64)
df1 = pd.to_timedelta(df.groupby('Date')['td'].mean()).reset_index()
print (df1)
        Date       td
0 2006-06-30 13:20:00
</code>```

... or for unique temperature:

```<code>df['td']= pd.to_timedelta(df["Time"] + ':00').values.astype(np.int64)
df1 = pd.to_timedelta(df.groupby('Outside Temperature')['td'].mean()).reset_index()
print (df1)
   Outside Temperature       td
0                 15.9 13:20:00
</code>```

...or mean of temperature and times:

```<code>df['Time']= pd.to_timedelta(df["Time"]).values.astype(np.int64)
df1 = df.groupby('Date', as_index=False).mean()
df1['Time']= pd.to_timedelta(df1["Time"])
print (df1)
        Date     Time  Outside Temperature
0 2006-06-30 13:20:00                 15.9
</code>```

Body:
I am really new of Pandas and I have a problem how to calculate the average value of a set of time.

I have a csv file with columns: Date, Time, Outside temperature

I imported and modify it as:

df = pd.read_csv("./file.csv", parse_dates=[0], dayfirst=True)
df["Date"] = pd.to_datetime(df["Date"])
df["Time"] = pd.to_datetime(df["Time"]).dt.time

I prefer to have the date and time separate in two different columns and not use them as index.

I already extracted the part I need and obtaining something like this:

           Date      Time  Outside Temperature
4343 2006-06-30  13:00:00                 15.9
4344 2006-06-30  13:10:00                 15.9
4345 2006-06-30  13:20:00                 15.9
4346 2006-06-30  13:30:00                 15.9
4347 2006-06-30  13:40:00                 15.9

as you can see at same temperature I have different time, I would like to have the average value of the time, something like: 13:22:34

How can I do it?

I checked other questions as: Average time for datetime list, I tried several way to access to the time, for example:

print(tempdf["Time"].dt.hour)

but I obtain the error:

AttributeError: Can only use .dt accessor with datetimelike values

I think I make a mistake in the conversion to timestamp.

Do you have any suggestion?

I am using python3.5 and pandas 0.20.2

Thanks a lot

Ciccio

Edit:

The original csv file for the time has the format hh:mm without the seconds.

Body:
I think you can use timedelatas by to_timedelta, then convert to ns, get mean and convert back:

df = pd.read_csv("./file.csv", parse_dates=[0], dayfirst=True)

a = pd.to_timedelta(df["Time"] + ':00').mean()
print (a)
0 days 13:20:00

a = pd.to_timedelta(pd.to_timedelta(df["Time"] + ':00').values.astype(np.int64).mean())
print (a)
0 days 13:20:00

If need average time for each unique dates:

df['td']= pd.to_timedelta(df["Time"] + ':00').values.astype(np.int64)
df1 = pd.to_timedelta(df.groupby('Date')['td'].mean()).reset_index()
print (df1)
        Date       td
0 2006-06-30 13:20:00

... or for unique temperature:

df['td']= pd.to_timedelta(df["Time"] + ':00').values.astype(np.int64)
df1 = pd.to_timedelta(df.groupby('Outside Temperature')['td'].mean()).reset_index()
print (df1)
   Outside Temperature       td
0                 15.9 13:20:00

...or mean of temperature and times:

df['Time']= pd.to_timedelta(df["Time"]).values.astype(np.int64)
df1 = df.groupby('Date', as_index=False).mean()
df1['Time']= pd.to_timedelta(df1["Time"])
print (df1)
        Date     Time  Outside Temperature
0 2006-06-30 13:20:00                 15.9


问:
Android - How to differentiate between users who sign in and register from firebase signinintent builder?
How can I differentiate between users who sign in and register when using firebase signinintentbuilder? https://github.com/firebase/FirebaseUI-Android/blob/master/auth/src/main/java/com/firebase/ui/auth/AuthUI.java

A workaround for this is to store the user's UID when registering, but how can I store a UID if the user object is null when starting the signinintentbuilder?

This is the code that starts the signinintentbuilder : '

```<code>        if(FirebaseAuth.getInstance().getCurrentUser() == null) {
             // Start sign in/sign up activity
             startActivityForResult(
                AuthUI.getInstance()
                        .createSignInIntentBuilder()
                        .build(),
                SIGN_IN_REQUEST_CODE
           );
        } else {
        // User is already signed in. Therefore, display

        // a welcome Toast
        Toast.makeText(this,
                "Welcome " + FirebaseAuth.getInstance()
                        .getCurrentUser()
                        .getDisplayName(),
                Toast.LENGTH_LONG)
                .show();
    }'
</code>```

Highly appreciate anyone's advise right now!

答: Here is how I do it: When the firebase UI flow finishes I "register" the user in the firebase DB and when the user logs out and presses for example the "google sign in" I check if the current uid is present in the firebase db. If it is the action that was performed was a "login" if not it was a "register"</p>

Body:
How can I differentiate between users who sign in and register when using firebase signinintentbuilder? https://github.com/firebase/FirebaseUI-Android/blob/master/auth/src/main/java/com/firebase/ui/auth/AuthUI.java

A workaround for this is to store the user's UID when registering, but how can I store a UID if the user object is null when starting the signinintentbuilder?

This is the code that starts the signinintentbuilder : '

        if(FirebaseAuth.getInstance().getCurrentUser() == null) {
             // Start sign in/sign up activity
             startActivityForResult(
                AuthUI.getInstance()
                        .createSignInIntentBuilder()
                        .build(),
                SIGN_IN_REQUEST_CODE
           );
        } else {
        // User is already signed in. Therefore, display

        // a welcome Toast
        Toast.makeText(this,
                "Welcome " + FirebaseAuth.getInstance()
                        .getCurrentUser()
                        .getDisplayName(),
                Toast.LENGTH_LONG)
                .show();
    }'

Highly appreciate anyone's advise right now!


问:
I am trying to extract password-protected ZIP files using zip4j jar file but i am getting error for following
I am very new to Java and I am trying to extract password-protected ZIP file using java and I have written code for the same but I am getting error for few methods such as isEncrypted(), fileHeaderList(), extractFile(),
I searched for few related posts/issues but did not find the exact resolution.
Can anyone of you help me in this issue</p>

```<code> import java.util.ArrayList;
    import java.util.List;
    import java.util.zip.ZipFile;
    import net.lingala.zip4j.model.FileHeader;

    public class Extraction {
    public Extraction() {

            try {
                ZipFile zipFile = new ZipFile("C:\\Users\\rajesh\\Desktop\\ZipFile\\file1.zip");

                //Error for isEncrypted() "The method isEncrypted() is undefined for the type ZipFile"
                if (zipFile.isEncrypted()) {
                                        zipFile.setPassword("MYPASS!");
                }

                //The method getFileHeaders() is undefined for the type ZipFile
                List fileHeaderList = zipFile.getFileHeaders();

                                for (int i = 0; i < fileHeaderList.size(); i++) {
                    FileHeader fileHeader = (FileHeader)fileHeaderList.get(i);
        //The method extractFile(FileHeader, String) is undefined for the type ZipFile
zipFile.extractFile(fileHeader, "C:\\Users\\rajesh\\Desktop\\ZipFile");
                }

            } catch (Exception e) {
                System.out.println("Please Try Again");
            }

        }

        public static void main(String[] args) {
            new Extraction();

        }

    }
</code>```

答: You are importing java.util.zip.ZipFile, but it sounds like you want to use zip4j ZipFile class instead.  I'm not familiar with that library, but based on the docs online, I think you might want to import net.lingala.zip4j.core.ZipFile.

Body:
I am very new to Java and I am trying to extract password-protected ZIP file using java and I have written code for the same but I am getting error for few methods such as isEncrypted(), fileHeaderList(), extractFile(),
I searched for few related posts/issues but did not find the exact resolution.
Can anyone of you help me in this issue

 import java.util.ArrayList;
    import java.util.List;
    import java.util.zip.ZipFile;
    import net.lingala.zip4j.model.FileHeader;

    public class Extraction {
    public Extraction() {

            try {
                ZipFile zipFile = new ZipFile("C:\\Users\\rajesh\\Desktop\\ZipFile\\file1.zip");

                //Error for isEncrypted() "The method isEncrypted() is undefined for the type ZipFile"
                if (zipFile.isEncrypted()) {
                                        zipFile.setPassword("MYPASS!");
                }

                //The method getFileHeaders() is undefined for the type ZipFile
                List fileHeaderList = zipFile.getFileHeaders();

                                for (int i = 0; i < fileHeaderList.size(); i++) {
                    FileHeader fileHeader = (FileHeader)fileHeaderList.get(i);
        //The method extractFile(FileHeader, String) is undefined for the type ZipFile
zipFile.extractFile(fileHeader, "C:\\Users\\rajesh\\Desktop\\ZipFile");
                }

            } catch (Exception e) {
                System.out.println("Please Try Again");
            }

        }

        public static void main(String[] args) {
            new Extraction();

        }

    }


问:
Angular 2 | How to pass a model data into another model
How to pass a model data into another model

For Example i want to inject the model 2 modelUser to model 1 user..

model1.ts

```<code>export class model1{
  constructor(private user: modelUser;){}
}
</code>```

model2.ts

```<code>export class model2{
   constructor(public modelUser: string){}
}
</code>```

答:
Derived classes that contain constructor functions must call super() which will execute the constructor function on the base class.</p>

```<code>    export class model2{
  constructor(public modelUser: string){
    console.log(modelUser);
  }
}
export class model1 extends model2{

  constructor(public modelUser: string){
    super(modelUser);
    console.log(this.modelUser)
  }
}
let y=new model2('model2');
let x=new model1('model1');
</code>```

Body:
How to pass a model data into another model

For Example i want to inject the model 2 modelUser to model 1 user..

model1.ts

export class model1{
  constructor(private user: modelUser;){}
}

model2.ts

export class model2{
   constructor(public modelUser: string){}
}

Body:
Derived classes that contain constructor functions must call super() which will execute the constructor function on the base class.

    export class model2{
  constructor(public modelUser: string){
    console.log(modelUser);
  }
}
export class model1 extends model2{

  constructor(public modelUser: string){
    super(modelUser);
    console.log(this.modelUser)
  }
}
let y=new model2('model2');
let x=new model1('model1');


问:
How to access a resource from a java library packed into its own .jar
I have a library project with some resources that I would like to load and use.
I would be using this library in another project so I have to pack the resources into the .jar. This is how that's achieved:

```<code><resources>
    <resource>
        <directory>src/main/resources</directory>
    </resource>
</resources>
</code>```

The problem comes when trying to retrieve the file, I do:

```<code>String resourceName = "myTemplateResource.json";
URL url = MyClass.class.getClassLoader().getResource(resourceName);
</code>```

url is assigned a null value. It happens in the library's tests and in the dependant project. Any hint of what is missing?

Also tested using

```<code>MyClass.class.getResource("/myTemplateResourceName.json");
</code>```

and

```<code>MyClass.class.getClassLoader().getResource("src/main/resources/myTemplateResource.json");
</code>```

with the same result.

答:
There was something wrong with the filename that I was not able to find out. Renamed the file and now it's fine.

To answer my question:

First add the resource to the jar on the .pom file.

```<code><resources>
    <resource>
        <directory>src/main/resources</directory>
    </resource>
</resources>
</code>```

Then access your file.

```<code>URL url = MyClass.class.getClassLoader().getResource(resourceName);
</code>```

From there you can get an InputStream. As simple as it looks.

Body:
I have a library project with some resources that I would like to load and use.
I would be using this library in another project so I have to pack the resources into the .jar. This is how that's achieved:

<resources>
    <resource>
        <directory>src/main/resources</directory>
    </resource>
</resources>

The problem comes when trying to retrieve the file, I do:

String resourceName = "myTemplateResource.json";
URL url = MyClass.class.getClassLoader().getResource(resourceName);

url is assigned a null value. It happens in the library's tests and in the dependant project. Any hint of what is missing?

Also tested using

MyClass.class.getResource("/myTemplateResourceName.json");

and

MyClass.class.getClassLoader().getResource("src/main/resources/myTemplateResource.json");

with the same result.

Body:
There was something wrong with the filename that I was not able to find out. Renamed the file and now it's fine.

To answer my question:

First add the resource to the jar on the .pom file.

<resources>
    <resource>
        <directory>src/main/resources</directory>
    </resource>
</resources>

Then access your file.

URL url = MyClass.class.getClassLoader().getResource(resourceName);

From there you can get an InputStream. As simple as it looks.


问:
Could not load the image referenced from a nib in the bundle with identifier
I had got an iPad application.The ViewContrtoller.xib has got an UIImageView in it. The UIImage of the UIImageView is set through Interface Builder. When I run the application in simulator everything is fine. But when I am trying to run it in iPad the UIImage is not loaded. The message that I am getting is:

HexaPuzzle1.0[3259:207] Could not load the "start.png" image referenced from a nib in the bundle with identifier "com.yourcompany.HexaPuzzle1-0"
      2010-12-17 10:57:27.221 HexaPuzzle1.0[3259:207] HexaPuzzle loaded

Any help would be appreciated and will be a great help for me.

答:
The issue has been rectified.
Problem was with the image format. When the image has been edited and saved as PNG-24 everything goes fine.
The application now runs smoothly in simulator and device.

Thanks for all friends who suggested a solution and tried to helped me.

Regards,
Rupesh R Menon


问:
Post text on Facebook on button click
What I have is a 'random quote generator'. As the name suggests, it generates random quotes on button click. In this so called app of mine, I have a button that is supposed to post the 'generated quote'on the facebook wall. The same thing works smoothly in case of my twitter button whilst I am not able to do so in case of facebook.

```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
 background-color : white;
 border-radius : 5px;
}

.my-btn {
 color : white;
}

#twitter-btn, #fb-btn {
 width : 40px;
}</code>```

        <button type="button" class="btn btn-default my-btn bg-colour" id="twitter-btn"></button>
        <button type="button" class="btn btn-default my-btn bg-colour" id="fb-btn"></button>
        <button type="button" class="btn btn-default my-btn bg-colour pull-right" id="new-quote-btn">New Quote</button>

```

Following is my working example ..

https://codepen.io/iamrkcheers/pen/gRjoeZ

Instead of the "Say something about this .." text, I want my 'random quote'.
Anyway to do this ?!?
Anyhelp is appreciated.
Thank You.

答:
Try this method..</p>

```<code>using Facebook;

private string PostFacebookWall(string accessToken, string message) {
    var responsePost = "";
    try {
        //create the facebook account object
        var objFacebookClient = new FacebookClient(accessToken);
        var parameters = new Dictionary<string, object>();
        parameters["message"] = message;
        responsePost = objFacebookClient.Post("feed", parameters);
    }
    catch (Exception ex) {
        responsePost = "Facebook Posting Error Message: " + ex.Message;
    }
    return responsePost;
}
</code>```

Title: Post text on Facebook on button click

Body:
What I have is a 'random quote generator'. As the name suggests, it generates random quotes on button click. In this so called app of mine, I have a button that is supposed to post the 'generated quote'on the facebook wall. The same thing works smoothly in case of my twitter button whilst I am not able to do so in case of facebook.

.box {
 background-color : white;
 border-radius : 5px;
}

.my-btn {
 color : white;
}

#twitter-btn, #fb-btn {
 width : 40px;
}

        <button type="button" class="btn btn-default my-btn bg-colour" id="twitter-btn"></button>
        <button type="button" class="btn btn-default my-btn bg-colour" id="fb-btn"></button>
        <button type="button" class="btn btn-default my-btn bg-colour pull-right" id="new-quote-btn">New Quote</button>

Following is my working example ..

https://codepen.io/iamrkcheers/pen/gRjoeZ

Instead of the "Say something about this .." text, I want my 'random quote'.
Anyway to do this ?!?
Anyhelp is appreciated.
Thank You.

Body:
Try this method..

using Facebook;

private string PostFacebookWall(string accessToken, string message) {
    var responsePost = "";
    try {
        //create the facebook account object
        var objFacebookClient = new FacebookClient(accessToken);
        var parameters = new Dictionary<string, object>();
        parameters["message"] = message;
        responsePost = objFacebookClient.Post("feed", parameters);
    }
    catch (Exception ex) {
        responsePost = "Facebook Posting Error Message: " + ex.Message;
    }
    return responsePost;
}


问:
Negative dimension size caused by subtracting 3 from 1 for 'Conv2D'
I'm using Keras with Tensorflow as backend , here is my code:

```<code>import numpy as np
np.random.seed(1373)
import tensorflow as tf
tf.python.control_flow_ops = tf

import os
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.layers.convolutional import Convolution2D, MaxPooling2D
from keras.utils import np_utils

batch_size = 128
nb_classes = 10
nb_epoch = 12

img_rows, img_cols = 28, 28

nb_filters = 32

nb_pool = 2

nb_conv = 3

(X_train, y_train), (X_test, y_test) = mnist.load_data()

print(X_train.shape[0])

X_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols)
X_test = X_test.reshape(X_test.shape[0], 1, img_rows, img_cols)

X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255

print('X_train shape:', X_train.shape)
print(X_train.shape[0], 'train samples')
print(X_test.shape[0], 'test samples')

Y_train = np_utils.to_categorical(y_train, nb_classes)
Y_test = np_utils.to_categorical(y_test, nb_classes)

model = Sequential()

model.add(Convolution2D(nb_filters, nb_conv, nb_conv,
border_mode='valid',
input_shape=(1, img_rows, img_cols)))
model.add(Activation('relu'))
model.add(Convolution2D(nb_filters, nb_conv, nb_conv))
model.add(Activation('relu'))

model.add(MaxPooling2D(pool_size=(nb_pool, nb_pool)))
model.add(Dropout(0.25))

model.add(Flatten())
model.add(Dense(128))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(nb_classes))
model.add(Activation('softmax'))

model.compile(loss='categorical_crossentropy', optimizer='adadelta', metrics=["accuracy"])

model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch,
verbose=1, validation_data=(X_test, Y_test))

score = model.evaluate(X_test, Y_test, verbose=0)

print('Test score:', score[0])
print('Test accuracy:', score[1])
</code>```

and Trackback error:

```<code>Using TensorFlow backend.
60000
('X_train shape:', (60000, 1, 28, 28))
(60000, 'train samples')
(10000, 'test samples')
Traceback (most recent call last):
  File "mnist.py", line 154, in <module>
    input_shape=(1, img_rows, img_cols)))
  File "/usr/local/lib/python2.7/dist-packages/keras/models.py", line 276, in add
    layer.create_input_layer(batch_input_shape, input_dtype)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 370, in create_input_layer
    self(x)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 514, in __call__
    self.add_inbound_node(inbound_layers, node_indices, tensor_indices)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 572, in add_inbound_node
    Node.create_node(self, inbound_layers, node_indices, tensor_indices)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 149, in create_node
    output_tensors = to_list(outbound_layer.call(input_tensors[0], mask=input_masks[0]))
  File "/usr/local/lib/python2.7/dist-packages/keras/layers/convolutional.py", line 466, in call
    filter_shape=self.W_shape)
  File "/usr/local/lib/python2.7/dist-packages/keras/backend/tensorflow_backend.py", line 1579, in conv2d
    x = tf.nn.conv2d(x, kernel, strides, padding=padding)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_nn_ops.py", line 396, in conv2d
    data_format=data_format, name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/op_def_library.py", line 759, in apply_op
    op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2242, in create_op
    set_shapes_for_outputs(ret)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1617, in set_shapes_for_outputs
    shapes = shape_func(op)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1568, in call_with_requiring
    return call_cpp_shape_fn(op, require_shape_fn=True)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/common_shapes.py", line 610, in call_cpp_shape_fn
    debug_python_shape_fn, require_shape_fn)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/common_shapes.py", line 675, in _call_cpp_shape_fn_impl
    raise ValueError(err.message)
ValueError: Negative dimension size caused by subtracting 3 from 1 for 'Conv2D' (op: 'Conv2D') with input shapes: [?,1,28,28], [3,3,28,32].
</code>```

First I saw some answers that problem is with Tensorflow version so I upgrade Tensorflow to 0.12.0, but still exist , is that problem with network or I missing something, what should input_shape looks like?

Update
Here is ./keras/keras.json:

```<code>{
    "image_dim_ordering": "tf",
    "epsilon": 1e-07,
    "floatx": "float32",
    "backend": "tensorflow"
}
</code>```

答:
Just add this:</p>

```<code>from keras import backend as K
K.set_image_dim_ordering('th')
</code>```

Body:
I'm using Keras with Tensorflow as backend , here is my code:

import numpy as np
np.random.seed(1373)
import tensorflow as tf
tf.python.control_flow_ops = tf

import os
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.layers.convolutional import Convolution2D, MaxPooling2D
from keras.utils import np_utils

batch_size = 128
nb_classes = 10
nb_epoch = 12

img_rows, img_cols = 28, 28

nb_filters = 32

nb_pool = 2

nb_conv = 3

(X_train, y_train), (X_test, y_test) = mnist.load_data()

print(X_train.shape[0])

X_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols)
X_test = X_test.reshape(X_test.shape[0], 1, img_rows, img_cols)

X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255

print('X_train shape:', X_train.shape)
print(X_train.shape[0], 'train samples')
print(X_test.shape[0], 'test samples')

Y_train = np_utils.to_categorical(y_train, nb_classes)
Y_test = np_utils.to_categorical(y_test, nb_classes)

model = Sequential()

model.add(Convolution2D(nb_filters, nb_conv, nb_conv,
border_mode='valid',
input_shape=(1, img_rows, img_cols)))
model.add(Activation('relu'))
model.add(Convolution2D(nb_filters, nb_conv, nb_conv))
model.add(Activation('relu'))

model.add(MaxPooling2D(pool_size=(nb_pool, nb_pool)))
model.add(Dropout(0.25))

model.add(Flatten())
model.add(Dense(128))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(nb_classes))
model.add(Activation('softmax'))

model.compile(loss='categorical_crossentropy', optimizer='adadelta', metrics=["accuracy"])

model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch,
verbose=1, validation_data=(X_test, Y_test))

score = model.evaluate(X_test, Y_test, verbose=0)

print('Test score:', score[0])
print('Test accuracy:', score[1])

and Trackback error:

Using TensorFlow backend.
60000
('X_train shape:', (60000, 1, 28, 28))
(60000, 'train samples')
(10000, 'test samples')
Traceback (most recent call last):
  File "mnist.py", line 154, in <module>
    input_shape=(1, img_rows, img_cols)))
  File "/usr/local/lib/python2.7/dist-packages/keras/models.py", line 276, in add
    layer.create_input_layer(batch_input_shape, input_dtype)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 370, in create_input_layer
    self(x)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 514, in __call__
    self.add_inbound_node(inbound_layers, node_indices, tensor_indices)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 572, in add_inbound_node
    Node.create_node(self, inbound_layers, node_indices, tensor_indices)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 149, in create_node
    output_tensors = to_list(outbound_layer.call(input_tensors[0], mask=input_masks[0]))
  File "/usr/local/lib/python2.7/dist-packages/keras/layers/convolutional.py", line 466, in call
    filter_shape=self.W_shape)
  File "/usr/local/lib/python2.7/dist-packages/keras/backend/tensorflow_backend.py", line 1579, in conv2d
    x = tf.nn.conv2d(x, kernel, strides, padding=padding)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_nn_ops.py", line 396, in conv2d
    data_format=data_format, name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/op_def_library.py", line 759, in apply_op
    op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2242, in create_op
    set_shapes_for_outputs(ret)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1617, in set_shapes_for_outputs
    shapes = shape_func(op)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1568, in call_with_requiring
    return call_cpp_shape_fn(op, require_shape_fn=True)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/common_shapes.py", line 610, in call_cpp_shape_fn
    debug_python_shape_fn, require_shape_fn)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/common_shapes.py", line 675, in _call_cpp_shape_fn_impl
    raise ValueError(err.message)
ValueError: Negative dimension size caused by subtracting 3 from 1 for 'Conv2D' (op: 'Conv2D') with input shapes: [?,1,28,28], [3,3,28,32].

First I saw some answers that problem is with Tensorflow version so I upgrade Tensorflow to 0.12.0, but still exist , is that problem with network or I missing something, what should input_shape looks like?

Update
Here is ./keras/keras.json:

{
    "image_dim_ordering": "tf",
    "epsilon": 1e-07,
    "floatx": "float32",
    "backend": "tensorflow"
}

Body:
Just add this:

from keras import backend as K
K.set_image_dim_ordering('th')


问:
Why does `vagrant up` fail the "ifdown eth1" SSH test?
I recently destroyed my homestead box and then re-built. Ever since, I have been getting this error:

```<code>$ vagrant up
...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
==> default: Setting hostname...
==> default: Configuring and enabling network interfaces...
The following SSH command responded with a non-zero exit status.
Vagrant assumes that this means the command failed!

/sbin/ifdown eth1 2> /dev/null

Stdout from the command:

Stderr from the command:
</code>```

The error is a bit cryptic and I can't figure it out. I have re-installed vagrant/virtual-box and purged the config files, but the error persists.

Host: Ubuntu 16.04

Box: Homestead v0.5

答:
For me worked adding auto_config: false at the end of network configuration.

```<code>config.vm.network 'private_network', ip: '192.168.14.10', auto_config: false
</code>```

Body:
I recently destroyed my homestead box and then re-built. Ever since, I have been getting this error:

$ vagrant up
...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
==> default: Setting hostname...
==> default: Configuring and enabling network interfaces...
The following SSH command responded with a non-zero exit status.
Vagrant assumes that this means the command failed!

/sbin/ifdown eth1 2> /dev/null

Stdout from the command:

Stderr from the command:

The error is a bit cryptic and I can't figure it out. I have re-installed vagrant/virtual-box and purged the config files, but the error persists.

Host: Ubuntu 16.04

Box: Homestead v0.5

Body:
For me worked adding auto_config: false at the end of network configuration.

config.vm.network 'private_network', ip: '192.168.14.10', auto_config: false


问:
Simple NHibernate subquery - pulling my hair out
All I want to do is lookup a value and return it in a subquery

```<code>select
(select top 1 c.Type from ChangeTypes c where c.TypeID = r.ChangeType) as ChangeType,
COUNT(r.requestId) as RequestCount
from Request r
group by ChangeType
</code>```

I can't get this to work for the life of me...

Any help would be greatly appreciated!

答:
Try something similar to</p>

```<code>select
    (select c.Type
     from ChangeTypes c
     where c.Type.Id = r.ChangeType.Id) as rtypes,
    count(r.Requests) as rcount
from Request r
group by rtypes
</code>```

Body:
All I want to do is lookup a value and return it in a subquery

select
(select top 1 c.Type from ChangeTypes c where c.TypeID = r.ChangeType) as ChangeType,
COUNT(r.requestId) as RequestCount
from Request r
group by ChangeType

I can't get this to work for the life of me...

Any help would be greatly appreciated!

Body:
Try something similar to

select
    (select c.Type
     from ChangeTypes c
     where c.Type.Id = r.ChangeType.Id) as rtypes,
    count(r.Requests) as rcount
from Request r
group by rtypes


问:
Error deploying Angular4 to ghpages using angular-cli-ghpages
I am trying to deploy a simple Angular 4 app to gh-pages. I have tried several methods and it seems that angular-cli-ghpages is the most up to date way to do it.

I've followed the instructions on the npm angular-cli-ghpages page.

First I installed successfully angular-cli-ghpages,

```<code>$ sudo npm i -g angular-cli-ghpages
</code>```

This command wouldn't work without sudo.

Next I created the dist folder and set the base-href,

```<code>$ ng build --prod --base-href "https://shanegibney.github.io/mathapp/"
</code>```

Then I deployed with,

```<code>$ ngh
</code>```

but this gives errors,

The output can be seen in this image below,

Running angular-cli-ghpages instead of ngh produces the same error,

I am using the following versions,

npm 3.10.10

angular-cli-ghpages ^0.5.1

node 6.9.4 (not really an issue here)

Thanks

答:
I deployed Angular2 app to gh-pages at last week(Live).But I didn't use

angular-cli-ghpages page.

Used these dependencies -

@angular/cli": "^1.2.0

@angular/compiler-cli": "^2.3.1

Now need to build our project as minifiles css and js.
to do it just run this code in your angular project

```<code>ng build --prod--aot --base-href "https://username.github.io/repo-name/"
</code>```

If you have problem when compiling
replace this code in angular-cli.json file

```<code>"environments": {
  "source": "environments/environment.ts",
  "dev": "environments/environment.ts",
  "prod": "environments/environment.prod.ts"
}
</code>```

to

```<code>"environmentSource": "environments/environment.ts",
"environments": {
  "dev": "environments/environment.ts",
  "prod": "environments/environment.prod.ts"
}
</code>```

After successful compiled(100%)
just run this command to deploy to gh-pahes

```<code>ngh --message "Deploy gh pages"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to deploy a simple Angular 4 app to gh-pages. I have tried several methods and it seems that angular-cli-ghpages is the most up to date way to do it.

I've followed the instructions on the npm angular-cli-ghpages page.

First I installed successfully angular-cli-ghpages,

$ sudo npm i -g angular-cli-ghpages

This command wouldn't work without sudo.

Next I created the dist folder and set the base-href,

$ ng build --prod --base-href "https://shanegibney.github.io/mathapp/"

Then I deployed with,

$ ngh

but this gives errors,

The output can be seen in this image below,

Running angular-cli-ghpages instead of ngh produces the same error,

I am using the following versions,

npm 3.10.10

angular-cli-ghpages ^0.5.1

node 6.9.4 (not really an issue here)

Thanks

Body:
I deployed Angular2 app to gh-pages at last week(Live).But I didn't use

angular-cli-ghpages page.

Used these dependencies -

@angular/cli": "^1.2.0

@angular/compiler-cli": "^2.3.1

Now need to build our project as minifiles css and js.
to do it just run this code in your angular project

ng build --prod--aot --base-href "https://username.github.io/repo-name/"

If you have problem when compiling
replace this code in angular-cli.json file

"environments": {
  "source": "environments/environment.ts",
  "dev": "environments/environment.ts",
  "prod": "environments/environment.prod.ts"
}

to

"environmentSource": "environments/environment.ts",
"environments": {
  "dev": "environments/environment.ts",
  "prod": "environments/environment.prod.ts"
}

After successful compiled(100%)
just run this command to deploy to gh-pahes

ngh --message "Deploy gh pages"


问:
Why is "and" evaluated before "equal"
In Javascript precedence of strict equal (10) is greater than logical and (6) then how does this code works

var a;
console.log("value of a is", a);
if (a && a.test === "test") {}```

Should it not throw error

cannot read test of undefined.

And to add salt to the wound precedence of member access is higher than both of them (19).

What am i missing?

答:
what that table means is that in an expression like that the elements are evaluated as

a && (a.test === 'something') and not as (a && a.test) === 'something'

because of the order of precedence.this is totally independent on how the logical expressions are evaluated(in order of appearance). so if a is false there is no reason to evaluate the rest of the expression because no matter what lies after the && the expression will be false. same thing would happen if a was true and the operator was ||. this is also known as short-circuit.

Title: Why is "and" evaluated before "equal"

Body:
In Javascript precedence of strict equal (10) is greater than logical and (6) then how does this code works

var a;
console.log("value of a is", a);
if (a && a.test === "test") {}

Should it not throw error

cannot read test of undefined.

And to add salt to the wound precedence of member access is higher than both of them (19).

What am i missing?


问:
How to change values in a 2-dimensional array?
I have a simple program to find the greater number of two numbers and store them in first line of an array.

the array is arr[tot][2] and I want to compare each element in arr[tot][0] to elements in arr[tot][1] but its giving me Invalid array assignment.
which function/method should I use to do that ?

```<code>for(i=0;i<tot;i++)
    {
        if(arr[i,1]>arr[i,0])
            {
            arr[i,0]=arr[i,1]}
    }
</code>```

Full program

```<code>#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
    //Input

    int tot = 23;
    int arr[tot][2] = {
    {9272992,-5268711},
    {-6457223,-8368810},
    {-3415057,-2776446},
    {-6492757,-3453386},
    {4313482,4783138},
    {5573672,8360909},
    {-2546018,2224083},
    {1267093,4700254},
    {6136723,9042717},
    {1277125,2796189},
    {-2062877,2036481},
    {6089545,-6182241},
    {-8795303,6074456},
    {8152425,785931},
    {-5134200,4319924},
    {6820437,-5861208},
    {9051213,-9636786},
    {-4230018,-4363843},
    {-2413233,-722776},
    {2182770,-8099750},
    {-5939638,-2243558},
    {-9738840,1514344},
    {9980524,1528253}
        };

    //the comparing
    int i;
    for(i=0;i<tot;i++)
        {
            if(arr[i,1]>arr[i,0])
                {
                arr[i,0]=arr[i,1]
                }
        }
    for(i=0;i<tot;i++)
        {
        cout<<arr[i,0]<<" ";
        }
    return 0;
}
</code>```

Thanks for answering my questions :)
Also thanks for the downvotes, It really helped me understand that only smart and advanced questions are allowed here and stupid mistakes and syntax errors are not welcome.

答:
@songyuanyao's comment is correct. If you want to access a value in a 2D array, you need to use arr[i][0].

You code has three errors:

When you declare an array, the number of elements must be a constant. So int tot = 23; should be const int tot = 23;

arr[i,0] is a valid expression, but it shouldn't be used here. You should use the syntax arr[i][0] throughout this program.

You missed a semicolon.

Some explanation for #2: The error "Invalid array assignment" is due to the line arr[i,0]=arr[i,1] (you missed a ; here as well). In arr[i,0], the comma is a comma operator, which returns the value of the second operand. So arr[i,0] is equivalent to arr[0], which is a 1D array. Similarly arr[i,1] is arr[1] which is also a 1D array. But array is not a modifiable L-value, so arr[i,0]=arr[i,1] gives "Invalid array assignment" error. This also explains why arr[i,1]>arr[i,0] doesn't give compile-time error, but it's a runtime bug.

Body:
I have a simple program to find the greater number of two numbers and store them in first line of an array.

the array is arr[tot][2] and I want to compare each element in arr[tot][0] to elements in arr[tot][1] but its giving me Invalid array assignment.
which function/method should I use to do that ?

for(i=0;i<tot;i++)
    {
        if(arr[i,1]>arr[i,0])
            {
            arr[i,0]=arr[i,1]}
    }

Full program

#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
    //Input

    int tot = 23;
    int arr[tot][2] = {
    {9272992,-5268711},
    {-6457223,-8368810},
    {-3415057,-2776446},
    {-6492757,-3453386},
    {4313482,4783138},
    {5573672,8360909},
    {-2546018,2224083},
    {1267093,4700254},
    {6136723,9042717},
    {1277125,2796189},
    {-2062877,2036481},
    {6089545,-6182241},
    {-8795303,6074456},
    {8152425,785931},
    {-5134200,4319924},
    {6820437,-5861208},
    {9051213,-9636786},
    {-4230018,-4363843},
    {-2413233,-722776},
    {2182770,-8099750},
    {-5939638,-2243558},
    {-9738840,1514344},
    {9980524,1528253}
        };

    //the comparing
    int i;
    for(i=0;i<tot;i++)
        {
            if(arr[i,1]>arr[i,0])
                {
                arr[i,0]=arr[i,1]
                }
        }
    for(i=0;i<tot;i++)
        {
        cout<<arr[i,0]<<" ";
        }
    return 0;
}

Thanks for answering my questions :)
Also thanks for the downvotes, It really helped me understand that only smart and advanced questions are allowed here and stupid mistakes and syntax errors are not welcome.


问:
How to insert line endings in Sinatra
I was wondering how I could perform output in multiple lines in Sinatra. Eg.

```<code>get '/test' do
  array= ["one","two","three"]
  "#{array.each { |elem| elem}}"
end
</code>```

ideally would have output:

```<code>one
two
three
</code>```

not onetwothree

I'm fairly new to Sinatra and Ruby (first day of study) so please apology me for basic question (can't find answer anywhere)

答:
Plain text newlines

```<code>["one", "two", "three"].join("\n")
</code>```

or for HTML line breaks:

```<code>["one", "two", "three"].join("<br>")
</code>```

Reference: http://ruby-doc.org/core/classes/Array.html#M002182

Note: It's not a sinatra problem. Newlines are intepreted differently in HTML, plain newlines aren't interpreted as such by HTML, unless they are inside a ```</code> block; outside <code>```
 is used for linebreaks.

Title: How to insert line endings in Sinatra

Body:
I was wondering how I could perform output in multiple lines in Sinatra. Eg.

get '/test' do
  array= ["one","two","three"]
  "#{array.each { |elem| elem}}"
end

ideally would have output:

one
two
three

not onetwothree

I'm fairly new to Sinatra and Ruby (first day of study) so please apology me for basic question (can't find answer anywhere)

Body:
Plain text newlines

["one", "two", "three"].join("\n")

or for HTML line breaks:

["one", "two", "three"].join("<br>")

Reference: http://ruby-doc.org/core/classes/Array.html#M002182

Note: It's not a sinatra problem. Newlines are intepreted differently in HTML, plain newlines aren't interpreted as such by HTML, unless they are inside a <pre> block; outside <pre> <br> is used for linebreaks.


问:
SQLAlchemy - Max of column among rows with same value in other column
I have the following a Table DataUnit with columns session_id (INT) and timeStamp (INT). I want to find the maximum value of timeStamp for a given value of session_id. How to do this in SQLAlchemy?

I can simply query all rows with given session_id, order by timeStamp and take the first element, but what will be the more efficient way of doing it?

Table definition:-

```<code>class DataUnit(db.Model):
    __tablename__ = 'DataUnit'
    dataUnit_id = Column(Integer(), primary_key=True, autoincrement=True)
    session_id = Column(Integer(), ForeignKey('Session.session_id'))
    timeStamp = Column(BigInteger())
</code>```

答:
Your database probably has the aggregate function MAX(), and SQLAlchemy offers a generic approach to using SQL function expressions, the special func object. Since you are interested in a scalar value, you can also employ Query.scalar(), which returns the first column of the first result row, or None. It'd seem like you use Flask-SQLAlchemy, since you inherit from db.Model, so here's a method of using Model.query with Query.with_entities():

```<code>session_id = 'insert session id here'

max_timestamp = DataUnit.query.\
    filter_by(session_id=session_id).\
    with_entities(db.func.max(DataUnit.timeStamp)).\
    scalar()
</code>```

Efficiency of the query will depend on your database engine and possible indexes available.

Body:
I have the following a Table DataUnit with columns session_id (INT) and timeStamp (INT). I want to find the maximum value of timeStamp for a given value of session_id. How to do this in SQLAlchemy?

I can simply query all rows with given session_id, order by timeStamp and take the first element, but what will be the more efficient way of doing it?

Table definition:-

class DataUnit(db.Model):
    __tablename__ = 'DataUnit'
    dataUnit_id = Column(Integer(), primary_key=True, autoincrement=True)
    session_id = Column(Integer(), ForeignKey('Session.session_id'))
    timeStamp = Column(BigInteger())

Body:
Your database probably has the aggregate function MAX(), and SQLAlchemy offers a generic approach to using SQL function expressions, the special func object. Since you are interested in a scalar value, you can also employ Query.scalar(), which returns the first column of the first result row, or None. It'd seem like you use Flask-SQLAlchemy, since you inherit from db.Model, so here's a method of using Model.query with Query.with_entities():

session_id = 'insert session id here'

max_timestamp = DataUnit.query.\
    filter_by(session_id=session_id).\
    with_entities(db.func.max(DataUnit.timeStamp)).\
    scalar()

Efficiency of the query will depend on your database engine and possible indexes available.


问:
How to convert all values in a pandas DataFrame to string according to display settings?
How can I turn a DataFrame into DataFrame of strings according to the same rules that str(df) uses?

I tried df.astype("str") and df.applymap(str), but both left floats with larger precision than indicated by display.precision setting.

答:
You can use applymap with a format string, e.g.:</p>

```<code>df.applymap(lambda x: '{0:.2f}'.format(x))
</code>```

Body:
You can use applymap with a format string, e.g.:

df.applymap(lambda x: '{0:.2f}'.format(x))


问:
Javascript functions are not implementing
My webpage should display a slideshow on page load but the script functions doesn't seem to be working. I have tried running simple scripts containing  prompt() and confirm() functions and they are working fine but custom functions doesn't seem to work. Same is the case with my "modal.js" script which should display a modal box on button click. Please help me out

```<code><!doctype html>
<html lang = "en">
<head>
    <title> Ice Cream </title>
    <link rel="stylesheet" href="main_ice.css" />
    <script type = "text/javascript" src = "slideShow.js"> </script>
    <script src = "modal.js"> </script>
    <meta charset = "utf-8" />
</head>
<body>
    <div id = "big_wrapper">
            <header  class= "top_header">
                <hgroup>
                    <h1> ICE Funky </h1>
                    <h3> ice cream production </h3>
                </hgroup>
            </header>

            <nav class= "nav_bar">
                <ul>
                    <label><li name = "home"> Home </li>
                    <li> About Us </li>
                    <li> Products </li>
                    <li> Services </li>
                    <li> Contacts </li>
                    </label>
                </ul>
            </nav>

        <div id = "slideshow">

            <span class = "image_slide"><img src = "4072.jpg" width = "500px" height = "300px"/> </span>
            <span class = "image_slide"><img src = "26551.jpg" width = "500px" height = "300px"/> </span>
            <span class = "image_slide"><img src = "30225.jpg" width = "500px" height = "300px"/> </span>
            <span class = "image_slide"><img src = "74223.jpg" width = "500px" height = "300px"/> </span>
            <span class = "image_slide"><img src = "74285.jpg" width = "500px" height = "300px"/> </span>

        </div>
        <button id = "modalButton"> Modal </button>
                <div id = "myModal">
                    <div id = "modal_title"> Main Title </div><br><br>
                    <div id = "modal_body"> Body </div>
                </div>

    </div>

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

!-----------CSS File ----------------!

```<code>*{
    margin:0px;
    padding:0px;
}

header, footer, nav, hgroup, aside, article, section{
    display : block;
}

body{
    width:100%;
    display: -webkit-box;
    -webkit-box-pack: center;
}

#big_wrapper{
    max-width: 100%;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-box-flex: 1;
}

.top_header{
    position: absolute;
    margin: 20px 0px 0px 120px;
    border: 2px solid black;
    width: 180px;
    padding: 25px;

}

.nav_bar{
    margin-left: 350px;
    margin-top: 85px;
    text-align: center;
}
.nav_bar li{
    position: relative;
    list-style: none;
    display: inline-block;
    -webkit-box-flex: 1;
    margin: 20px;
    border: 2px solid white;
    padding: 5px;
    -webkit-transition: border-left 1s,  border-top 3s,  border-right 4s,
                         border-bottom 6s;
}

.nav_bar li:hover{
    border-left: 2px solid black;
    border-top: 2px solid black;
    border-right: 2px solid black;
    border-bottom: 2px solid black;
}

#slideshow{
    position: absolute;
    margin-top: 50px;
    margin-left: 400px;
    width: 500px;
}

.image_slide{
    position: absolute;
    /*display: none;*/

}

.prev, .next {
  cursor: pointer;
  position: absolute;
  top: 150px;
  width: auto;
  margin-top: -22px;
  padding: 16px;
  color: yellow;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
}

.next{
    /*left: 458px;*/
    right: 0px;
}

.prev:hover, .next:hover {
  background-color: rgba(0,0,0,0.8);
}

#modalButton{
    background: rgba(0,256,0,0.5);
    padding: 5px;
    margin-left: 40px;
    margin-top: 40px;
    color: chocolate;
}

#myModal{
    position: fixed;
    top:0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 0;
    background-color: rgba(0,0,0,0.4);
    display: none;
}

#modal_title{
    width: 95%;
    height: 5%;
    position: fixed;
    bottom: 15%;
    left: 30px;
    background: rgba(0,256,0,0.4);
}

#modal_body{
    width: 95%;
    height: 10%;
    position: fixed;
    top: 85%;
    left: 30px;
    background: rgba(256,256,256,0.4);

}
</code>```

!--------------JS File(slideShow.js)----------------!

```<code>    var slideIndex = 0;
    showSlides();

    function showSlides() {
        var i;
        var slides = document.getElementsByClassName("image_slide");
        for (i = 0; i < slides.length; i++) {
            slides[i].style.display = "none";
        }
        slideIndex++;
        if (slideIndex> slides.length) {slideIndex = 1}
        slides[slideIndex-1].style.display = "block";
        setTimeout(showSlides, 2000); // Change image every 2 seconds
    }
</code>```

!---------------JS File(modal.js)------------------!

```<code>modalButton = getElementById("modalButton");
myModal = getElementById("myModal");
modalButton.onclick = function(){
    prompt("hi");
    myModal.style.display = "block";

}
</code>```

答:
You have to use document.getElementById() instead of getElementById() being used directly.

Make modifications to your modal.js file.

```<code>modalButton = document.getElementById("modalButton");
myModal = document.getElementById("myModal");
modalButton.onclick = function(){
    prompt("hi");
    myModal.style.display = "block";

}
</code>```

Working fiddle - https://jsfiddle.net/arjunskumar47/L8Lvwywe/

Body:
My webpage should display a slideshow on page load but the script functions doesn't seem to be working. I have tried running simple scripts containing  prompt() and confirm() functions and they are working fine but custom functions doesn't seem to work. Same is the case with my "modal.js" script which should display a modal box on button click. Please help me out

<!doctype html>

    <title> Ice Cream </title>
    <link rel="stylesheet" href="main_ice.css" />

    <meta charset = "utf-8" />

                <hgroup>

 ICE Funky

 ice cream production

                </hgroup>

 Home

 About Us

 Products

 Services

 Contacts

        <button id = "modalButton"> Modal </button>

 Main Title

 Body

!-----------CSS File ----------------!

*{
    margin:0px;
    padding:0px;
}

header, footer, nav, hgroup, aside, article, section{
    display : block;
}

body{
    width:100%;
    display: -webkit-box;
    -webkit-box-pack: center;
}

#big_wrapper{
    max-width: 100%;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-box-flex: 1;
}

.top_header{
    position: absolute;
    margin: 20px 0px 0px 120px;
    border: 2px solid black;
    width: 180px;
    padding: 25px;

}

.nav_bar{
    margin-left: 350px;
    margin-top: 85px;
    text-align: center;
}
.nav_bar li{
    position: relative;
    list-style: none;
    display: inline-block;
    -webkit-box-flex: 1;
    margin: 20px;
    border: 2px solid white;
    padding: 5px;
    -webkit-transition: border-left 1s,  border-top 3s,  border-right 4s,
                         border-bottom 6s;
}

.nav_bar li:hover{
    border-left: 2px solid black;
    border-top: 2px solid black;
    border-right: 2px solid black;
    border-bottom: 2px solid black;
}

#slideshow{
    position: absolute;
    margin-top: 50px;
    margin-left: 400px;
    width: 500px;
}

.image_slide{
    position: absolute;
    /*display: none;*/

}

.prev, .next {
  cursor: pointer;
  position: absolute;
  top: 150px;
  width: auto;
  margin-top: -22px;
  padding: 16px;
  color: yellow;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
}

.next{
    /*left: 458px;*/
    right: 0px;
}

.prev:hover, .next:hover {
  background-color: rgba(0,0,0,0.8);
}

#modalButton{
    background: rgba(0,256,0,0.5);
    padding: 5px;
    margin-left: 40px;
    margin-top: 40px;
    color: chocolate;
}

#myModal{
    position: fixed;
    top:0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 0;
    background-color: rgba(0,0,0,0.4);
    display: none;
}

#modal_title{
    width: 95%;
    height: 5%;
    position: fixed;
    bottom: 15%;
    left: 30px;
    background: rgba(0,256,0,0.4);
}

#modal_body{
    width: 95%;
    height: 10%;
    position: fixed;
    top: 85%;
    left: 30px;
    background: rgba(256,256,256,0.4);

}

!--------------JS File(slideShow.js)----------------!

    var slideIndex = 0;
    showSlides();

    function showSlides() {
        var i;
        var slides = document.getElementsByClassName("image_slide");
        for (i = 0; i < slides.length; i++) {
            slides[i].style.display = "none";
        }
        slideIndex++;
        if (slideIndex> slides.length) {slideIndex = 1}
        slides[slideIndex-1].style.display = "block";
        setTimeout(showSlides, 2000); // Change image every 2 seconds
    }

!---------------JS File(modal.js)------------------!

modalButton = getElementById("modalButton");
myModal = getElementById("myModal");
modalButton.onclick = function(){
    prompt("hi");
    myModal.style.display = "block";

}

Body:
You have to use document.getElementById() instead of getElementById() being used directly.

Make modifications to your modal.js file.

modalButton = document.getElementById("modalButton");
myModal = document.getElementById("myModal");
modalButton.onclick = function(){
    prompt("hi");
    myModal.style.display = "block";

}

Working fiddle - https://jsfiddle.net/arjunskumar47/L8Lvwywe/


答: You have imported java.util.zip.ZipFile and are attempting to call methods on it which do not exist. You can find the ZipFile's API via the link I provided above. As you also imported net.lingala.zip4j.model.FileHeader I guess you wanted to use a different zip library than the one found under java.util.zip. So in order to solve your problem you have to clean up your imports. You most likely need to delete the import statements for the package java.util.zip and need to import the appropriate classes from net.lingala.zip4j.*.

Title: I am trying to extract password-protected ZIP files using zip4j jar file but i am getting error for following

Body:
I am very new to Java and I am trying to extract password-protected ZIP file using java and I have written code for the same but I am getting error for few methods such as isEncrypted(), fileHeaderList(), extractFile(),
I searched for few related posts/issues but did not find the exact resolution.
Can anyone of you help me in this issue

 import java.util.ArrayList;
    import java.util.List;
    import java.util.zip.ZipFile;
    import net.lingala.zip4j.model.FileHeader;

    public class Extraction {
    public Extraction() {

            try {
                ZipFile zipFile = new ZipFile("C:\\Users\\rajesh\\Desktop\\ZipFile\\file1.zip");

                //Error for isEncrypted() "The method isEncrypted() is undefined for the type ZipFile"
                if (zipFile.isEncrypted()) {
                                        zipFile.setPassword("MYPASS!");
                }

                //The method getFileHeaders() is undefined for the type ZipFile
                List fileHeaderList = zipFile.getFileHeaders();

                                for (int i = 0; i < fileHeaderList.size(); i++) {
                    FileHeader fileHeader = (FileHeader)fileHeaderList.get(i);
        //The method extractFile(FileHeader, String) is undefined for the type ZipFile
zipFile.extractFile(fileHeader, "C:\\Users\\rajesh\\Desktop\\ZipFile");
                }

            } catch (Exception e) {
                System.out.println("Please Try Again");
            }

        }

        public static void main(String[] args) {
            new Extraction();

        }

    }


问:
Do additional function/method definitions increase a program's memory footprint?
In C++, does defining additional methods or functions that don't get used result in a larger memory footprint or slower execution speed?

Basically, I have several utility debugging methods in a class, none of which are required for the normal use of the class. Would it make a difference in terms of memory footprint or speed whether or not these definitions remain if they're never used? For example:

```<code>class myClass
{
    public:

        //Something the user of this class would use
        int doSomething() {...}

        //Something used solely to make sure I wrote the class properly
        bool isClassValid() {...}
};

...

myClass classInstance();
myClass.doSomething();
</code>```

答: Determining whether code is unused or not is a fairly hard problem. Just write a hello world program, static link it with glibc, and use objdump to look at all the junk that ends up in your binary. The vast majority of this code is not used, but it's referenced in ways that makes it difficult or impossible for a compiler or linker to optimize it out. Unless as a library author you work very diligently to avoid introducing this kind of dependency, unused functions/methods will waste space, and probably lots of it. I suspect it's even harder in C++ than in C.

Body:
In C++, does defining additional methods or functions that don't get used result in a larger memory footprint or slower execution speed?

Basically, I have several utility debugging methods in a class, none of which are required for the normal use of the class. Would it make a difference in terms of memory footprint or speed whether or not these definitions remain if they're never used? For example:

class myClass
{
    public:

        //Something the user of this class would use
        int doSomething() {...}

        //Something used solely to make sure I wrote the class properly
        bool isClassValid() {...}
};

...

myClass classInstance();
myClass.doSomething();


问:
Using a JSON script in HTML and show data
Here is the Link to JSON.
http://api.wunderground.com/api/c3d8a6a640832fd0/conditions/forecast/alert/q/29.9205347,73.8706849.json

This JSON file give data about weather

And I want to show this data, given by the above link into my HTML file. I am using JSON for the first time. So I need help linking this JSON file into my HTML document.

```<code><html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
</head>

<body>

<div class="wrapper">
<span id="temp"></span>
<span id="high"></span>
<span id="low"></span>
<span id="windspeed"></span>
<span id="description"></span>
<span id="city"></span>
<span id="iconorimage"></span>
<span id="time"></span>
<span id="any thing else"></span>
</div>
</body>
</html>
</code>```

I am ok, If I can show only temperature, city, weather icon [rain,sunny], a text description about weather, high/low, wind speed and time.

答:
You can use Ajax for load data.

See example,

```<code>function getJson(){
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            console.log(JSON.parse(this.responseText));
        }
    };
    xhttp.open("GET", "http://api.wunderground.com/api/c3d8a6a640832fd0/conditions/forecast/alert/q/29.9205347,73.8706849.json", true);
    xhttp.send();
}
getJson();
</code>```

It will return JSON decoded data.

Body:
Here is the Link to JSON.
http://api.wunderground.com/api/c3d8a6a640832fd0/conditions/forecast/alert/q/29.9205347,73.8706849.json

This JSON file give data about weather

And I want to show this data, given by the above link into my HTML file. I am using JSON for the first time. So I need help linking this JSON file into my HTML document.

I am ok, If I can show only temperature, city, weather icon [rain,sunny], a text description about weather, high/low, wind speed and time.

Body:
You can use Ajax for load data.

See example,

function getJson(){
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            console.log(JSON.parse(this.responseText));
        }
    };
    xhttp.open("GET", "http://api.wunderground.com/api/c3d8a6a640832fd0/conditions/forecast/alert/q/29.9205347,73.8706849.json", true);
    xhttp.send();
}
getJson();

It will return JSON decoded data.


问:
Can an app created using Microsoft Desktop App converter be used on a Surface Hub?
I've converted an app using Microsoft's Desktop App Converter Here are the instructions I followed and I was able to install it just fine on a laptop running Windows 10. I then used Windows Configuration Designer to create a package to use to install it on the Surface Hub, but that fails to install on the Surface Hub. It says a 'Provisioning failure occurred".

I've tried converting multiple apps and none of them install on the Hub. Am I doing something wrong or does the Desktop App Converter just not work with the Surface Hub?

Thank you

答:
You cannot install the app on the other devices, for now. It can run only on Windows 10 desktops (including the new Windows 10 S), not tablets (ARM based), phones, the Surface Hub or any other device from the Windows 10 ecosystem.

As the picture below shows, the Desktop Bridge is here to help you start migrating your app to a full universal version. Remember, you're still building your binaries as Win32/.NET resources, the only difference is that the Desktop Bridge helps you package them inside of an AppX instead of an MSI and allows you to access the UWP APIs (live tiles, etc..,), and of course get published in the Windows Store.

You can read more about the Desktop Bridge migration process and options on the Microsoft blogs.

Once you get to the final step, Reach All from the below picture, where the code from your app is all UWP, you can deploy your application on any Windows 10 device you want.