问:
Download zip file from REST web service + AngularJS
I am using REST jersey on server side and AngularJS on client side.

My requirement is to download the zip file requested by client for specific date range.

Server side code: //Time being I have hardcoded one zip file for testing

```<code>@POST
    @Path("/LogRange")
    @Produces({MediaType.APPLICATION_OCTET_STREAM} )
    @Consumes({ MediaType.APPLICATION_JSON} )
    public Response getLogsBetween(@HeaderParam(HttpHeaders.AUTHORIZATION) String authorization,
            @Context HttpServletRequest request, @Context HttpServletResponse response, LogFolders folders){

        StreamingOutput stream = new StreamingOutput(){
            @Override
                public void write(OutputStream arg0) {
                    // TODO Auto-generated method stub
                    BufferedOutputStream bus = new BufferedOutputStream(arg0);
                    try {
                        File file = new File("C:\\ProgramData\\ABC\\Logfiles\\UI.zip");
                        FileInputStream fizip = new FileInputStream(file);
                        byte[] buffer2 = IOUtils.toByteArray(fizip);
                        bus.write(buffer2);
                        bus.flush();
                        bus.close();

                    } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    }
                }
            };
            return Response.status(Response.Status.OK).entity(stream).header("Content-Disposition","attachment; filename=\"log.zip\"").build();
}
</code>```

Client side code:

```<code>$http({
    url : urlBase + endPoint,
    method: "POST",
    data: formData, //this is your json data string
    headers : {
        'Content-Type' : "application/json",
        'Authorization' : authCode,
    },
    responseType: 'arraybuffer'
}).success(function(response, status, headers, config) {

    var blob = new Blob([response], { type: "application/zip" });
    var objectUrl = URL.createObjectURL(blob);
    window.open(objectUrl);

    }).error(function (data, status, headers, config) {
    //upload failed
});
</code>```

File get downloaded in local but it is always corrupted and displays like below.
Please help me on how to download file properly.

答:
HTML

```<code>    <html ng-app="ReviwerApp">

    <div   ng-controller="downloadCtrl">

    <button ng-click="downloadzippedPdfs()" class="btn btn-danger">Download</button>

   </div>

   </html>
</code>```

JavaScript

```<code>'use strict';

angular.module('downloads', []);

 //Routers
 myApp.config(function($stateProvider) {

 $stateProvider.state('downloads', {
 url: '/downloads',
 templateUrl: 'partials/downloads/downloads.html',
 data:{
    auth:true
 }
 });

 });

 //Factories
 myApp.factory('downloadServices', ['$http', function($http) {

 var factoryDefinitions = {
  getdownloadcontent: function() {

        return  $http.get('/smartcompare/rest/download/zip/2017-06-30', {
            headers: {'Authorization': 'Basic xyz12345'},
          responseType: 'arraybuffer'
       }).then(function(response) { return response;  });
  },
}

return factoryDefinitions;
}
 ]);

 //Controllers
myApp.controller('downloadCtrl', ['$scope', 'downloadServices' ,
 function($scope, downloadServices ) {

 var fileName = "comressedpdfreports.zip";
    var a = document.createElement("a");
    document.body.appendChild(a);

downloadServices.getdownloadcontent().then(function(response){
    $scope.downloadzippedPdfs =    function () {

            var file = new Blob([response.data], {type: 'application/zip'});
            var fileURL = URL.createObjectURL(file);
            a.href = fileURL;
            a.download = fileName;
            a.click();

    };

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

Java

```<code> import java.io.File;
 import java.io.IOException;
 import java.nio.file.Files;
 import java.nio.file.Paths;
 import javax.ws.rs.GET;
 import javax.ws.rs.HeaderParam;
 import javax.ws.rs.Path;
 import javax.ws.rs.PathParam;
 import javax.ws.rs.WebApplicationException;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.StreamingOutput;
 import sun.misc.BASE64Decoder;

 @Path("/download")

 public class FileDownloadService {

    @Path("/zip/{date}")

    @GET
    public Response downloadzipFile( @HeaderParam("authorization") String authString, @PathParam("date") String date)
    {
      {
     StreamingOutput fileStream =  new StreamingOutput()
        {
            @Override
            public void write(java.io.OutputStream output) throws IOException, WebApplicationException
            {
                try
                {

                    java.nio.file.Path path = Paths.get( "DailyReports"+File.separator+date+".zip");
                    byte[] data = Files.readAllBytes(path);
                    output.write(data);
                    output.flush();
                }
                catch (Exception e)
                {
                    throw new WebApplicationException("File Not Found !!");
                }
            }
        };
        return Response
                .ok(fileStream, MediaType.APPLICATION_OCTET_STREAM)
                .header("content-disposition","attachment; filename = "+date+".zip")
                .build();

    }
</code>```

Body:
I am using REST jersey on server side and AngularJS on client side.

My requirement is to download the zip file requested by client for specific date range.

Server side code: //Time being I have hardcoded one zip file for testing

@POST
    @Path("/LogRange")
    @Produces({MediaType.APPLICATION_OCTET_STREAM} )
    @Consumes({ MediaType.APPLICATION_JSON} )
    public Response getLogsBetween(@HeaderParam(HttpHeaders.AUTHORIZATION) String authorization,
            @Context HttpServletRequest request, @Context HttpServletResponse response, LogFolders folders){

        StreamingOutput stream = new StreamingOutput(){
            @Override
                public void write(OutputStream arg0) {
                    // TODO Auto-generated method stub
                    BufferedOutputStream bus = new BufferedOutputStream(arg0);
                    try {
                        File file = new File("C:\\ProgramData\\ABC\\Logfiles\\UI.zip");
                        FileInputStream fizip = new FileInputStream(file);
                        byte[] buffer2 = IOUtils.toByteArray(fizip);
                        bus.write(buffer2);
                        bus.flush();
                        bus.close();

                    } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    }
                }
            };
            return Response.status(Response.Status.OK).entity(stream).header("Content-Disposition","attachment; filename=\"log.zip\"").build();
}

Client side code:

$http({
    url : urlBase + endPoint,
    method: "POST",
    data: formData, //this is your json data string
    headers : {
        'Content-Type' : "application/json",
        'Authorization' : authCode,
    },
    responseType: 'arraybuffer'
}).success(function(response, status, headers, config) {

    var blob = new Blob([response], { type: "application/zip" });
    var objectUrl = URL.createObjectURL(blob);
    window.open(objectUrl);

    }).error(function (data, status, headers, config) {
    //upload failed
});

File get downloaded in local but it is always corrupted and displays like below.
Please help me on how to download file properly.

Body:
HTML

    <html ng-app="ReviwerApp">

    <div   ng-controller="downloadCtrl">

    <button ng-click="downloadzippedPdfs()" class="btn btn-danger">Download</button>

   </div>

   </html>

JavaScript

'use strict';

angular.module('downloads', []);

 //Routers
 myApp.config(function($stateProvider) {

 $stateProvider.state('downloads', {
 url: '/downloads',
 templateUrl: 'partials/downloads/downloads.html',
 data:{
    auth:true
 }
 });

 });

 //Factories
 myApp.factory('downloadServices', ['$http', function($http) {

 var factoryDefinitions = {
  getdownloadcontent: function() {

        return  $http.get('/smartcompare/rest/download/zip/2017-06-30', {
            headers: {'Authorization': 'Basic xyz12345'},
          responseType: 'arraybuffer'
       }).then(function(response) { return response;  });
  },
}

return factoryDefinitions;
}
 ]);

 //Controllers
myApp.controller('downloadCtrl', ['$scope', 'downloadServices' ,
 function($scope, downloadServices ) {

 var fileName = "comressedpdfreports.zip";
    var a = document.createElement("a");
    document.body.appendChild(a);

downloadServices.getdownloadcontent().then(function(response){
    $scope.downloadzippedPdfs =    function () {

            var file = new Blob([response.data], {type: 'application/zip'});
            var fileURL = URL.createObjectURL(file);
            a.href = fileURL;
            a.download = fileName;
            a.click();

    };

   });
   }]);

Java

 import java.io.File;
 import java.io.IOException;
 import java.nio.file.Files;
 import java.nio.file.Paths;
 import javax.ws.rs.GET;
 import javax.ws.rs.HeaderParam;
 import javax.ws.rs.Path;
 import javax.ws.rs.PathParam;
 import javax.ws.rs.WebApplicationException;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.StreamingOutput;
 import sun.misc.BASE64Decoder;

 @Path("/download")

 public class FileDownloadService {

    @Path("/zip/{date}")

    @GET
    public Response downloadzipFile( @HeaderParam("authorization") String authString, @PathParam("date") String date)
    {
      {
     StreamingOutput fileStream =  new StreamingOutput()
        {
            @Override
            public void write(java.io.OutputStream output) throws IOException, WebApplicationException
            {
                try
                {

                    java.nio.file.Path path = Paths.get( "DailyReports"+File.separator+date+".zip");
                    byte[] data = Files.readAllBytes(path);
                    output.write(data);
                    output.flush();
                }
                catch (Exception e)
                {
                    throw new WebApplicationException("File Not Found !!");
                }
            }
        };
        return Response
                .ok(fileStream, MediaType.APPLICATION_OCTET_STREAM)
                .header("content-disposition","attachment; filename = "+date+".zip")
                .build();

    }


来源: stackexchange

问:
Reconfiguring the DNS to show the SSL certificate online?
So, I am trying to get the SSL certificate to show up on my website but even after following all the steps from the aws documentation and various internet tutorials. The SSL lock sign is still not visible up on my website.

I found this website really helpful and tried to follow all the steps listed there : https://blog.webinista.com/2016/02/enable-https-cloudfront-certificate-manager-s3/index.html

What I think the problem is that I am not quite certain how to reconfigure the DNS server after creating the cloudfront distribution. In this instance, I just created an alias target for my domain name (shamveelahammed.com) to point towards the cloudfront distribution. But this hasn't worked at all for me. At the moment, I only have 4 entries in my domain record set.
https://www.dropbox.com/s/5g2nkyxip1c22oo/Screen%20Shot%202017-07-05%20at%2002.05.31.png?dl=0

Any help with figuring out my next steps will be massively appreciated. (N.B I am very new to this and still learning how to use AWS.)

答:
Well, thanks for all the helpful answers. I managed to find a work around to solve the issue I was having.

I generated a new certificate for the domain www.shamveelahammed.com .

Created a target alias for cloud distribution pointed towards www.shamveelahammed.com .

And finally, redirected all the requests made in www.shamveelahammed.com in s3 bucket to shamveelahammed.com.

This fixed my problem. Hope this helps...

ContentLicense: CC BY-SA 3.0


问:
Python Showing:- TypeError: 'int' object is not callable in python While Trying to Run Code
Well, I researched and saw many posts on this but none of them let me fix my code.

I am learning python and is currently learning Object Oriented classes.

This is My Code:-

```<code>class Employee:
    'Common base calss for all employees'
    empCount = 0

    def __init__(self,name,salary):
        self.name = name
        self.salary = salary
        Employee.empCount += 1

    def displayCount(self):
        print "Total Employee %d" % Employee.empCount

    def displayEmployee(self):
        print "Name: ", self.name, ",Salary: ", self.salary

"This whould create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This whould create second object of employee class"
emp2 = Employee("Manni", 5000)

emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount()
</code>```

And then when I run it:-

```<code>Name:  Zara ,Salary:  2000
Name:  Manni ,Salary:  5000

Traceback (most recent call last):
File "D:/Python Programs/Object Oriented-Classes(Python 2).py", line 46, in
<module>
print "Total Employee %d" % Employee.empCount()
TypeError: 'int' object is not callable
</code>```

答:
Look at the error.

TypeError : 'int' object is not callable

You are trying to call a class variable Employee.empCount which is an integer and thus cannot be called.

Just change it to Employee.empCount and it should print out the varialble.

Body:
Well, I researched and saw many posts on this but none of them let me fix my code.

I am learning python and is currently learning Object Oriented classes.

This is My Code:-

class Employee:
    'Common base calss for all employees'
    empCount = 0

    def __init__(self,name,salary):
        self.name = name
        self.salary = salary
        Employee.empCount += 1

    def displayCount(self):
        print "Total Employee %d" % Employee.empCount

    def displayEmployee(self):
        print "Name: ", self.name, ",Salary: ", self.salary

"This whould create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This whould create second object of employee class"
emp2 = Employee("Manni", 5000)

emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount()

And then when I run it:-

Name:  Zara ,Salary:  2000
Name:  Manni ,Salary:  5000

Traceback (most recent call last):
File "D:/Python Programs/Object Oriented-Classes(Python 2).py", line 46, in
<module>
print "Total Employee %d" % Employee.empCount()
TypeError: 'int' object is not callable


问:
Virtual functions and performance - C++
In my class design, I use abstract classes and virtual functions extensively. I had a  feeling that virtual functions affects the performance. Is this true? But I think this performance difference is not noticeable and looks like I am doing premature optimization. Right?</p>

答:
A good rule of thumb is:

It's not a performance problem until you can prove it.

The use of virtual functions will have a very slight effect on performance, but it's unlikely to affect the overall performance of your application. Better places to look for performance improvements are in algorithms and I/O.

An excellent article that talks about virtual functions (and more) is Member Function Pointers and the Fastest Possible C++ Delegates.

OwnerDisplayName: Appu

Title: Virtual functions and performance - C++

LastEditorDisplayName: Serge

OwnerDisplayName: Greg Hewgill

ContentLicense: CC BY-SA 2.5


问:
How can I undo my last git add/commit?
I edited a file and did:

```<code>git add file.py
git commit -m 'fixed bug'
</code>```

I then edited another file and performed a minor bug fix. I don't want two commits, one after the other, showing 'bug fix'. I want one commit with 'bug fixes'.

How can I undo the last add/commit and change the first commit message?

I was looking at the git reset, git revert, git undo commands but I don't want to screw up my repo with a guess

EDIT: Found out how to do it: http://www.gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html

答:
If you already commited your second change, reset it first:

```<code>git reset HEAD^
</code>```

Now your HEAD is at the first commit, and the content of your local files is unchanged.

```<code>git add <the file(s) for the second bug fix>
git commit --amend -m'bug fixes'
</code>```

If all tracked and changed file are to be included for the second bug fix, you can run this instead, as usual:

```<code>git commit -a --amend
</code>```

Amending the commit is exactly this:

adds the changes in index to the previous commit (therefore the need for git add, or -a)

allows you to change your commit message

Be careful, though: if you have distributed the first commit, other people's repo will get strange. You should not change a commit that someone else has fetched.

You could also probably use git merge --squash, which feels more logical but not necessarily easier. Use it to merge a branch containing your two commits, unto the previous commit.

Squashing works with git rebase as well.

Title: How can I undo my last git add/commit?

Body:
I edited a file and did:

git add file.py
git commit -m 'fixed bug'

I then edited another file and performed a minor bug fix. I don't want two commits, one after the other, showing 'bug fix'. I want one commit with 'bug fixes'.

How can I undo the last add/commit and change the first commit message?

I was looking at the git reset, git revert, git undo commands but I don't want to screw up my repo with a guess

EDIT: Found out how to do it: http://www.gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html

Body:
If you already commited your second change, reset it first:

git reset HEAD^

Now your HEAD is at the first commit, and the content of your local files is unchanged.

git add <the file(s) for the second bug fix>
git commit --amend -m'bug fixes'

If all tracked and changed file are to be included for the second bug fix, you can run this instead, as usual:

git commit -a --amend

Amending the commit is exactly this:

adds the changes in index to the previous commit (therefore the need for git add, or -a)

allows you to change your commit message

Be careful, though: if you have distributed the first commit, other people's repo will get strange. You should not change a commit that someone else has fetched.

You could also probably use git merge --squash, which feels more logical but not necessarily easier. Use it to merge a branch containing your two commits, unto the previous commit.

Squashing works with git rebase as well.


问:
String substring error
Question:

```<code>Input:-gandhi                      output:- Gandhi
Input:-mahatma gandhi              output:- M. Gandhi
Input:-Mohndas Karamchand ganDhi   output:- M. K. Gandhi
</code>```

Answer:

```<code>public class Chef_NITIKA {

    static Scanner scan=new Scanner(System.in);

    public static void main(String[] args) {
        String name=    myString();
        System.out.println("nam is :"+name);
        mySformatter(name);

    }

    private static void mySformatter(String name) {
           int count=0;
          for(char c:name.toCharArray()){
              if(c==' '){
                  count+=1;
              }
          }
          System.out.println(count+" blank spaces");
          if(count==0){
              char ch=name.charAt(0);
              name=Character.toUpperCase(ch)+name.substring(1);
              System.out.println("nam is :"+name);
          }
          else if(count==1){
              char ch=name.charAt(0);
             name= name.replace(' ', '.');
             String subname=name.substring(name.indexOf(".")+1);
             char c=subname.charAt(0);
             subname=Character.toUpperCase(c)+subname.substring(1);
             name=Character.toUpperCase(ch)+"."+subname;
              System.out.println("nam is :"+name);
          }
          else if(count==2){
              char ch=name.charAt(0);
            // name= name.replace(' ', '.');
             String subname=name.substring(name.indexOf(" ")+1);
             System.out.println(subname);
             String subsubname=subname.substring(name.indexOf(" "));
             System.out.println(subsubname);
             char c=subname.charAt(0);
             char c1=subsubname.charAt(0);
             subname=Character.toUpperCase(c)+subname.substring(1);
             name = Character.toUpperCase(ch)+"."+Character.toUpperCase(c)+"."+Character.toUpperCase(c1)+subsubname.substring(1);
              System.out.println("nam is :"+name);
          }
    }

    private static String myString() {
       System.out.println("enter the string");
       String s=scan.nextLine();
       StringBuffer name=new StringBuffer();
     //  name.append(s);
       return s;
    }
}
</code>```

I am not getting the desired output when i type "abc cde fgh" i get the output as A.C..fgh

Is there any efficient way to solve this problem?

undesired output:-

```<code>enter the string
iam writing onStack
nam is :iam writing onStack
2 blank spaces
writing onStack
ing onStack
nam is :I.W.Ing onStack
</code>```

I want the output as I.W.OnStack

答:
Just split the name into components and then form the abbreviations you want:

```<code>public static String getName(String input) {
    String[] names = input.split("\\s+");
    String output = "";

    // replace 1st through second to last names with capitalized 1st letter
    for (int i=names.length; i > 1; --i) {
        output += names[names.length - i].substring(0, 1).toUpperCase() + ". ";
    }

    // append full last name, first letter capitalized, rest lower case
    output += names[names.length - 1].substring(0, 1).toUpperCase()
           + names[names.length - 1].substring(1).toLowerCase();

    return output;
}

public static void main(String[] args) {
    System.out.println(getName("gandhi"));
    System.out.println(getName("mahatma gandhi"));
    System.out.println(getName("Mohndas Karamchand ganDhi"));
}
</code>```

Output:

```<code>Gandhi
M. Gandhi
M. K. Gandhi
</code>```

Demo here:

Rextester

Update:

Here is a link to a demo where I have corrected your original code, at least partially.  The issue was the following line:

```<code>String subsubname = subname.substring(name.indexOf(" "));
</code>```

which I changed to this:

```<code>String subsubname = subname.substring(subname.indexOf(" ") + 1);
</code>```

You were not correctly identifying the first character of the third portion of the name.  This being said, your current approach is verbose, hard to read, and inflexible.  In practice, you would probably want to use a leaner approach to this problem.

Title: String substring error

Body:
Question:

Input:-gandhi                      output:- Gandhi
Input:-mahatma gandhi              output:- M. Gandhi
Input:-Mohndas Karamchand ganDhi   output:- M. K. Gandhi

Answer:

public class Chef_NITIKA {

    static Scanner scan=new Scanner(System.in);

    public static void main(String[] args) {
        String name=    myString();
        System.out.println("nam is :"+name);
        mySformatter(name);

    }

    private static void mySformatter(String name) {
           int count=0;
          for(char c:name.toCharArray()){
              if(c==' '){
                  count+=1;
              }
          }
          System.out.println(count+" blank spaces");
          if(count==0){
              char ch=name.charAt(0);
              name=Character.toUpperCase(ch)+name.substring(1);
              System.out.println("nam is :"+name);
          }
          else if(count==1){
              char ch=name.charAt(0);
             name= name.replace(' ', '.');
             String subname=name.substring(name.indexOf(".")+1);
             char c=subname.charAt(0);
             subname=Character.toUpperCase(c)+subname.substring(1);
             name=Character.toUpperCase(ch)+"."+subname;
              System.out.println("nam is :"+name);
          }
          else if(count==2){
              char ch=name.charAt(0);
            // name= name.replace(' ', '.');
             String subname=name.substring(name.indexOf(" ")+1);
             System.out.println(subname);
             String subsubname=subname.substring(name.indexOf(" "));
             System.out.println(subsubname);
             char c=subname.charAt(0);
             char c1=subsubname.charAt(0);
             subname=Character.toUpperCase(c)+subname.substring(1);
             name = Character.toUpperCase(ch)+"."+Character.toUpperCase(c)+"."+Character.toUpperCase(c1)+subsubname.substring(1);
              System.out.println("nam is :"+name);
          }
    }

    private static String myString() {
       System.out.println("enter the string");
       String s=scan.nextLine();
       StringBuffer name=new StringBuffer();
     //  name.append(s);
       return s;
    }
}

I am not getting the desired output when i type "abc cde fgh" i get the output as A.C..fgh

Is there any efficient way to solve this problem?

undesired output:-

enter the string
iam writing onStack
nam is :iam writing onStack
2 blank spaces
writing onStack
ing onStack
nam is :I.W.Ing onStack

I want the output as I.W.OnStack

Body:
Just split the name into components and then form the abbreviations you want:

public static String getName(String input) {
    String[] names = input.split("\\s+");
    String output = "";

    // replace 1st through second to last names with capitalized 1st letter
    for (int i=names.length; i > 1; --i) {
        output += names[names.length - i].substring(0, 1).toUpperCase() + ". ";
    }

    // append full last name, first letter capitalized, rest lower case
    output += names[names.length - 1].substring(0, 1).toUpperCase()
           + names[names.length - 1].substring(1).toLowerCase();

    return output;
}

public static void main(String[] args) {
    System.out.println(getName("gandhi"));
    System.out.println(getName("mahatma gandhi"));
    System.out.println(getName("Mohndas Karamchand ganDhi"));
}

Output:

Gandhi
M. Gandhi
M. K. Gandhi

Demo here:

Rextester

Update:

Here is a link to a demo where I have corrected your original code, at least partially.  The issue was the following line:

String subsubname = subname.substring(name.indexOf(" "));

which I changed to this:

String subsubname = subname.substring(subname.indexOf(" ") + 1);

You were not correctly identifying the first character of the third portion of the name.  This being said, your current approach is verbose, hard to read, and inflexible.  In practice, you would probably want to use a leaner approach to this problem.


问:
Formula in worksheet and VBA works differently
Cell A1 contains the number 25, which is right-aligned, implying it's a number, not text.

D1 contains the formula:

="" & A1

The 25 in D1 is left-aligned, implying it's text. That is confirmed by the following formula, which returns 1:

=IF(D1="25",1,0)

The following VBA code puts 25 in F1 but the 25 is right-aligned and the IF test returns 0:

```<code>Range("F1") = "" & Range("A1")
</code>```

Any explanation for the discrepancy?

E1 contains the following formula which gives a left-aligned 25 and the IF test returns 1:

TEXT(A1,"0")

However, the following code gives a right-aligned 25 and the IF test returns 0:

```<code>Range("F1") = Application.WorksheetFunction.Text(Range("A1"), "0")
</code>```

Not that I have to use the TEXT function. I just wonder why it works differently than when in a worksheet.

Any rule that tells when or what worksheet functions won't work in VBA code, or more precisely, will give different results than when in worksheet?

答:
You simply get the wrong idea of what is a number in Excel.

in general ALL input is a string. Also writing "25" in a cell.
However: If possible, Excel will convert all inputs to a numerical value if possible. Also for dates and times.

To prevent this, you simply insert a ' in front of your "text" in the cell.

The confusing part for you is the different behavior for formulas.
A formula will always output a "result" AND the "data type".

So =1+1 will be numeric as the last action was math.
=Left(1+1,1) will be text as the last action was text-based.

For =A1 it will simply copy the type. If there is a formula, then this will be the same. But if there is a "direct input" it will always try to convert to numerical and only be text if it can't be converted or if it starts with a leading ' (A1 itself does this already).

As a result: If there is a plain 25 in the cell, it will always be "numerical" no matter "how" you input the 25.

For newer Excel there is only one exception: if the cell formatting is text prior to entering a number, it will be treated as text (no converting). This does not apply if you change the formatting later.

Simple test:

enter 25 in A1 (formatting general)

enter =ISNUMBER(A1) in A2 (will be TRUE)

set formatting for A1 to "text" (A2 will still be TRUE)

enter 25 in A1 (now A2 will become FALSE)

This may fail (Excel confuses itself sometimes here). Try it with a new sheet. ;)

Hopefully you understood the fault in your logic ;)

Body:
Cell A1 contains the number 25, which is right-aligned, implying it's a number, not text.

D1 contains the formula:

="" & A1

The 25 in D1 is left-aligned, implying it's text. That is confirmed by the following formula, which returns 1:

=IF(D1="25",1,0)

The following VBA code puts 25 in F1 but the 25 is right-aligned and the IF test returns 0:

Range("F1") = "" & Range("A1")

Any explanation for the discrepancy?

E1 contains the following formula which gives a left-aligned 25 and the IF test returns 1:

TEXT(A1,"0")

However, the following code gives a right-aligned 25 and the IF test returns 0:

Range("F1") = Application.WorksheetFunction.Text(Range("A1"), "0")

Not that I have to use the TEXT function. I just wonder why it works differently than when in a worksheet.

Any rule that tells when or what worksheet functions won't work in VBA code, or more precisely, will give different results than when in worksheet?


问:
Where cookies are stored in system?
If i use Response.Cookies["test"].Value ="Hi"; where are cookie stored in system?

Can i check Cookies["test"] value in my pc because cookies are stored in text format.

I am using VS 2008. Operating system is Windows 7.

I have tried to find in Google but not getting the exact answer. Please help to sort out this problem.

答:
On Windows 10, I press Win+R and type shell:Cookies to open the cookies folder.

it's a hidden folder, the path is

C:\Users\admin\AppData\Local\Microsoft\Windows\INetCookies

Title: Where cookies are stored in system?


问:
importing numpy in hackerrank competitions
I want to use numpy module for solving problems on hackerrank. But, when I imported numpy, it gave me the following error.

ImportError: No module named 'numpy'.

I understand that this might be a very trivial question. But, I am a beginner in programming. Any help is highly appreciated.

答:
I have run into the same issue on HackerRank. A number of their challenges do support NumPy--indeed, a handful require it. Either import numpy or the idiomatic import numpy as np will work just fine on those.

I believe you're simply trying to use numpy where they don't want you to. Because it's not part of the standard library, HackerRank would need to intentionally provide it. Where they do not, you will need to substitute lower-level, non-numpy code as a result.


问:
C# equivalent of C++ std::string find_first_not_of and find_last_not_of
IndexOf, IndexOfAny and LastIndexOf, LastIndexOfAny dont seem to do these (or maybe they do). I'm looking for the equialent of std::string's find_first_not_of and find_last_not_of. I'm thinking about creating an extension class but I'm not sure if C# already provides this functionality.

答:
If the use of LINQ is acceptable, you can call the First() and Last() methods with the appropriate predicate.

For instance, if you want the first and last characters that aren't vowels:

```<code>string vowels = "aeiouy";
char first = yourString.First(ch => vowels.IndexOf(ch) < 0);
char last = yourString.Last(ch => vowels.IndexOf(ch) < 0);
</code>```

EDIT: The above will return the characters, not their indexes. In order to do that, you can project the indexes using the Select() method, but things will get hairy since we need to return -1 if no character matches:

```<code>int firstIndex = (yourString.Select(
        (ch, i) => new { Character = ch, Index = i }
    ).First(obj => vowels.IndexOf(obj.Character) < 0)
    ?? new { Character = '\0', Index = -1 }).Index;

int lastIndex = (yourString.Select(
        (ch, i) => new { Character = ch, Index = i }
    ).Last(obj => vowels.IndexOf(obj.Character) < 0)
    ?? new { Character = '\0', Index = -1 }).Index;
</code>```

Alternatively, here's a less complicated solution based on @abatishchev's answer:

```<code>string vowels = "aeiouy";
int firstIndex = yourString.IndexOf(yourString.First(
    ch => vowels.IndexOf(ch) < 0));
int lastIndex = yourString.LastIndexOf(yourString.Last(
    ch => vowels.IndexOf(ch) < 0));
</code>```

Body:
If the use of LINQ is acceptable, you can call the First() and Last() methods with the appropriate predicate.

For instance, if you want the first and last characters that aren't vowels:

string vowels = "aeiouy";
char first = yourString.First(ch => vowels.IndexOf(ch) < 0);
char last = yourString.Last(ch => vowels.IndexOf(ch) < 0);

EDIT: The above will return the characters, not their indexes. In order to do that, you can project the indexes using the Select() method, but things will get hairy since we need to return -1 if no character matches:

int firstIndex = (yourString.Select(
        (ch, i) => new { Character = ch, Index = i }
    ).First(obj => vowels.IndexOf(obj.Character) < 0)
    ?? new { Character = '\0', Index = -1 }).Index;

int lastIndex = (yourString.Select(
        (ch, i) => new { Character = ch, Index = i }
    ).Last(obj => vowels.IndexOf(obj.Character) < 0)
    ?? new { Character = '\0', Index = -1 }).Index;

Alternatively, here's a less complicated solution based on @abatishchev's answer:

string vowels = "aeiouy";
int firstIndex = yourString.IndexOf(yourString.First(
    ch => vowels.IndexOf(ch) < 0));
int lastIndex = yourString.LastIndexOf(yourString.Last(
    ch => vowels.IndexOf(ch) < 0));


答:
You wrote "Employee.empCount()". Remember, "()" this is used to call functions.
Like you can do "Employee.displayCount()", because displayCount() is a function.
But to access variables, simply do like this:</p>

```<code>print "Total Employee %d" % Employee.empCount
</code>```

Title: Python Showing:- TypeError: 'int' object is not callable in python While Trying to Run Code

Body:
You wrote "Employee.empCount()". Remember, "()" this is used to call functions.
Like you can do "Employee.displayCount()", because displayCount() is a function.
But to access variables, simply do like this:

print "Total Employee %d" % Employee.empCount


问:
Samza equivalent of Kafka Consumer - Manual Offset Control (enable.auto.commit = false)
We have Samza tasks which reads messages from Kafka Output stream but if there is any retryable failure while processing the message then i would want my Samza task to read the same message again and reprocess it. And after successfully processing the message acknowledge it for checkpointing.

Is there a way to manually control the checkpoint(just like what Kafka Consumer provides "Manual Offset Control" by setting enable.auto.commit to false : https://kafka.apache.org/0100/javadoc/index.html?org/apache/kafka/clients/consumer/KafkaConsumer.html )

I came across this doc https://samza.apache.org/learn/documentation/0.13/jobs/reprocessing.html which talks about reprocessing previously processed data but it is not offering any acknowledge based checkpoint control.

Found relate issues https://github.com/zendesk/ruby-kafka/issues/304

答:
Sid,

You can perform manual commit from your StreamTask. If you set task.commit.ms is set to -1, then auto-commit in the Samza job is disabled. In such a case, the task should manually trigger a commit by invoking taskCoordinator.commit() when you are ready to acknowledge.

You can find documentation regarding checkpointing here - http://samza.apache.org/learn/documentation/0.13/container/checkpointing.html.
I believe documentation is insufficient in the website as it doesn't elaborately cover the manual commit scenario. The configuration table also needs to be updated so that it is obvious to the user that manual commit is supported.

HTH :)


问:
Python selecting row from second dataframe based on complex criteria
I have two dataframes, one with some purchasing data, and one with a weekly calendar, e.g.

```<code>df1:
purchased_at  product_id  cost
01-01-2017    1           £10
01-01-2017    2           £8
09-01-2017    1           £10
18-01-2017    3           £12

df2:
week_no  week_start  week_end
1        31-12-2016  06-01-2017
2        07-01-2017  13-01-2017
3        14-01-2017  20-01-2017
</code>```

I want to use data from the two to add a 'week_no' column to df1, which is selected from df2 based on where the 'purchased_at' date in df1 falls between the 'week_start' and 'week_end' dates in df2, i.e.

```<code>df1:
purchased_at  product_id  cost  week_no
01-01-2017    1           £10   1
01-01-2017    2           £8    1
09-01-2017    1           £10   2
18-01-2017    3           £12   3
</code>```

I've searched but I've not been able to find an example where the data is being pulled from a second dataframe using comparisons between the two, and I've been unable to correctly apply any examples I've found, e.g.

```<code>df1.loc[(df1['purchased_at'] < df2['week_end']) &
        (df1['purchased_at'] > df2['week_start']), df2['week_no']
</code>```

was unsuccessful, with the ValueError 'can only compare identically-labeled Series objects'

Could anyone help with this problem, or I'm open to suggestions if there is a better way to achieve the same outcome.

edit to add further detail of df1

df1 full dataframe headers

```<code>purchased_at  purchase_id  product_id  product_name  transaction_id  account_number  cost
01-01-2017    1            1           A             1               AA001           £10
01-01-2017    2            2           B             1               AA001           £8
02-01-2017    3            1           A             2               AA008           £10
03-01-2017    4            3           C             3               AB040           £12
...
09-01-2017   12            1           A             10              AB102           £10
09-01-2017   13            2           B             11              AB102           £8
...
18-01-2017   20            3           C             15              AA001           £12
</code>```

So the purchase_id increases incrementally with each row, the product_id and product_name have a 1:1 relationship, the transaction_id also increases incrementally, but there can be multiple purchases within a transaction.

答:
If your dataframes are to big you can use this trick.

Do a full cartisian product join of all records to all records:

```<code>df_out = pd.merge(df1.assign(key=1),df2.assign(key=1),on='key')
</code>```

Next filter out those records that do not match criteria in this case, where purchased_at is not between week_start and week_end

```<code>(df_out.query('week_start < purchased_at < week_end')
       .drop(['key','week_start','week_end'], axis=1))
</code>```

Output:

```<code>   purchased_at  product_id cost  week_no
0    2017-01-01           1  £10        1
3    2017-01-01           2   £8        1
7    2017-01-09           1  £10        2
11   2017-01-18           3  £12        3
</code>```

If you do have large dataframes then you can use this numpy method as proposed by PiRSquared.

```<code>a = df1.purchased_at.values

bh = df2.week_end.values

bl = df2.week_start.values

i, j = np.where((a[:, None] >= bl) & (a[:, None] <= bh))

pd.DataFrame(
    np.column_stack([df1.values[i], df2.values[j]]),
    columns=df1.columns.append(df2.columns)
).drop(['week_start','week_end'],axis=1)
</code>```

Output:

```<code>          purchased_at product_id cost week_no
0  2017-01-01 00:00:00          1  £10       1
1  2017-01-01 00:00:00          2   £8       1
2  2017-01-09 00:00:00          1  £10       2
3  2017-01-18 00:00:00          3  £12       3
</code>```

Body:
I have two dataframes, one with some purchasing data, and one with a weekly calendar, e.g.

df1:
purchased_at  product_id  cost
01-01-2017    1           £10
01-01-2017    2           £8
09-01-2017    1           £10
18-01-2017    3           £12

df2:
week_no  week_start  week_end
1        31-12-2016  06-01-2017
2        07-01-2017  13-01-2017
3        14-01-2017  20-01-2017

I want to use data from the two to add a 'week_no' column to df1, which is selected from df2 based on where the 'purchased_at' date in df1 falls between the 'week_start' and 'week_end' dates in df2, i.e.

df1:
purchased_at  product_id  cost  week_no
01-01-2017    1           £10   1
01-01-2017    2           £8    1
09-01-2017    1           £10   2
18-01-2017    3           £12   3

I've searched but I've not been able to find an example where the data is being pulled from a second dataframe using comparisons between the two, and I've been unable to correctly apply any examples I've found, e.g.

df1.loc[(df1['purchased_at'] < df2['week_end']) &
        (df1['purchased_at'] > df2['week_start']), df2['week_no']

was unsuccessful, with the ValueError 'can only compare identically-labeled Series objects'

Could anyone help with this problem, or I'm open to suggestions if there is a better way to achieve the same outcome.

edit to add further detail of df1

df1 full dataframe headers

purchased_at  purchase_id  product_id  product_name  transaction_id  account_number  cost
01-01-2017    1            1           A             1               AA001           £10
01-01-2017    2            2           B             1               AA001           £8
02-01-2017    3            1           A             2               AA008           £10
03-01-2017    4            3           C             3               AB040           £12
...
09-01-2017   12            1           A             10              AB102           £10
09-01-2017   13            2           B             11              AB102           £8
...
18-01-2017   20            3           C             15              AA001           £12

So the purchase_id increases incrementally with each row, the product_id and product_name have a 1:1 relationship, the transaction_id also increases incrementally, but there can be multiple purchases within a transaction.

Body:
If your dataframes are to big you can use this trick.

Do a full cartisian product join of all records to all records:

df_out = pd.merge(df1.assign(key=1),df2.assign(key=1),on='key')

Next filter out those records that do not match criteria in this case, where purchased_at is not between week_start and week_end

(df_out.query('week_start < purchased_at < week_end')
       .drop(['key','week_start','week_end'], axis=1))

Output:

   purchased_at  product_id cost  week_no
0    2017-01-01           1  £10        1
3    2017-01-01           2   £8        1
7    2017-01-09           1  £10        2
11   2017-01-18           3  £12        3

If you do have large dataframes then you can use this numpy method as proposed by PiRSquared.

a = df1.purchased_at.values

bh = df2.week_end.values

bl = df2.week_start.values

i, j = np.where((a[:, None] >= bl) & (a[:, None] <= bh))

pd.DataFrame(
    np.column_stack([df1.values[i], df2.values[j]]),
    columns=df1.columns.append(df2.columns)
).drop(['week_start','week_end'],axis=1)

Output:

          purchased_at product_id cost week_no
0  2017-01-01 00:00:00          1  £10       1
1  2017-01-01 00:00:00          2   £8       1
2  2017-01-09 00:00:00          1  £10       2
3  2017-01-18 00:00:00          3  £12       3


问:
Java Websockets - confused by the different options
I've been working on writing a Web Socket server in Java and this point has confused me for a while now. On GitHub there's this library by TooTallNate that's a "barebones WebSocket client and server implementation in 100% Java": https://github.com/TooTallNate/Java-WebSocket

It has a ton of stars, and is actively developed.

But then it seems like Java already has websocket functionality in the main library? https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_a_WebSocket_server_in_Java

And there's also things like Jetty's WebSocket stuff: http://www.eclipse.org/jetty/documentation/9.4.x/jetty-websocket-server-api.html

There's also Netty which seems to have WebSocket stuff too.

So what exactly is the difference between these? Is it a question of simplicity? Or performance? Or are they totally separate things? If I need low-latency high-frequency sending of 5-10 kb messages, is there one option that would be most appropriate?

答:
WebSocket is a technology providing for bi-directional, full-duplex communications channels, over a single Transmission Control Protocol (TCP) socket.

This is standardised by the IETF as RFC 6455.

The three links that you provided (TooTallNate, Mozilla, Jetty) are just the implementation of that websocket standards/protocol.

Similarly Netty also has Websocket implemenation.

Regarding which one to choose:

Look at it like, HTTP standard.

All Web servers (Tomcat, weblogic, Jetty, Apache HTTP etc) implement the same HTTP standard but which one to choose depends on many factors like:

How efficient is the implementation?

Is it configuration friendly?

Memory/CPU it consumes

etc

So you may want to conduct some performance tests and see which one fits for your requirement.


问:
C# ASP.NET Slider JavaScript react differently in HTML page and ASPX Web Site
needed help again,
I found some template online which I can use, I tried to copy it and put inside my html, it works, however the slider had some problem.

If its on .HTML format, the Slider works perfectly fine like this, it reaches until the end of conversation.

But if its in the .ASPX file, it will looks like this

It slides out of the container, does anyone know what cause the problem?

Btw, the code is exactly the same, same css, bootstrap and JS
Thanks

答:
In your ASPX page when you apply the runat=server can cause the id of your control to change in the browser.

For example on a regular html generic control you may have:

```<code><input id='mybutton' type='button' value='Go' />
</code>```

When you apply the runat=server to a control that is nested inside of a parent control, such as a master page or a user control the ID that gets generated in the web browser can change:

For example, when using a master control, content is typically place in a content placeholder. If the above control was placed like this:

```<code><asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server"><input id='mybutton' type='button' value='Go' runat='server' /> </asp:content>
</code>```

The ASP.NET will render the control in the browser something like this:

```<code><input id='MainContent_mybutton' type='button' value='Go' runat='server'  />
</code>```

The name attribute of the control can also be changed.

This is by design so ASP.NET can keep track of your controls and make sure they are in the correct hierarchy of a pages control collection. The ID and name are also use to populate objects and raise event handlers for control methods.

You can override the changing of the id by setting ClientIDMode="Static" on the control, but take care that you don't end up with multiple controls with the same id.

You will need to make sure that the ID matches those set in any CSS or JavaScript. A common method to handle this is to leave the generated client id and reference it in JavaScript like this:

```<code>var mybuttonId = '<%= mybutton.ClientID %>';
</code>```

You also need to be careful that any skins or themes you have set in your application don't override the default styles of your controls.

To fix your issue, compare the rendered normal HTML of your controls to those rendered by ASP.NET. The either address ASP.NET changing the ID/NAME/STYLE/CLASS attributes or update your JavaScript and CSS to use the names generated by your aspx page.

Body:
In your ASPX page when you apply the runat=server can cause the id of your control to change in the browser.

For example on a regular html generic control you may have:

<input id='mybutton' type='button' value='Go' />

When you apply the runat=server to a control that is nested inside of a parent control, such as a master page or a user control the ID that gets generated in the web browser can change:

For example, when using a master control, content is typically place in a content placeholder. If the above control was placed like this:

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server"><input id='mybutton' type='button' value='Go' runat='server' /> </asp:content>

The ASP.NET will render the control in the browser something like this:

<input id='MainContent_mybutton' type='button' value='Go' runat='server'  />

The name attribute of the control can also be changed.

This is by design so ASP.NET can keep track of your controls and make sure they are in the correct hierarchy of a pages control collection. The ID and name are also use to populate objects and raise event handlers for control methods.

You can override the changing of the id by setting ClientIDMode="Static" on the control, but take care that you don't end up with multiple controls with the same id.

You will need to make sure that the ID matches those set in any CSS or JavaScript. A common method to handle this is to leave the generated client id and reference it in JavaScript like this:

var mybuttonId = '<%= mybutton.ClientID %>';

You also need to be careful that any skins or themes you have set in your application don't override the default styles of your controls.

To fix your issue, compare the rendered normal HTML of your controls to those rendered by ASP.NET. The either address ASP.NET changing the ID/NAME/STYLE/CLASS attributes or update your JavaScript and CSS to use the names generated by your aspx page.


问:
How to align vertical textview and editText in Linearlayout in android
Currently, I am trying to code a textview and a edittext to align vertically using Linearlayout in android studio. I tried setting out the layout gravity and the other element but I cannot achieve what I want currently this is my code.

```<code>LinearLayout params3 = new LinearLayout(this);
        params3.setOrientation(LinearLayout.VERTICAL);
        params3.setGravity(Gravity.CENTER_VERTICAL);

        LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        params2.weight = 35;
        params3.setLayoutParams(params2);
        params2.height = convertDiptoPix(80,context);
        //params2.leftMargin = convertDiptoPix(5,context);

        TextView textView1 = new TextView(this);
        textView1.setId(View.generateViewId());
        textView1.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
        textView1.setPadding(0,convertDiptoPix(1,context),0,convertDiptoPix(3,context));
        textView1.setText("Receipt");
        textView1.setTextColor(Color.parseColor("#000000"));
        //textView1.setLayoutParams(params2);
        textView1.setTextSize(convertDiptoPix(13,context));

        EditTextIME editTextIME = new EditTextIME(this);
        editTextIME.setId(View.generateViewId());
        //editTextIME.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
        //editTextIME.setMinimumHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
        editTextIME.setGravity(Gravity.BOTTOM | Gravity.CENTER_VERTICAL);
        //editTextIME.setLayoutParams(params2);
        editTextIME.setFocusableInTouchMode(true);
        editTextIME.setKeyListener(DigitsKeyListener.getInstance("abcdefghijklmnopqrstuvwxyzöäüßñéúíóáèùòìàâãåæçëêìíîïôõûýABCDEFGHIJKLMNOPQRSTUVWXYZÖÄÜÕÔÒÔÓÙÚÛÝÑÇÈÉÊËÌÍÎÏÆÅÄÃÂÁÀØ01234567890()&*$%#!+-:;,._?¿/><[]{}|\\^ "));
        editTextIME.setHint("Notes");
        editTextIME.setInputType(InputType.TYPE_CLASS_TEXT);
        editTextIME.setHorizontallyScrolling(true);
        editTextIME.setTextSize(convertDiptoPix(13,context));
</code>```

is anyone had anyone tried to code like vertical align in android studio? Can you share your idea?

答:
You can try this,</p>

```<code>        LinearLayout parent = new LinearLayout(context);

        parent.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
        parent.setOrientation(LinearLayout.VERTICAL);

        LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

        TextView textView1 = new TextView(this);
        textView1.setLayoutParams(params2);
        textView1.setId(View.generateViewId());
        textView1.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
        textView1.setText("Receipt");
        textView1.setTextColor(Color.parseColor("#000000"));

        EditText editTextIME = new EditText(this);
        editTextIME.setId(View.generateViewId());
        editTextIME.setGravity(Gravity.BOTTOM | Gravity.CENTER_VERTICAL);
        editTextIME.setLayoutParams(params2);
        editTextIME.setFocusableInTouchMode(true);
        editTextIME.setKeyListener(DigitsKeyListener.getInstance("abcdefghijklmnopqrstuvwxyzöäüßñéúíóáèùòìàâãåæçëêìíîïôõûýABCDEFGHIJKLMNOPQRSTUVWXYZÖÄÜÕÔÒÔÓÙÚÛÝÑÇÈÉÊËÌÍÎÏÆÅÄÃÂÁÀØ01234567890()&*$%#!+-:;,._?¿/><[]{}|\\^ "));
        editTextIME.setHint("Notes");
        editTextIME.setInputType(InputType.TYPE_CLASS_TEXT);
        editTextIME.setHorizontallyScrolling(true);
//        editTextIME.setTextSize(convertDiptoPix(13,context));

        parent.addView(textView1);
        parent.addView(editTextIME);
</code>```

Body:
Currently, I am trying to code a textview and a edittext to align vertically using Linearlayout in android studio. I tried setting out the layout gravity and the other element but I cannot achieve what I want currently this is my code.

LinearLayout params3 = new LinearLayout(this);
        params3.setOrientation(LinearLayout.VERTICAL);
        params3.setGravity(Gravity.CENTER_VERTICAL);

        LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        params2.weight = 35;
        params3.setLayoutParams(params2);
        params2.height = convertDiptoPix(80,context);
        //params2.leftMargin = convertDiptoPix(5,context);

        TextView textView1 = new TextView(this);
        textView1.setId(View.generateViewId());
        textView1.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
        textView1.setPadding(0,convertDiptoPix(1,context),0,convertDiptoPix(3,context));
        textView1.setText("Receipt");
        textView1.setTextColor(Color.parseColor("#000000"));
        //textView1.setLayoutParams(params2);
        textView1.setTextSize(convertDiptoPix(13,context));

        EditTextIME editTextIME = new EditTextIME(this);
        editTextIME.setId(View.generateViewId());
        //editTextIME.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
        //editTextIME.setMinimumHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
        editTextIME.setGravity(Gravity.BOTTOM | Gravity.CENTER_VERTICAL);
        //editTextIME.setLayoutParams(params2);
        editTextIME.setFocusableInTouchMode(true);
        editTextIME.setKeyListener(DigitsKeyListener.getInstance("abcdefghijklmnopqrstuvwxyzöäüßñéúíóáèùòìàâãåæçëêìíîïôõûýABCDEFGHIJKLMNOPQRSTUVWXYZÖÄÜÕÔÒÔÓÙÚÛÝÑÇÈÉÊËÌÍÎÏÆÅÄÃÂÁÀØ01234567890()&*$%#!+-:;,._?¿/><[]{}|\\^ "));
        editTextIME.setHint("Notes");
        editTextIME.setInputType(InputType.TYPE_CLASS_TEXT);
        editTextIME.setHorizontallyScrolling(true);
        editTextIME.setTextSize(convertDiptoPix(13,context));

is anyone had anyone tried to code like vertical align in android studio? Can you share your idea?

Body:
You can try this,

        LinearLayout parent = new LinearLayout(context);

        parent.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
        parent.setOrientation(LinearLayout.VERTICAL);

        LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

        TextView textView1 = new TextView(this);
        textView1.setLayoutParams(params2);
        textView1.setId(View.generateViewId());
        textView1.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
        textView1.setText("Receipt");
        textView1.setTextColor(Color.parseColor("#000000"));

        EditText editTextIME = new EditText(this);
        editTextIME.setId(View.generateViewId());
        editTextIME.setGravity(Gravity.BOTTOM | Gravity.CENTER_VERTICAL);
        editTextIME.setLayoutParams(params2);
        editTextIME.setFocusableInTouchMode(true);
        editTextIME.setKeyListener(DigitsKeyListener.getInstance("abcdefghijklmnopqrstuvwxyzöäüßñéúíóáèùòìàâãåæçëêìíîïôõûýABCDEFGHIJKLMNOPQRSTUVWXYZÖÄÜÕÔÒÔÓÙÚÛÝÑÇÈÉÊËÌÍÎÏÆÅÄÃÂÁÀØ01234567890()&amp;*$%#!+-:;,._?¿/&gt;&lt;[]{}|\\^ "));
        editTextIME.setHint("Notes");
        editTextIME.setInputType(InputType.TYPE_CLASS_TEXT);
        editTextIME.setHorizontallyScrolling(true);
//        editTextIME.setTextSize(convertDiptoPix(13,context));

        parent.addView(textView1);
        parent.addView(editTextIME);


问:
i make pagination but it cant limit post per page codeigniter
this is my controller , i use $config['per_page'] to limit my post but it not work still all my database show in it,

```<code>function index()

{

    $jumlah_data = $this->m_berita->jumlah_data();

    $config['base_url'] = base_url().'berita/index/';
    $config['total_rows'] = $jumlah_data;
    $config['per_page'] = 2;
    $from = $this->uri->segment(3);

    $this->pagination->initialize($config);

    $halaman['berita'] = $this->m_berita->data($config['per_page'],$from);

    $urutan['berita'] = $this->db->order_by("id", "desc");

    $data['berita'] = $this->m_berita->data_berita()->result();

    $this->load->view('artikel', $data, $urutan, $halaman);

}
</code>```

my model

```<code>class m_berita extends CI_Model{

public function __construct()

    {
        $this->load->database();
    }

    public function data_berita(){
        return $this->db->get('berita');

    }

    public function data($number,$offset){
        return $query = $this->db->get('berita',$number,$offset)->result();
    }

    function jumlah_data(){
        return $this->db->get('berita')->num_rows();
    }
</code>```

and this my view

```<code>    <?php
$no = $this->uri->segment('3') + 1;
foreach ($berita as $u) {
?>

<?php $no++;?>
<div class="container">
<?php $u->id; ?>
    <h4> <?php echo $u->judul; ?> </h4>
    <span style="margin-bottom: 5%;" class="image left 3u"><img class="fit" src="<?php echo base_url('images/').$u->gambar; ?>" alt="" /></span>
    <?php $artikel = $u->isi; $artikel=word_limiter($artikel, 98); ?> <?php echo $artikel;?> <?php echo anchor('berita/tampil_berita/'.$u->id,'Read More'); ?>
</div>

<?php } ?>
<div class="container">
<ul class="pagination">
  <li><?php echo $this->pagination->create_links(); ?></li>
</ul>
</div>
</code>```

答:
change the db function

to

```<code>function jumlah_data(){
    return $this->db->count_all('berita');
}
</code>```

Body:
this is my controller , i use $config['per_page'] to limit my post but it not work still all my database show in it,

function index()

{

    $jumlah_data = $this->m_berita->jumlah_data();

    $config['base_url'] = base_url().'berita/index/';
    $config['total_rows'] = $jumlah_data;
    $config['per_page'] = 2;
    $from = $this->uri->segment(3);

    $this->pagination->initialize($config);

    $halaman['berita'] = $this->m_berita->data($config['per_page'],$from);

    $urutan['berita'] = $this->db->order_by("id", "desc");

    $data['berita'] = $this->m_berita->data_berita()->result();

    $this->load->view('artikel', $data, $urutan, $halaman);

}

my model

class m_berita extends CI_Model{

public function __construct()

    {
        $this->load->database();
    }

    public function data_berita(){
        return $this->db->get('berita');

    }

    public function data($number,$offset){
        return $query = $this->db->get('berita',$number,$offset)->result();
    }

    function jumlah_data(){
        return $this->db->get('berita')->num_rows();
    }

and this my view

    <?php
$no = $this->uri->segment('3') + 1;
foreach ($berita as $u) {
?>

<?php $no++;?>

<?php $u->id; ?>

 <?php echo $u->judul; ?>

    <img class="fit" src="<?php echo base_url('images/').$u->gambar; ?>" alt="" />
    <?php $artikel = $u->isi; $artikel=word_limiter($artikel, 98); ?> <?php echo $artikel;?> <?php echo anchor('berita/tampil_berita/'.$u->id,'Read More'); ?>

<?php } ?>

<?php echo $this->pagination->create_links(); ?>

Body:
change the db function

to

function jumlah_data(){
    return $this->db->count_all('berita');
}


问:
Identifier userName is unresolved (not a static field) <at times>
I am making an object persistent using JDO. I have run code numerous times. At times, i get things persisted without any error. At times, i receive the following errors.

```<code> 1. org.datanucleus.exceptions.NucleusUserException
 2. javax.jdo.JDOUserException
</code>```

I dont understand why it runs successfully sometimes and why it fails sometimes. These happens very randomly.
My application is validating new User during signUp. Here goes my code.

User.java(entity being persisted)

```<code> @Entity
 @PersistenceCapable

 public class User {

@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
public String userName;

@Persistent
private String name, password, city, bikeModel, age;

public User(){

}
public User(String name, String uname, String pswd, String age, String city, String bike){
    this.name=name;
    this.userName=uname;
    this.password=pswd;
    this.age=age;
    this.city=city;
    this.bikeModel=bike;
}

public String getUserName() {
    return userName;
}
//rest of the getters
}
</code>```

Main servlet :

```<code>    //Getting SignUp form values
    String name=req.getParameter("name1");
    String uname=req.getParameter("uname1");
    String pswd=req.getParameter("pswd1");
    String age=req.getParameter("age");
    String city=req.getParameter("city");
    String bike=req.getParameter("bike");

            //PeristenceManager instance
            PersistenceManager pm = PMF.get().getPersistenceManager();

            //Creating instance for persistent entity class
     User newEntry=new User(name,uname,pswd,age,city,bike);

            //Query to match the userName entered in form and that of the dataStore user
    Query q = pm.newQuery(User.class);
    q.setFilter("userName == userNameParam");
    q.declareParameters("String userNameParam");
            try{
      List<User> results = (List<User>) q.execute(uname);
      if (!results.isEmpty()) {
                //if userName is found in DataStore
            resp.sendRedirect("invalidUser.html");
      } else{
             //If userName is not found in dataStore
          pm.makePersistent(newEntry);
          resp.sendRedirect("success.html");
          return;
      }
     }
    finally{

        System.out.println("Finally!");
    }
</code>```

答:
I too had the same error while saving UserSession Object as JDO cannot store non-primitive datatype apart from String,Text and other Numeric Type for enhancement, using objectify we can provide key for non-primitive object and can save the same or we have to convert that object to String in my case converted Map to Sring using json.</p>

```<code>Jul 08, 2017 11:50:41 AM org.datanucleus.enhancer.DataNucleusEnhancer main
SEVERE: DataNucleus Enhancer completed with an error. Please review the enhancer log for full details. Some classes may have been enhanced but some caused errors
Class "net.giffy.domain.UserSession" field "map" has been defined as a Map but the key type is not specified!
org.datanucleus.metadata.InvalidMemberMetaDataException: Class "net.giffy.domain.UserSession" field "map" has been defined as a Map but the key type is not specified!
    at org.datanucleus.metadata.MapMetaData.populate(MapMetaData.java:136)
    at org.datanucleus.metadata.AbstractMemberMetaData.populate(AbstractMemberMetaData.java:949)
    at org.datanucleus.metadata.ClassMetaData.populateMemberMetaData(ClassMetaData.java:543)
    at org.datanucleus.metadata.ClassMetaData.populate(ClassMetaData.java:215)
    at org.datanucleus.metadata.MetaDataManager$1.run(MetaDataManager.java:2699)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.datanucleus.metadata.MetaDataManager.populateAbstractClassMetaData(MetaDataManager.java:2693)
    at org.datanucleus.metadata.MetaDataManager.populateFileMetaData(MetaDataManager.java:2516)
    at org.datanucleus.metadata.MetaDataManager.initialiseFileMetaDataForUse(MetaDataManager.java:1123)
    at org.datanucleus.metadata.MetaDataManager.loadClasses(MetaDataManager.java:543)
    at org.datanucleus.enhancer.DataNucleusEnhancer.getFileMetadataForInput(DataNucleusEnhancer.java:734)
    at org.datanucleus.enhancer.DataNucleusEnhancer.enhance(DataNucleusEnhancer.java:525)
    at org.datanucleus.enhancer.DataNucleusEnhancer.main(DataNucleusEnhancer.java:1258)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.google.appengine.tools.enhancer.Enhancer.execute(Enhancer.java:74)
    at com.google.appengine.tools.enhancer.Enhance.<init>(Enhance.java:71)
    at com.google.appengine.tools.enhancer.Enhance.main(Enhance.java:51)
</code>```

Body:
I am making an object persistent using JDO. I have run code numerous times. At times, i get things persisted without any error. At times, i receive the following errors.

 1. org.datanucleus.exceptions.NucleusUserException
 2. javax.jdo.JDOUserException

I dont understand why it runs successfully sometimes and why it fails sometimes. These happens very randomly.
My application is validating new User during signUp. Here goes my code.

User.java(entity being persisted)

 @Entity
 @PersistenceCapable

 public class User {

@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
public String userName;

@Persistent
private String name, password, city, bikeModel, age;

public User(){

}
public User(String name, String uname, String pswd, String age, String city, String bike){
    this.name=name;
    this.userName=uname;
    this.password=pswd;
    this.age=age;
    this.city=city;
    this.bikeModel=bike;
}

public String getUserName() {
    return userName;
}
//rest of the getters
}

Main servlet :

    //Getting SignUp form values
    String name=req.getParameter("name1");
    String uname=req.getParameter("uname1");
    String pswd=req.getParameter("pswd1");
    String age=req.getParameter("age");
    String city=req.getParameter("city");
    String bike=req.getParameter("bike");

            //PeristenceManager instance
            PersistenceManager pm = PMF.get().getPersistenceManager();

            //Creating instance for persistent entity class
     User newEntry=new User(name,uname,pswd,age,city,bike);

            //Query to match the userName entered in form and that of the dataStore user
    Query q = pm.newQuery(User.class);
    q.setFilter("userName == userNameParam");
    q.declareParameters("String userNameParam");
            try{
      List<User> results = (List<User>) q.execute(uname);
      if (!results.isEmpty()) {
                //if userName is found in DataStore
            resp.sendRedirect("invalidUser.html");
      } else{
             //If userName is not found in dataStore
          pm.makePersistent(newEntry);
          resp.sendRedirect("success.html");
          return;
      }
     }
    finally{

        System.out.println("Finally!");
    }

Body:
I too had the same error while saving UserSession Object as JDO cannot store non-primitive datatype apart from String,Text and other Numeric Type for enhancement, using objectify we can provide key for non-primitive object and can save the same or we have to convert that object to String in my case converted Map to Sring using json.

Jul 08, 2017 11:50:41 AM org.datanucleus.enhancer.DataNucleusEnhancer main
SEVERE: DataNucleus Enhancer completed with an error. Please review the enhancer log for full details. Some classes may have been enhanced but some caused errors
Class "net.giffy.domain.UserSession" field "map" has been defined as a Map but the key type is not specified!
org.datanucleus.metadata.InvalidMemberMetaDataException: Class "net.giffy.domain.UserSession" field "map" has been defined as a Map but the key type is not specified!
    at org.datanucleus.metadata.MapMetaData.populate(MapMetaData.java:136)
    at org.datanucleus.metadata.AbstractMemberMetaData.populate(AbstractMemberMetaData.java:949)
    at org.datanucleus.metadata.ClassMetaData.populateMemberMetaData(ClassMetaData.java:543)
    at org.datanucleus.metadata.ClassMetaData.populate(ClassMetaData.java:215)
    at org.datanucleus.metadata.MetaDataManager$1.run(MetaDataManager.java:2699)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.datanucleus.metadata.MetaDataManager.populateAbstractClassMetaData(MetaDataManager.java:2693)
    at org.datanucleus.metadata.MetaDataManager.populateFileMetaData(MetaDataManager.java:2516)
    at org.datanucleus.metadata.MetaDataManager.initialiseFileMetaDataForUse(MetaDataManager.java:1123)
    at org.datanucleus.metadata.MetaDataManager.loadClasses(MetaDataManager.java:543)
    at org.datanucleus.enhancer.DataNucleusEnhancer.getFileMetadataForInput(DataNucleusEnhancer.java:734)
    at org.datanucleus.enhancer.DataNucleusEnhancer.enhance(DataNucleusEnhancer.java:525)
    at org.datanucleus.enhancer.DataNucleusEnhancer.main(DataNucleusEnhancer.java:1258)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.google.appengine.tools.enhancer.Enhancer.execute(Enhancer.java:74)
    at com.google.appengine.tools.enhancer.Enhance.<init>(Enhance.java:71)
    at com.google.appengine.tools.enhancer.Enhance.main(Enhance.java:51)

ContentLicense: CC BY-SA 4.0


问:
SelectAll Textbox Text
I am using these following code. I want to when I select all text in the textbox it tells me but I don't know why it's not working. please give me some help. Please give some code so that I can use this when I select all text in the textbox text it tells me

```<code>if (textBox1.SelectAll() == true)
        {
            MessageBox.Show("You have selected all text in the textbox");
        }
</code>```

It will tell me: Operator == cannot be applied to operands of type void and bool

答:
I think you should use the GotMouseCapture Event Here the code it works fine for me.</p>

```<code> private void textBox_GotMouseCapture(object sender, MouseEventArgs e)
    {
        textBox.SelectAll();
        textBox.Focus();
    }
</code>```

Title: SelectAll Textbox Text

Body:
I am using these following code. I want to when I select all text in the textbox it tells me but I don't know why it's not working. please give me some help. Please give some code so that I can use this when I select all text in the textbox text it tells me

if (textBox1.SelectAll() == true)
        {
            MessageBox.Show("You have selected all text in the textbox");
        }

It will tell me: Operator == cannot be applied to operands of type void and bool

Body:
I think you should use the GotMouseCapture Event Here the code it works fine for me.

 private void textBox_GotMouseCapture(object sender, MouseEventArgs e)
    {
        textBox.SelectAll();
        textBox.Focus();
    }


问:
force update jQuery fullcalendar, after prop change in React.js
I am struggling with updating jQuery fullcalendar wrapped in React after events prop change.

Here is class containing data & calendar:

```<code>export default class Calendar extends Component {
  constructor(props) {
    super(props);
    this.addEvent = this.addEvent.bind(this);
    this.state = {
      events: [
        {
          title: 'Sometitle',
          date: moment(Date.now()),
          allDay: false,
        },
      ],
    };
  }

  addEvent() {
    const date = moment(Date.now()).add(1, 'hour');
    this.setState({
      events: [].concat(this.state.events, [{
        title: 'Sometitle 1',
        date,
        allDay: false,
      }]),
    });
  }

  render() {
    return (
      <div className="allow-scroll">
        <button onClick={this.addEvent}> Add event</button>
        <EmployeesCalendar events={this.state.events} />
      </div>
    );
  }
}
</code>```

And here is class containing the fullcalendar plugin:

```<code>import React, { Component } from 'react';
import jQuery from 'jquery';

require('fullcalendar');

export default class EmployeesCalendar extends Component {
  constructor(props) {
    super(props);
    this.state = {
      events: props.events,
    };
  }

  componentDidMount() {
    const { fullCalendar } = this;

    jQuery(fullCalendar).fullCalendar({
      events: this.state.events,
    });
  }

  componentWillReceiveProps(nextProps, nextState) {
    const { fullCalendar } = this;
    const { events } = nextState;
    this.setState({
      events: nextProps.events,
    }, () => {
      console.log(this.state.events);
      jQuery(fullCalendar).fullCalendar('refetchEventSources', nextProps.event);
    });
  }

  componentWillUnmount() {
    const { fullCalendar } = this;
    jQuery(fullCalendar).fullCalendar('destroy');
  }

  render() {
    return (
      <div ref={(calendar) => { this.fullCalendar = calendar; }} />
    );
  }
}
</code>```

I have addEvent function that adds new event to array and than I pass it to EmployeesCalendar.

In EmployeesCalendar I update events state in componentWillReceiveProps and than pass it to fullcalendar plugin, forcing to update it. But the fullcalendar never updates.

Any suggestions ?

答:
The refetchEvents method worked for me, but not until I configured events as a function with a callback rather than as an array.

Instead of componentWillReceiveProps, I used componentDidUpdate, which is fired after state or props actually change.  I think that componentWillReceiveProps will work, but it's an earlier event than you need.  It gives you an opportunity to change state, which you don't need to do.

```<code>  componentDidMount() {
    const { fullCalendar } = this;
    jQuery(fullCalendar).fullCalendar({
      events: (start, end, timezone, callback) => {
        callback(this.state.events);
      },
    });
  }

  componentDidUpdate(nextProps, nextState) {
    const { fullCalendar } = this;
    jQuery(fullCalendar).fullCalendar('refetchEvents');
  }
</code>```

According to the FullCalendar doc, "FullCalendar will call this function whenever it needs new event data. This is triggered when the user clicks prev/next or switches views."  It also appears to be triggered when you run refetchEvents.  Maybe rerenderEvents too?  I didn't try that one.

Body:
I am struggling with updating jQuery fullcalendar wrapped in React after events prop change.

Here is class containing data & calendar:

export default class Calendar extends Component {
  constructor(props) {
    super(props);
    this.addEvent = this.addEvent.bind(this);
    this.state = {
      events: [
        {
          title: 'Sometitle',
          date: moment(Date.now()),
          allDay: false,
        },
      ],
    };
  }

  addEvent() {
    const date = moment(Date.now()).add(1, 'hour');
    this.setState({
      events: [].concat(this.state.events, [{
        title: 'Sometitle 1',
        date,
        allDay: false,
      }]),
    });
  }

  render() {
    return (

        <button onClick={this.addEvent}> Add event</button>
        <EmployeesCalendar events={this.state.events} />

    );
  }
}

And here is class containing the fullcalendar plugin:

import React, { Component } from 'react';
import jQuery from 'jquery';

require('fullcalendar');

export default class EmployeesCalendar extends Component {
  constructor(props) {
    super(props);
    this.state = {
      events: props.events,
    };
  }

  componentDidMount() {
    const { fullCalendar } = this;

    jQuery(fullCalendar).fullCalendar({
      events: this.state.events,
    });
  }

  componentWillReceiveProps(nextProps, nextState) {
    const { fullCalendar } = this;
    const { events } = nextState;
    this.setState({
      events: nextProps.events,
    }, () => {
      console.log(this.state.events);
      jQuery(fullCalendar).fullCalendar('refetchEventSources', nextProps.event);
    });
  }

  componentWillUnmount() {
    const { fullCalendar } = this;
    jQuery(fullCalendar).fullCalendar('destroy');
  }

  render() {
    return (

 { this.fullCalendar = calendar; }} />
    );
  }
}

I have addEvent function that adds new event to array and than I pass it to EmployeesCalendar.

In EmployeesCalendar I update events state in componentWillReceiveProps and than pass it to fullcalendar plugin, forcing to update it. But the fullcalendar never updates.

Any suggestions ?

Body:
The refetchEvents method worked for me, but not until I configured events as a function with a callback rather than as an array.

Instead of componentWillReceiveProps, I used componentDidUpdate, which is fired after state or props actually change.  I think that componentWillReceiveProps will work, but it's an earlier event than you need.  It gives you an opportunity to change state, which you don't need to do.

  componentDidMount() {
    const { fullCalendar } = this;
    jQuery(fullCalendar).fullCalendar({
      events: (start, end, timezone, callback) => {
        callback(this.state.events);
      },
    });
  }

  componentDidUpdate(nextProps, nextState) {
    const { fullCalendar } = this;
    jQuery(fullCalendar).fullCalendar('refetchEvents');
  }

According to the FullCalendar doc, "FullCalendar will call this function whenever it needs new event data. This is triggered when the user clicks prev/next or switches views."  It also appears to be triggered when you run refetchEvents.  Maybe rerenderEvents too?  I didn't try that one.


问:
HTML to WordPress
I've never used WordPress.org before. I'm wondering if I can convert this html website that I have to wordpress exactly the same?

https://reporting.pacificamerican.org/pas/

And if this website is a wordpress site, does it means that I don't have to go into the codes if I want to update my content? Because right now with html site it takes more time to update all the contents.

Thank you.

答:
Yes, you can, but looking at the content I wouldn't say it looks like a great idea. Mostly because of how static the current content seems to be.

Pros:

It looks like you are about to add a blog-page. WordPress does make such re-occuring content easy.

It looks like you have repeated the menu on every page. (If you change the menu on one page, then you have to makes changes to all pages as well?). WordPress would help with that and let you use one menu everywhere. But there are also tons of easier methods to accomplish the same thing without WordPress. (For example <?php include 'menu.php';?> using PHP).

Cons:

The "multiple sub-pages in one page" that you are using doesn't play naturally with WordPress. Absolutely possible yes, perhaps not even difficult, but not out-of-the-box for sure.

The time it would take to edit pages would likely not change as drastic as you hope. I believe that the current content looks so static that anyone with a bit HTML/CSS knowledge would rather want to edit those static html files over having to click around in the WordPress admin interface.

The scroll-spy, editing tables and things like the yearly admissions does not come naturally either. I can think of a few dozen ways to solve such things with WordPress, but if you are going to do this work yourself, then the WordPress-conversion will take some effort and the results will not always be as pretty as you might imagine.

You'll definitely take a performance hit over using only static html. (But that is true for any CMS/framework)

My suggestion would be to first look at your current workflow. Perhaps look at an IDE that can upload with a click or on save, have history so you can back up when things break, and predefined snippets that make static content changes easy, (and of course code syntax highlighting!).

What tools are you using now?

Also remember that you are asking on a coding-site. Not many here would opt to use the WordPress editor over simply editing html-files. In fact, I dare to say many here carries a deep grudge after having to work around some specific quirks in the WP editor (aka tinyMCE).

Title: HTML to WordPress


问:
jquery autocomplete: works for first value, how to enable it for next?
I'm using autocomplete so user can easly enter data on inputs, like this:

```<code> <?
$a = new etiqueta(0, '');
$b = $a->autocomplete_etiquetas();
?>
<script type="text/javascript">
    function cargar_autocomplete_etiquetas(){
        $("#tags").autocomplete({
            source: [<? echo $b; ?>]
        });
    }
</script>
</code>```

$a =  $b its an  array  with a result like:  'help','please',i','need','to,'be able to', 'select next item',' with autocomplete';

and i checked the ui documentation, but it doesn't fith with my source method.. any idea?
I'm trying like this (edited with Bugai13 aportation):

```<code> <?
$a = new etiqueta(0, '');
$b = $a->autocomplete_etiquetas();
?>
<script type="text/javascript">
    function cargar_autocomplete_etiquetas(){
    $("#tags").autocomplete({
        source: [<? echo $b; ?>],
        multiple: true,
        multipleSeparator: ", ",
        matchContains: true
    });
}

</script>
</code>```

but i don't know how to do it.. any idea? are .push and .pop functions from the autocomplete? or shall i define, them?

thanks again!

PS: i'm getting adicted to this site!
PS: come on dudes, i think the answer will be very usefull for many people
PS: is it allowed to offer paypal reward?

答:
What does echo $b; print? I would expect you would need something like echo implode(',', $b), or even echo '"' . implode('", "', $b) . '"'; to make this work, if $b really is a PHP array.

Edit: (of course I'm only assuming you're using PHP, but if it <?s like PHP and $s like PHP...)

Body:
I'm using autocomplete so user can easly enter data on inputs, like this:

 <?
$a = new etiqueta(0, '');
$b = $a->autocomplete_etiquetas();
?>

$a =  $b its an  array  with a result like:  'help','please',i','need','to,'be able to', 'select next item',' with autocomplete';

and i checked the ui documentation, but it doesn't fith with my source method.. any idea?
I'm trying like this (edited with Bugai13 aportation):

 <?
$a = new etiqueta(0, '');
$b = $a->autocomplete_etiquetas();
?>

but i don't know how to do it.. any idea? are .push and .pop functions from the autocomplete? or shall i define, them?

thanks again!

PS: i'm getting adicted to this site!
PS: come on dudes, i think the answer will be very usefull for many people
PS: is it allowed to offer paypal reward?


问:
Changing UIPageViewController's page programmatically doesn't update the UIPageControl
In my custom UIPageViewController class:

```<code>- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        self.model = [[BSTCMWelcomingPageViewModel alloc] init];
        self.dataSource = self.model;
        self.delegate = self;

        self.pageControl = [UIPageControl appearance];
        self.pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
        self.pageControl.currentPageIndicatorTintColor = [UIColor blackColor];
    }
    return self;
}
</code>```

Then I programmatically set the current ViewController when a button is hit:

```<code>- (void)scrollToNext
{
    UIViewController *current = self.viewControllers[0];
    NSInteger currentIndex = [self.model indexForViewController:current];
    UIViewController *nextController = [self.model viewControllerForIndex:++currentIndex];
    if (nextController) {
        NSArray *viewControllers = @[nextController];
        // This changes the View Controller, but PageControl doesn't update
        [self setViewControllers:viewControllers
                       direction:UIPageViewControllerNavigationDirectionForward
                        animated:YES
                      completion:nil];
        //Nothing happens!
        [self.pageControl setCurrentPage:currentIndex];

        //Error: _installAppearanceSwizzlesForSetter: Not a setter!
        [self.pageControl updateCurrentPageDisplay];
    }
}
</code>```

If I can't do this with the UIPageControl that "belongs" to my UIPageViewController I will just try to make my own. But it would be nice if this was possible tho!

答: Make sure to set the currentIndex BEFORE you call setViewControllers</p>

Body:
In my custom UIPageViewController class:

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        self.model = [[BSTCMWelcomingPageViewModel alloc] init];
        self.dataSource = self.model;
        self.delegate = self;

        self.pageControl = [UIPageControl appearance];
        self.pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
        self.pageControl.currentPageIndicatorTintColor = [UIColor blackColor];
    }
    return self;
}

Then I programmatically set the current ViewController when a button is hit:

- (void)scrollToNext
{
    UIViewController *current = self.viewControllers[0];
    NSInteger currentIndex = [self.model indexForViewController:current];
    UIViewController *nextController = [self.model viewControllerForIndex:++currentIndex];
    if (nextController) {
        NSArray *viewControllers = @[nextController];
        // This changes the View Controller, but PageControl doesn't update
        [self setViewControllers:viewControllers
                       direction:UIPageViewControllerNavigationDirectionForward
                        animated:YES
                      completion:nil];
        //Nothing happens!
        [self.pageControl setCurrentPage:currentIndex];

        //Error: _installAppearanceSwizzlesForSetter: Not a setter!
        [self.pageControl updateCurrentPageDisplay];
    }
}

If I can't do this with the UIPageControl that "belongs" to my UIPageViewController I will just try to make my own. But it would be nice if this was possible tho!


答: In your case make sure that User class is getting enhanced everytime properly and would suggest you to declare User Class fields separately as Persistent field.</p>

Title: Identifier userName is unresolved (not a static field) <at times>


问:
How to assgin two diffrent url with java script code
Below is a JS code , and i want to redirect user to two different URL - If he enter value in input box 1 so he should redirect to this Default url[https://manage.bagful.com.au/cart.php?a=add&pid=30] else he put more than 1 so this URL [https://manage.bagful.com.au/cart.php?a=add&pid=30&configoption[2]]

Here is the Code:

```<code>$(document).ready(function(){

    document.getElementById("input").addEventListener("keyup", function(event) {
        event.preventDefault();
        if (event.keyCode == 1) {
            var inputvalue = $("#input").val();
            window.location.replace(" https://manage.bagful.com.au/cart.php?a=add&pid=30");
        }
    });

    $('#button').click(function(e) {
        var inputvalue = $("#input").val();
        window.location.replace(" https://manage.bagful.com.au/cart.php?a=add&pid=30&configoption[2]="+inputvalue);
    });
});
</code>```

Please check and suggest the best idea.

答:
Here you go with jsfiddle https://jsfiddle.net/Lfremy6z/1/

$(document).ready(function()
{
$('#submit').click(function(){
    var inputVal = $('input[type="text"]').val();
    if( inputVal == 1){
        window.location.replace("https://manage.bagful.com.au/cart.php?a=add&pid=30");
    }else{
        window.location.replace("https://manage.bagful.com.au/cart.php?a=add&pid=30&configoption[2]=" + inputVal);
    }
});
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" />
<button id="submit" type="submit">Submit</button></code>```

In jsfiddle window.location is not present so I added the code here.

Body:
Below is a JS code , and i want to redirect user to two different URL - If he enter value in input box 1 so he should redirect to this Default url[https://manage.bagful.com.au/cart.php?a=add&pid=30] else he put more than 1 so this URL [https://manage.bagful.com.au/cart.php?a=add&pid=30&configoption[2]]

Here is the Code:

$(document).ready(function(){

    document.getElementById("input").addEventListener("keyup", function(event) {
        event.preventDefault();
        if (event.keyCode == 1) {
            var inputvalue = $("#input").val();
            window.location.replace(" https://manage.bagful.com.au/cart.php?a=add&pid=30");
        }
    });

    $('#button').click(function(e) {
        var inputvalue = $("#input").val();
        window.location.replace(" https://manage.bagful.com.au/cart.php?a=add&pid=30&configoption[2]="+inputvalue);
    });
});

Please check and suggest the best idea.

Body:
Here you go with jsfiddle https://jsfiddle.net/Lfremy6z/1/

$(document).ready(function()
{
$('#submit').click(function(){
    var inputVal = $('input[type="text"]').val();
    if( inputVal == 1){
        window.location.replace("https://manage.bagful.com.au/cart.php?a=add&pid=30");
    }else{
        window.location.replace("https://manage.bagful.com.au/cart.php?a=add&pid=30&configoption[2]=" + inputVal);
    }
});
});

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

<input type="text" />
<button id="submit" type="submit">Submit</button>

In jsfiddle window.location is not present so I added the code here.


问:
Java if else with nested loop
I am having some problem with my java assignment and currently am stuck at the nested if else statement.I am actually trying to get an input age from the user and store in as a variable.After executing my code i am getting error when i run the program.Am i doing this correctly or is there some other way to program this?

Error message that i got

```
    Enter your selection:
    1
    You have selected No.1
    Please enter your age**Exception in thread "main"
    java.lang.IllegalStateException: Scanner closed
    at java.util.Scanner.ensureOpen(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at Assignment.main(Assignment.java:48)**
```

```<code>public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    System.out.println(
       "1. Add player" + "\n" +
       "2.Display transaction" + "\n" +
       "3.Begin the ride");
    System.out.println("");
    System.out.println("Enter your selection: ");
    char selection = sc.findInLine(".").charAt(0);
    sc.close();
    switch(selection)  {
    case '1' :
        System.out.println("You have selected No.1");
        break;
    case '2' :
        System.out.println("You have selected No.2" );
        break;
    case '3' :
        System.out.println("You have selected No.3" );
        break;
    default:
        System.out.println("Please make a selection");
        break;
   }
   if (selection=='1') {
        int age=0;
        System.out.print("Please enter your age");
        age = sc.nextInt();
        while (age<100) {
            age+=age;
        }
    }
    else if (selection=='2') {
        System.out.println("Display daily transaction");
    }
    else if (selection=='3') {
        System.out.println("Begin the ride");
    }
    else {
        System.out.println("Please enter a valid input");
    }
}
</code>```

答:
you can reduce this code to a very good extent, i haven't removed nested-if statements, which you can by moving all execution under case statements.

This program will terminate if option entered is not a number, this can also be improved by reading it as a string and checking is its one of the valid options (map's key set).

```<code>import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;

public class SwitchCase {

    public static Map<Integer, String> options = new LinkedHashMap<Integer, String>();
    static {
        options.put(1, "Add player");
        options.put(2, "Display transaction");
        options.put(3, "Begin the ride");
    }

    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        for (Integer option : options.keySet()) {
            System.out.println(option + ". " + options.get(option));
        }
        System.out.println("Enter your selection: ");
        int selection = sc.nextInt();
        switch (selection) {
        case 1:
        case 2:
        case 3:
            System.out.println("You have selected No." + selection);
            break;
        default:
            System.out.println("Please make a selection");
            break;
        }
        if (selection == 1) {
            int age = 0;
            System.out.print("Please enter your age : ");
            age = sc.nextInt();
            while (age < 100) {
                age += age;
            }
            System.out.println(age);
        } else if (selection == 2) {
            System.out.println(options.get(selection));
        } else if (selection == 3) {
            System.out.println(options.get(selection));
        } else {
            System.out.println("Please enter a valid input!");
        }
    }
}
</code>```

Title: Java if else with nested loop

Body:
I am having some problem with my java assignment and currently am stuck at the nested if else statement.I am actually trying to get an input age from the user and store in as a variable.After executing my code i am getting error when i run the program.Am i doing this correctly or is there some other way to program this?

Error message that i got

    Enter your selection:
    1
    You have selected No.1
    Please enter your age**Exception in thread "main"
    java.lang.IllegalStateException: Scanner closed
    at java.util.Scanner.ensureOpen(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at Assignment.main(Assignment.java:48)**

public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    System.out.println(
       "1. Add player" + "\n" +
       "2.Display transaction" + "\n" +
       "3.Begin the ride");
    System.out.println("");
    System.out.println("Enter your selection: ");
    char selection = sc.findInLine(".").charAt(0);
    sc.close();
    switch(selection)  {
    case '1' :
        System.out.println("You have selected No.1");
        break;
    case '2' :
        System.out.println("You have selected No.2" );
        break;
    case '3' :
        System.out.println("You have selected No.3" );
        break;
    default:
        System.out.println("Please make a selection");
        break;
   }
   if (selection=='1') {
        int age=0;
        System.out.print("Please enter your age");
        age = sc.nextInt();
        while (age<100) {
            age+=age;
        }
    }
    else if (selection=='2') {
        System.out.println("Display daily transaction");
    }
    else if (selection=='3') {
        System.out.println("Begin the ride");
    }
    else {
        System.out.println("Please enter a valid input");
    }
}

Body:
you can reduce this code to a very good extent, i haven't removed nested-if statements, which you can by moving all execution under case statements.

This program will terminate if option entered is not a number, this can also be improved by reading it as a string and checking is its one of the valid options (map's key set).

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;

public class SwitchCase {

    public static Map<Integer, String> options = new LinkedHashMap<Integer, String>();
    static {
        options.put(1, "Add player");
        options.put(2, "Display transaction");
        options.put(3, "Begin the ride");
    }

    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        for (Integer option : options.keySet()) {
            System.out.println(option + ". " + options.get(option));
        }
        System.out.println("Enter your selection: ");
        int selection = sc.nextInt();
        switch (selection) {
        case 1:
        case 2:
        case 3:
            System.out.println("You have selected No." + selection);
            break;
        default:
            System.out.println("Please make a selection");
            break;
        }
        if (selection == 1) {
            int age = 0;
            System.out.print("Please enter your age : ");
            age = sc.nextInt();
            while (age < 100) {
                age += age;
            }
            System.out.println(age);
        } else if (selection == 2) {
            System.out.println(options.get(selection));
        } else if (selection == 3) {
            System.out.println(options.get(selection));
        } else {
            System.out.println("Please enter a valid input!");
        }
    }
}